You should not use su
in a dockerfile, however you should use the USER
instruction in the Dockerfile.
At each stage of the Dockerfile build, a new container is created so any change you make to the user will not persist on the next build stage.
For example:
RUN whoami
RUN su test
RUN whoami
This would never say the user would be test
as a new container is spawned on the 2nd whoami. The output would be root on both (unless of course you run USER beforehand).
If however you do:
RUN whoami
USER test
RUN whoami
You should see root
then test
.
Alternatively you can run a command as a different user with sudo with something like
sudo -u test whoami
But it seems better to use the official supported instruction.
There's a nice article which may answer your question /only it prints the paths instead of collecting them/. Please note that you can experiment with the C++/Python samples in the online IDE.
http://www.geeksforgeeks.org/find-paths-given-source-destination/
Scope isolation, maybe. So that the variables inside the function declaration don't pollute the outer namespace.
Of course, on half the JS implementations out there, they will anyway.
An unsigned char
is an unsigned byte value (0 to 255). You may be thinking of char
in terms of being a "character" but it is really a numerical value. The regular char
is signed, so you have 128 values, and these values map to characters using ASCII encoding. But in either case, what you are storing in memory is a byte value.
The answers here work to open the page in the same browser window/tab.
However, I wanted the page to open in a new window/tab when they click a button. (tab/window decision depends on the user's browser setting)
So here is how it worked to open the page in new tab/window:
<button type="button" onclick="window.open('http://www.example.com/', '_blank');">View Example Page</button>
It doesn't have to be a button, you can use anywhere. Notice the _blank that is used to open in new tab/window.
My solution is to add the ID field as the LAST field in the table, thus bulk insert ignores it and it gets automatic values. Clean and simple ...
For instance, if inserting into a temp table:
CREATE TABLE #TempTable
(field1 varchar(max), field2 varchar(max), ...
ROW_ID int IDENTITY(1,1) NOT NULL)
Note that the ROW_ID
field MUST always be specified as LAST field!
df.loc[df['First season'] > 1990, 'First Season'] = 1
Explanation:
df.loc
takes two arguments, 'row index' and 'column index'. We are checking if the value is greater than 1990 of each row value, under "First season" column and then we replacing it with 1.
Click on SVG's <g>
element in <object>
with click event. Works 100%. Take a look on the nested javascript in <svg>
. Don't forget to insert window.parent.location.href=
if you want to redirect the parent page.
In case anyone wants an alternative method...
If it is the last subdirectory in the path, you can use this one-liner:
cd "c:\directory\subdirectory\filename.exe\..\.." && dir /ad /b /s
This would return the following:
c:\directory\subdirectory
The .... drops back to the previous directory. /ad shows only directories /b is a bare format listing /s includes all subdirectories. This is used to get the full path of the directory to print.
There is an implementation in my TypeScript utilities based on JavaScript GUID generators.
Here is the code:
class Guid {_x000D_
static newGuid() {_x000D_
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
var r = Math.random() * 16 | 0,_x000D_
v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
return v.toString(16);_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
var id = Guid.newGuid();_x000D_
console.log(id);_x000D_
}
_x000D_
Please note the following:
C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.
JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).
Your best bet is to bite the bullet use the DOM Parser - it's the 'right way' to do it. In the long run it'll save you more time than it takes to learn how. Parsing HTML with Regex is known to be unreliable and intolerant of special cases.
Just reciprocating Alex's answer but with jQuery
var currSrc = $("#currentElement").attr("src");
$("#currentElement").attr("src", currSrc);
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
Actually, the best way is the way Google recommends. Double quotes: https://google.github.io/styleguide/htmlcssguide.xml?showone=HTML_Quotation_Marks#HTML_Quotation_Marks
See https://google.github.io/styleguide/htmlcssguide.xml?showone=HTML_Validity#HTML_Validity Quoted Advice from Google: "Using valid HTML is a measurable baseline quality attribute that contributes to learning about technical requirements and constraints, and that ensures proper HTML usage."
Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.
So for your specific example you would need:
<div id="logapp">
<table>
<tbody>
<tr v-repeat="logs">
<td v-html="fail"></td>
<td v-html="type"></td>
<td v-html="description"></td>
<td v-html="stamp"></td>
<td v-html="id"></td>
</tr>
</tbody>
</table>
</div>
SyncToy is a free application from Microsoft with a "Preview" mode for comparing two paths. For example:
You can then choose one of three modes ("Synchronize", "Echo" and "Contribute") to resolve the differences.
Lastly, it comes with SyncToyCmd
for creating and synchronizing folder pairs from the CLI or a Scheduled Task.
You often see the check for definedness so you don't have to deal with the warning for using an undef value (and in Perl 5.10 it tells you the offending variable):
Use of uninitialized value $name in ...
So, to get around this warning, people come up with all sorts of code, and that code starts to look like an important part of the solution rather than the bubble gum and duct tape that it is. Sometimes, it's better to show what you are doing by explicitly turning off the warning that you are trying to avoid:
{
no warnings 'uninitialized';
if( length $name ) {
...
}
}
In other cases, use some sort of null value instead of the data. With Perl 5.10's defined-or operator, you can give length
an explicit empty string (defined, and give back zero length) instead of the variable that will trigger the warning:
use 5.010;
if( length( $name // '' ) ) {
...
}
In Perl 5.12, it's a bit easier because length
on an undefined value also returns undefined. That might seem like a bit of silliness, but that pleases the mathematician I might have wanted to be. That doesn't issue a warning, which is the reason this question exists.
use 5.012;
use warnings;
my $name;
if( length $name ) { # no warning
...
}
Your user.jsp:
<form:form action="profile/proffesional" modelAttribute="PROFESSIONAL">
---
---
</form:form>
In your controller class:
(make it as a meaning full method name..Hear i think you are insert record in DB.)
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String proffessionalDetails(
@ModelAttribute UserProfessionalForm professionalForm,
BindingResult result, Model model) {
UserProfileVO userProfileVO = new UserProfileVO();
userProfileVO.setUser(sessionData.getUser());
userService.saveUserProfile(userProfileVO);
model.addAttribute("PROFESSIONAL", professionalForm);
return "Your Professional Details Updated";
}
Actually this is pretty easy since Windows Vista. Microsoft added the command FORFILES
in your case
forfiles /p c:\directory /m *.xls /c "cmd /c ssconvert @file @fname.xlsx"
the only weird thing with this command is that forfiles automatically adds double quotes around @file and @fname. but it should work anyway
You're close
sudo apt-get install php-xml
Then you need to restart apache so it takes effect
sudo service apache2 restart
The issue here is that Map
has two values (a key and value), while a List
only has one value (an element).
Therefore, the best that can be done is to either get a List
of the keys or the values. (Unless we make a wrapper to hold on to the key/value pair).
Say we have a Map
:
Map<String, String> m = new HashMap<String, String>();
m.put("Hello", "World");
m.put("Apple", "3.14");
m.put("Another", "Element");
The keys as a List
can be obtained by creating a new ArrayList
from a Set
returned by the Map.keySet
method:
List<String> list = new ArrayList<String>(m.keySet());
While the values as a List
can be obtained creating a new ArrayList
from a Collection
returned by the Map.values
method:
List<String> list = new ArrayList<String>(m.values());
The result of getting the List
of keys:
Apple Another Hello
The result of getting the List
of values:
3.14 Element World
Using map and lambda function can produce a list of hex values, which can be printed (or used for other purposes)
>>> s = 'Hello 1 2 3 \x01\x02\x03 :)'
>>> map(lambda c: hex(ord(c)), s)
['0x48', '0x65', '0x6c', '0x6c', '0x6f', '0x20', '0x31', '0x20', '0x32', '0x20', '0x33', '0x20', '0x1', '0x2', '0x3', '0x20', '0x3a', '0x29']
Classes are objects with attributes (state, characteristic) and methods (functions, capacities) that are specific for that object (like the white color and fly powers, respectively, for a duck).
When you create an instance of a class, you can give it some initial personality (state or character like the name and the color of her dress for a newborn). You do this with __init__
.
Basically __init__
sets the instance characteristics automatically when you call instance = MyClass(some_individual_traits)
.
Here's one way:
Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = theDialog.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
Modified from here:MSDN OpenFileDialog.OpenFile
EDIT Here's another way more suited to your needs:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
string filename = theDialog.FileName;
string[] filelines = File.ReadAllLines(filename);
List<Employee> employeeList = new List<Employee>();
int linesPerEmployee = 4;
int currEmployeeLine = 0;
//parse line by line into instance of employee class
Employee employee = new Employee();
for (int a = 0; a < filelines.Length; a++)
{
//check if to move to next employee
if (a != 0 && a % linesPerEmployee == 0)
{
employeeList.Add(employee);
employee = new Employee();
currEmployeeLine = 1;
}
else
{
currEmployeeLine++;
}
switch (currEmployeeLine)
{
case 1:
employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
break;
case 2:
employee.Name = filelines[a].Trim();
break;
case 3:
employee.Address = filelines[a].Trim();
break;
case 4:
string[] splitLines = filelines[a].Split(' ');
employee.Wage = Convert.ToDouble(splitLines[0].Trim());
employee.Hours = Convert.ToDouble(splitLines[1].Trim());
break;
}
}
//Test to see if it works
foreach (Employee emp in employeeList)
{
MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
emp.Name + Environment.NewLine +
emp.Address + Environment.NewLine +
emp.Wage + Environment.NewLine +
emp.Hours + Environment.NewLine);
}
}
}
SELECT Computer.Computer_Name, Application1.Name, Max(Soft.[Version]) as Version1
FROM Application1
inner JOIN Software
ON Application1.ID = Software.Application_Id
cross join Computer
Left JOIN Software_Computer
ON Software_Computer.Computer_Id = Computer.ID and Software_Computer.Software_Id = Software.Id
Left JOIN Software as Soft
ON Soft.Id = Software_Computer.Software_Id
WHERE Computer.ID = 1
GROUP BY Computer.Computer_Name, Application1.Name
Easier solution will be changing this line
ft.replace(R.id.content_frame, A);
to ft.add(R.id.content_frame, A);
And inside your XML layout please use
android:background="@color/white"
android:clickable="true"
android:focusable="true"
Clickable
means that it can be clicked by a pointer device or be tapped by a touch device.
Focusable
means that it can gain the focus from an input device like a keyboard. Input devices like keyboards cannot decide which view to send its input events to based on the inputs itself, so they send them to the view that has focus.
Complementing the existing answers, as these commands are recurrent we can do it in a row. Given we are in the feature branch:
git checkout master && git pull && git checkout - && git merge -
Or add them in an alias:
alias merge_with_master="git checkout master && git pull && git checkout - && git merge -"
listagg
got recently covered by the ISO SQL standard (SQL:2016). As part of that, it also got an on overflow
clause, which is supported by Oracle 12cR2.
LISTAGG(<expression>, <separator> ON OVERFLOW …)
The on overflow
clause supports a truncate
option (as alternative to the default on overflow error
behavior).
ON OVERFLOW TRUNCATE [<filler>] WITH[OUT] COUNT
The optional defaults to three periods (...) and will be added as last element if truncation happens.
If with count is specified and truncation happens, the number of omitted values is put in brackets and appended to the result.
More about listagg
's on overflow
clause: http://modern-sql.com/feature/listagg
I had the problem before, but it was solved. The main problem was that I mistakenly spell the int main() function. Instead of writing int main() I wrote int mian()....Cheers !
While not a Nodejs setting, I suggest you use proxychains which I find rather convenient. It is probably available in your package manager.
After setting the proxy in the config file (/etc/proxychains.conf
for me), you can run proxychains npm start
or proxychains4 npm start
(i.e. proxychains [command_to_proxy_transparently]
) and all your requests will be proxied automatically.
Config settings for me:
These are the minimal settings you will have to append
## Exclude all localhost connections (dbs and stuff)
localnet 0.0.0.0/0.0.0.0
## Set the proxy type, ip and port here
http 10.4.20.103 8080
(You can get the ip of the proxy by using nslookup [proxyurl]
)
To append to an array, just use the +=
operator.
$Target += $TargetObject
Also, you need to declare $Target = @()
before your loop because otherwise, it will empty the array every loop.
It's better if you check visibility like this:
if($('#video-over').is(':visible'))
The difference is not Java-specific, but platform specific.
Historically UNIX-like OSes have used \n
as newline character, some other deprecated OSes have used \r
and Windows OSes have employed \r\n
.
You can format your webpack.config.js like this:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
module.exports = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./entry.js",
output: {
path: __dirname + "/dist",
filename: "library.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};'
And then to build it unminified run (while in the project's main directory):
$ webpack
To build it minified run:
$ NODE_ENV=production webpack
Notes:
Make sure that for the unminified version you change the output file name to library.js
and for the minified library.min.js
so they do not overwrite each other.
I figured out that in my case, my database was in different subnet than the subnet from where i was trying to access the db.
see: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
so you need to add: cursor:pointer;
In your case use:
#more {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
}
This will apply the curser to the element with the ID "more" (can be only used once). So in your HTML use
<input type="button" id="more" />
If you want to apply this to more than one button then you have more than one possibility:
using CLASS
.more {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
}
and in your HTML use
<input type="button" class="more" value="first" />
<input type="button" class="more" value="second" />
or apply to a html context:
input[type=button] {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
}
and in your HTML use
<input type="button" value="first" />
<input type="button" value="second" />
I think you should do it the other way round.
Define your Div
s and have your a href
within each Div
, pointing to different links
I just copied the jre folder to whatever path the message tells me it was missing at, and solved it.
(after editing the JAVA_HOME and editing the eclipse.ini didn't worked (as i probably did something wrong)) (i have no other java applications running so it's not affecting me)
Your model is null
because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:
@foreach (var planVM in Model)
{
@Html.Partial("_partialView", planVM)
}
is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:
<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />
However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:
<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />
That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:
EditorTemplates
folder inside your view's current folder (e.g. if your view is Home\Index.cshtml
, create the folder Home\EditorTemplates
).PlanCompareViewModel.cshtml
.Now, everything you have in your partial view wants to go in that template:
@model PlanCompareViewModel
<div>
@Html.HiddenFor(p => p.PlanID)
@Html.HiddenFor(p => p.CurrentPlan)
@Html.CheckBoxFor(p => p.ShouldCompare)
<input type="submit" value="Compare"/>
</div>
Finally, your parent view is simplified to this:
@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
@Html.EditorForModel()
</div>
}
DisplayTemplates
and EditorTemplates
are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.
For me work like this: 1. Stop mysql: systemctl stop mysqld
Set the mySQL environment option systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"
Start mysql usig the options you just set systemctl start mysqld
Login as root mysql -u root
After login I use FLUSH PRIVILEGES; tell the server to reload the grant tables so that account-management statements work. If i don't do that i receive this error trying to update the password: "Can't find any matching row in the user table"
Why not set ON CASCADE DELETE on Foreign Key patron_info
.pid?
Javascript is pass by value, and which essentially means part
is a copy of the value in the array.
To change the value, access the array itself in your loop.
arr[index] = 'new value';
I faced the problem in VS 2017 out of no where, took my whole day going through 100 of solutions any of these didnt work. I then took my whole solution and started it on different machine having VS 2017 installation.. IT FINALLY WORKED. Than reinstalled VS 2017 on the original one and it started running on that too. I strongly recommend you try your solution on a different machine before wasting much time to debug it, bcz it is a BUG in VS 2017 as it seemed for me, have reported same to VS TEAM. Hope this helps any one in grief. Cheers.
To be clear on the bits vs byte, vs characters.
2**8
possible combinations: 256 combinationsWhen you look at a hex character,
[0-9] + [a-f]
: the full range of 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
2**4
: that means one hex character can store 4 bits in a byte (half a byte).2**8
combinations.[0-9a-f][0-9a-f]
and that represents both halfs of a byte (we call a half-byte a nibble).When you look at a regular single-byte character, (we're totally going to skip multi-byte and wide-characters here)
2**8
range.md5()
could store all that, you'd see all the lowercase letters, all the uppercase letters, all the punctuation and things like ¡°ÀÐàð
, whitespace like (newlines, and tabs), and control characters (which you can't even see and many of which aren't in use).So they're clearly different and I hope that provides the best break down of the differences.
Use, a global variable or property for assigning the value to the textbox, give the value for the variable in another class and assign it to the textbox.text in form class.
While the answer from alireza is correct, it has one gotcha:
You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).
Convert.ToDouble(x) can also have a second parameter that indicates the CultureInfo and when you set it to System.Globalization.CultureInfo InvariantCulture the result will allways be the same.
The author appears to have taken a freemium approach to the font library and provides Black Tie to give different weights to the Font-Awesome library.
Here's one view on the singleton methods:
I have found these various "singleton" methods to be useful for passing a single value to an API that requires a collection of that value. Of course, this works best when the code processing the passed-in value does not need to add to the collection.
Angular uses is for properties generated by the framework. Guess, they are going by the (now defunct) hint provided by the ECMA-262 3.0.
Do just simple thing:
Try width: max-content
to adjust the width of the div by it's content.
<!DOCTYPE html>
<html>
<head>
<style>
div.ex1 {
width:500px;
margin: auto;
border: 3px solid #73AD21;
}
div.ex2 {
width: max-content;
margin: auto;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<div class="ex1">This div element has width 500px;</div>
<br>
<div class="ex2">Width by content size</div>
</body>
</html>
(In an attempt to give a succinct yet complete derivation.)
Every input byte has 8 bits, so for n input bytes we get:
n × 8 input bits
Every 6 bits is an output byte, so:
ceil(n × 8 / 6) = ceil(n × 4 / 3) output bytes
This is without padding.
With padding, we round that up to multiple-of-four output bytes:
ceil(ceil(n × 4 / 3) / 4) × 4 = ceil(n × 4 / 3 / 4) × 4 = ceil(n / 3) × 4 output bytes
See Nested Divisions (Wikipedia) for the first equivalence.
Using integer arithmetics, ceil(n / m) can be calculated as (n + m – 1) div m, hence we get:
(n * 4 + 2) div 3 without padding
(n + 2) div 3 * 4 with padding
For illustration:
n with padding (n + 2) div 3 * 4 without padding (n * 4 + 2) div 3
------------------------------------------------------------------------------
0 0 0
1 AA== 4 AA 2
2 AAA= 4 AAA 3
3 AAAA 4 AAAA 4
4 AAAAAA== 8 AAAAAA 6
5 AAAAAAA= 8 AAAAAAA 7
6 AAAAAAAA 8 AAAAAAAA 8
7 AAAAAAAAAA== 12 AAAAAAAAAA 10
8 AAAAAAAAAAA= 12 AAAAAAAAAAA 11
9 AAAAAAAAAAAA 12 AAAAAAAAAAAA 12
10 AAAAAAAAAAAAAA== 16 AAAAAAAAAAAAAA 14
11 AAAAAAAAAAAAAAA= 16 AAAAAAAAAAAAAAA 15
12 AAAAAAAAAAAAAAAA 16 AAAAAAAAAAAAAAAA 16
Finally, in the case of MIME Base64 encoding, two additional bytes (CR LF) are needed per every 76 output bytes, rounded up or down depending on whether a terminating newline is required.
In your routes.rb :
devise_for :users do
get '/sign_out' => 'devise/sessions#destroy'
get '/log_in' => 'devise/sessions#new'
get '/log_out' => 'devise/sessions#destroy'
get '/sign_up' => 'devise/registrations#new'
get '/edit_profile' => 'devise/registrations#edit'
end
and in your application.html.erb:
<%if user_signed_in?%>
<li><%= link_to "Sign_out", sign_out_path %></li>
<% end %>
I don't know why these are all so complicating.
for most cases, the simple expression ([A-Z]+)
will do the trick
>>> re.sub('([A-Z]+)', r'_\1','CamelCase').lower()
'_camel_case'
>>> re.sub('([A-Z]+)', r'_\1','camelCase').lower()
'camel_case'
>>> re.sub('([A-Z]+)', r'_\1','camel2Case2').lower()
'camel2_case2'
>>> re.sub('([A-Z]+)', r'_\1','camelCamelCase').lower()
'camel_camel_case'
>>> re.sub('([A-Z]+)', r'_\1','getHTTPResponseCode').lower()
'get_httpresponse_code'
To ignore the first character simply add look behind (?!^)
>>> re.sub('(?!^)([A-Z]+)', r'_\1','CamelCase').lower()
'camel_case'
>>> re.sub('(?!^)([A-Z]+)', r'_\1','CamelCamelCase').lower()
'camel_camel_case'
>>> re.sub('(?!^)([A-Z]+)', r'_\1','Camel2Camel2Case').lower()
'camel2_camel2_case'
>>> re.sub('(?!^)([A-Z]+)', r'_\1','getHTTPResponseCode').lower()
'get_httpresponse_code'
If you want to separate ALLCaps to all_caps and expect numbers in your string you still don't need to do two separate runs just use |
This expression ((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))
can handle just about every scenario in the book
>>> a = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')
>>> a.sub(r'_\1', 'getHTTPResponseCode').lower()
'get_http_response_code'
>>> a.sub(r'_\1', 'get2HTTPResponseCode').lower()
'get2_http_response_code'
>>> a.sub(r'_\1', 'get2HTTPResponse123Code').lower()
'get2_http_response123_code'
>>> a.sub(r'_\1', 'HTTPResponseCode').lower()
'http_response_code'
>>> a.sub(r'_\1', 'HTTPResponseCodeXYZ').lower()
'http_response_code_xyz'
It all depends on what you want so use the solution that best suits your needs as it should not be overly complicated.
nJoy!
Looking at the bottom of your wp-config.php file in the wordpress root directory will let you find something like this:
if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/');
For an example file have a look here:
http://core.trac.wordpress.org/browser/trunk/wp-config-sample.php
You can make use of this constant called ABSPATH in other places of your wordpress scripts and in most cases it should point to your wordpress root directory.
The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:
Edit: node-mysql-native is also a pure-Javascript solution.
true
/ false
stringsYYYY-mm-dd HH:ii:ss
stringsX'0fa5'
['a', 'b']
turns into 'a', 'b'
[['a', 'b'], ['c', 'd']]
turns into ('a', 'b'), ('c', 'd')
key = 'val'
pairs. Nested objects are cast to strings.undefined
/ null
are converted to NULL
NaN
/ Infinity
are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.This allows for you to do things like so:
var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
//query.sql returns SELECT * FROM users WHERE id = '5'
});
As well as this:
var post = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
//query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});
Aside from those functions, you can also use the escape functions:
connection.escape(query);
mysql.escape(query);
To escape query identifiers:
mysql.escapeId(identifier);
And as a response to your comment on prepared statements:
From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.
The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:
connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
This changes the query format of the connection so you can use queries like this:
connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");
Search extension in
/etc/php5/apache2/php.ini
This is actually pretty easy in Excel (or any spreadsheet application).
You'll want to use the =CONCATENATE()
function as shown in the formula bar in the following screenshot:
Step 1 involves adding quotes in column B,
Step 2 involves specifying the function and then copying it down column C (by now your spreadsheet should look like the screenshot),
Step 3 (if you need the text outside of the formula) involves copying column C, right-clicking on column D, choosing Paste Special >> Paste Values. Column D should then contain the text that was calculated in column C.
I think, this is the most human approach (with using break from while loop), I explained it's mechanism in comments.
function generateRandomUniqueNumbersArray (limit) {
//we need to store these numbers somewhere
const array = new Array();
//how many times we added a valid number (for if statement later)
let counter = 0;
//we will be generating random numbers until we are satisfied
while (true) {
//create that number
const newRandomNumber = Math.floor(Math.random() * limit);
//if we do not have this number in our array, we will add it
if (!array.includes(newRandomNumber)) {
array.push(newRandomNumber);
counter++;
}
//if we have enought of numbers, we do not need to generate them anymore
if (counter >= limit) {
break;
}
}
//now hand over this stuff
return array;
}
You can of course add different limit (your amount) to the last 'if' statement, if you need less numbers, but be sure, that it is less or equal to the limit of numbers itself - otherwise it will be infinite loop.
You can scale the image with pygame.transform.scale
:
import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))
You can then get the bounding rectangle of picture
with
rect = picture.get_rect()
and move the picture with
rect = rect.move((x, y))
screen.blit(picture, rect)
where screen
was set with something like
screen = pygame.display.set_mode((1600, 900))
To allow your widgets to adjust to various screen sizes, you could make the display resizable:
import os
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(
event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
pygame.display.flip()
call private method using square brackets
Ts file
class Calculate{
private total;
private add(a: number) {
return a + total;
}
}
spect.ts file
it('should return 5 if input 3 and 2', () => {
component['total'] = 2;
let result = component['add'](3);
expect(result).toEqual(5);
});
The accepted answer is too long, other answers didn't work for me. I'm gonna leave this for future purpose.
Dim sKey, bFound
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\SecurityHealth"
with CreateObject("WScript.Shell")
on error resume next ' turn off error trapping
sValue = .regread(sKey) ' read attempt
bFound = (err.number = 0) ' test for success
on error goto 0 ' restore error trapping
end with
If bFound Then
MsgBox = "Registry Key Exist."
Else
MsgBox = "Nope, it doesn't exist."
End If
Here's the list of the Registry Tree, choose your own base on your current task.
HKCR = HKEY_CLASSES_ROOT
HKCU = HKEY_CURRENT_USER
HKLM = HKEY_LOCAL_MACHINE
HKUS = HKEY_USERS
HKCC = HKEY_CURRENT_CONFIG
Using Spring EL:
@Value("#{'${my.list.of.strings}'.split(',')}")
private List<String> myList;
Assuming your properties file is loaded correctly with the following:
my.list.of.strings=ABC,CDE,EFG
You can use the zoom
property. Check this jsfiddle
Q. What is Artifact in maven?
ANS: ARTIFACT is a JAR,(WAR or EAR), but it could be also something else. Each artifact has,
Q.Why does Maven need them?
Ans: Maven is used to make them available for our applications.
Have you tried using JSONArray.getJSONObject(int), and JSONArray.length() to create your for-loop:
for (int i = 0; i < recs.length(); ++i) {
JSONObject rec = recs.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
var line = "<label onclick="alert(1)">aaa</label>";
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
using (html):
<span ng-bind-html="line | unsafe"></span>
==>click `aaa` show alert box
include angular-sanitize.js
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
add ngSanitize
in root angular app
var app = angular.module("app", ["ngSanitize"]);
using (html):
<span ng-bind-html="line"></span>
==>click `aaa` nothing happen
Split-Path $MyInvocation.MyCommand.Path -Parent
Here is my solution to the problem, a bit late perhaps. But it could maybe help others:
// Javascript to enable link to tab
var hash = location.hash.replace(/^#/, ''); // ^ means starting, meaning only match the first hash
if (hash) {
$('.nav-tabs a[href="#' + hash + '"]').tab('show');
}
// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
window.location.hash = e.target.hash;
})
I use Checkstlye plugin for such a purpose. In Checkstyle configuration, I add special regexp rules to detect lines with TABs and then mark such lines as checkstyle ERROR, which is clearly visible in Eclipse editor. Works fine.
Aangular 2 final has updated APIs. They have added many methods for this.
To update the form control from controller do this:
this.form.controls['dept'].setValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
No need to reset the errors
References
https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html
https://toddmotto.com/angular-2-form-controls-patch-value-set-value
Support for interactive graphics is much better in matlab than in R. I hate matlab as a language, but I get jealous when I see how its users can explore data with mouse operations, while I'm busy repeating commands with new values for xlim
etc. Matlab also handles multi-panel plots much better than any of the R methods for the task. Generally, R graphics has a 1960s feel. It's fine for publication, but not the best solution for interactive exploration of data.
I only want to cover second point of the question that is related to performance, because no body else has covered this. Select Into is a lot more faster than insert into, when it comes to tables with large datasets. I prefer select into when I have to read a very large table. insert into for a table with 10 million rows may take hours while select into will do this in minutes, and as for as losing indexes on new table is concerned you can recreate the indexes by query and can still save a lot more time when compared to insert into.
You must use 2 parameters :
android:ellipsize="none"
: the text is not cut on textview width
android:scrollHorizontally="false"
the text wraps on as many lines as necessary
Send the data from the form:
$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
type: "PUT"
url: url
dataType: "script"
data: postData
$domain = "domain.local"
$password = "Passw@rd" | ConvertTo-SecureString -asPlainText -Force
$username = "$domain\Administrator"
$hostname=hostname
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
Add-Computer -DomainName $domain -ComputerName $hostname -NewName alrootca -Credential $credential -Restart
Works for me ^^
You can achieve this using XML notation and the MethodInvokingFactoryBean
. For an example look here.
private static StaticBean staticBean;
public void setStaticBean(StaticBean staticBean) {
StaticBean.staticBean = staticBean;
}
You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.
Note testing can also be more difficult with this approach.
I just came across this error and it was because I was trying to write the build file to a network drive that was not working. Tried again from my desktop and it worked just fine. (You may have to "Clean" the build after you move it. Just choose "Clean all Targets" from the "Build" drop-down menu).
Tobias is correct though, dig into the details on the code by right-clicking it to see what your specific problem is.
If you call daemon() and then daemonize a process, by default the current working directory will change to /
. So if your program is a daemon then you should be looking for a core in /
directory and not in the directory of the binary.
Single statement that works with trailing slash. If you are using IE11 you'll have to polyfill the filter
function.
var name = window.location.pathname
.split("/")
.filter(function (c) { return c.length;})
.pop();
The code commented works as well, just choose which do you prefer
import numpy as np
from PIL import Image
def convert_from_cv2_to_image(img: np.ndarray) -> Image:
# return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
return Image.fromarray(img)
def convert_from_image_to_cv2(img: Image) -> np.ndarray:
# return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
return np.asarray(img)
After doing a lot of things, I upgraded pip
, setuptools
and virtualenv
.
python -m pip install -U pip
pip install -U setuptools
pip install -U virtualenv
I did steps 1, 2 in my virtual environment as well as globally.
Next, I installed the package through pip
and it worked.
FYI, I believe Bjarne Stroustrup is quoted as saying that C-style casts are to be avoided and that you should use static_cast or dynamic_cast if at all possible.
Barne Stroustrup's C++ style FAQ
Take that advice for what you will. I'm far from being a C++ guru.
If you even plan on merging your branch, I highly suggest you look at this:
I hear Subversion 1.5 builds more of the merge tracking in, I have no experience with that. My project is on 1.4.x and svnmerge.py is a life saver!
import re
regex = re.compile("u'2022'",re.UNICODE)
newstring = re.sub(regex, something, yourstring, <optional flags>)
I had the same problem upon launching Visual Studio 2013 Ultimate, and the solutions here didn't work for me. I tried deleting the mentioned folders and starting Visual Studio again, but it didn't work.
However I had other problems too, like Microsoft.visual studio package did not load correctly and also Page '312e8a59-2712-48a1-863e-0ef4e67961fc' not found VS 2012. The latter refers to a message in the Team Explorer window saying "Page 'somenumber' cannot be found".
So I run devenv /setup
on the Visual Studio command prompt with administrative rights. It did the job, and everything is fine now.
I'd suggest a RelativeLayout instead of a FrameLayout.
Assuming that you want to have the TextView always below the ImageView I'd use following layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:src="@drawable/icon"
android:visibility="visible"/>
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_below="@id/imageview"
android:gravity="center"
android:text="@string/hello"/>
</RelativeLayout>
Note that if you set the visibility
of an element to gone
then the space that element would consume is gone whereas when you use invisible
instead the space it'd consume will be preserved.
If you want to have the TextView on top of the ImageView then simply leave out the android:layout_alignParentTop
or set it to false
and on the TextView leave out the android:layout_below="@id/imageview"
attribute. Like this.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="false"
android:layout_centerInParent="true"
android:src="@drawable/icon"
android:visibility="visible"/>
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="@string/hello"/>
</RelativeLayout>
I hope this is what you were looking for.
You would use regex for that in mongo.
e.g:
db.users.find({"name": /^m/})
I came here looking for exporting blob into file with least effort. CLR functions is not something what I'd call least effort. Here described lazier one, using OLE Automation:
declare @init int
declare @file varbinary(max) = CONVERT(varbinary(max), N'your blob here')
declare @filepath nvarchar(4000) = N'c:\temp\you file name here.txt'
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @file; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @filepath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
You'll potentially need to allow to run OA stored procedures on server (and then turn it off, when you're done):
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
LINQ doesn't prohibit the use of stored procedures. I've used mixed mode with LINQ-SQL and LINQ-storedproc. Personally, I'm glad I don't have to write the stored procs....pwet-tu.
In Javascript I would use /.*_/
, meaning: match everything until _ (including)
Example:
console.log( 'hello_world'.replace(/.*_/,'') ) // 'world'
The gitlog-to-changelog
script comes in handy to generate a GNU-style ChangeLog
.
As shown by gitlog-to-changelog --help
, you may select the commits used to generate a ChangeLog
file using either the option --since
:
gitlog-to-changelog --since=2008-01-01 > ChangeLog
or by passing additional arguments after --
, which will be passed to git-log
(called internally by gitlog-to-changelog
):
gitlog-to-changelog -- -n 5 foo > last-5-commits-to-branch-foo
For instance, I am using the following rule in the top-level Makefile.am
of one of my projects:
.PHONY: update-ChangeLog
update-ChangeLog:
if test -d $(srcdir)/.git; then \
$(srcdir)/build-aux/gitlog-to-changelog \
--format='%s%n%n%b%n' --no-cluster \
--strip-tab --strip-cherry-pick \
-- $$(cat $(srcdir)/.last-cl-gen).. \
>ChangeLog.tmp \
&& git rev-list -n 1 HEAD >.last-cl-gen.tmp \
&& (echo; cat $(srcdir)/ChangeLog) >>ChangeLog.tmp \
&& mv -f ChangeLog.tmp $(srcdir)/ChangeLog \
&& mv -f .last-cl-gen.tmp $(srcdir)/.last-cl-gen \
&& rm -f ChangeLog.tmp; \
fi
EXTRA_DIST += .last-cl-gen
This rule is used at release time to update ChangeLog
with the latest not-yet-recorded commit messages. The file .last-cl-gen
contains the SHA1 identifier of the latest commit recorded in ChangeLog
and is stored in the Git repository. ChangeLog
is also recorded in the repository, so that it can be edited (e.g. to correct typos) without altering the commit messages.
// These are three very simple and concise answers:
function fun() {
console.log(this.prop1, this.prop2, this.prop3);
}
let obj = { prop1: 'one', prop2: 'two', prop3: 'three' };
let bound = fun.bind(obj);
setTimeout(bound, 3000);
// or
function funOut(par1, par2, par3) {
return function() {
console.log(par1, par2, par3);
}
};
setTimeout(funOut('one', 'two', 'three'), 5000);
// or
let funny = function(a, b, c) { console.log(a, b, c); };
setTimeout(funny, 2000, 'hello', 'worldly', 'people');
$(function() {
$('.button').click(function() {
$(this).toggleClass('active');
$('.yourclass').toggle("slide", {direction: "right"}, 1000);
});
});
GetFile should be closing the file (or opening it within a using). Then you can delete the file after conversion to bytes-- the download will be done on that byte buffer.
byte[] GetFile(string s)
{
byte[] data;
using (System.IO.FileStream fs = System.IO.File.OpenRead(s))
{
data = new byte[fs.Length];
int br = fs.Read(data, 0, data.Length);
if (br != fs.Length)
throw new System.IO.IOException(s);
}
return data;
}
So in your download method...
byte[] fileBytes = GetFile(file);
// delete the file after conversion to bytes
System.IO.File.Delete(file);
// have the file download dialog only display the base name of the file return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(file));
In my case build 1 was installed correctly in my mobile using the signed APK (also from Google Play Store). But when I update the application with build 2 for first time, I had an issue installing it with the signed APK as I got "There was a problem parsing the package".
I tried several methods as specified above. But did not work.
After some time, I rerun the commands
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-key.keystore app-release-unsigned.apk myappkeyalias
zipalign -v 4 app-release-unsigned.apk MyApp.apk
and surprisingly, it worked.
It seems sometimes the APK built might be corrupt. So, Re-running jarsigner and zipalign commands resolved my issue.
This solves the problem on my end.
var files = sftp.ListDirectory(remoteVendorDirectory).Where(f => !f.IsDirectory);
foreach (var file in files)
{
var filename = $"{LocalDirectory}/{file.Name}";
if (!File.Exists(filename))
{
Console.WriteLine("Downloading " + file.FullName);
var localFile = File.OpenWrite(filename);
sftp.DownloadFile(file.FullName, localFile);
}
}
If the above solution doesn't work, check to see if you have $(LibraryPath) in Properties->VC++ Directories->Library Directories. If you are missing it, try adding it.
OK, you basically need to pass the action to the button and call it when click happens, it doesn't need to be inside a from, you can use HTML onclick
on button to trigger it when the button get clicked...
<button id="my-button" onclick="location.href='@Url.Action("YourActionName", "YourControllerName")'">Submit</button>
You can try to upload it to google docs, and download it as HTML.
Change the property WindowState
to System.Windows.Forms.FormWindowState.Maximized
, in some cases if the older answers doesn't works.
So the window will be maximized, and the other parts are in the other answers.
This is what helped me:
Create a new branch with the existing one. Let's call the existing one branch_old
and new as branch_new
.
Reset branch_new
to a stable state, when you did not have any problem commit at all.
For example, to put it at your local master's level do the following:
git reset —hard master git push —force origin
cherry-pick
the commits from branch_old
into branch_new
git push
I came here looking for making an input that's actually multiple lines. Turns out I didn't want an input, I wanted a textarea. You can set height or line-height as other answers specify, but it'll still just be one line of a textbox. If you want actual multiple lines, use a textarea instead. The following is an example of a 3-row textarea with a width of 500px (should be a good part of the page, not necessary to set this and will have to change it based on your requirements).
<textarea name="roleExplanation" style="width: 500px" rows="3">This role is for facility managers and holds the highest permissions in the application.</textarea>
Only for Linux: One-liner for the RAM usage with only stdlib dependency:
import os
tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])
edit: specified solution OS dependency
Matthew Brindley, your code worked very good for some website I needed (with login), but I needed to change to HttpWebRequest
and HttpWebResponse
otherwise I get a 404 Bad Request from the remote server. Also I would like to share my workaround using your code, and is that I tried it to login to a website based on moodle, but it didn't work at your step "GETting the page behind the login form" because when successfully POSTing the login, the Header 'Set-Cookie'
didn't return anything despite other websites does.
So I think this where we need to store cookies for next Requests, so I added this.
To the "POSTing to the login form" code block :
var cookies = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookies;
And To the "GETting the page behind the login form" :
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(resp.Cookies);
getRequest.Headers.Add("Cookie", cookieHeader);
Doing this, lets me Log me in and get the source code of the "page behind login" (website based moodle) I know this is a vague use of the CookieContainer
and HTTPCookies because we may ask first is there a previously set of cookies saved before sending the request to the server. This works without problem anyway, but here's a good info to read about WebRequest
and WebResponse
with sample projects and tutorial:
Retrieving HTTP content in .NET
How to use HttpWebRequest and HttpWebResponse in .NET
Do not use >
; it messes up the character encoding. Use:
Get-Content files.* | Set-Content newfile.file
<div class="container-fluid login-container">
<div class="row">
<form (ngSubmit)="login('da')">
<div class="col-md-4">
<div class="login-text">
Login
</div>
<div class="form-signin">
<input type="text" class="form-control" placeholder="Email" required>
<input type="password" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="col-md-4">
<div class="login-go-div">
<input type="image" src="../../../assets/images/svg/login-go-initial.svg" class="login-go"
onmouseover="this.src='../../../assets/images/svg/login-go.svg'"
onmouseout="this.src='../../../assets/images/svg/login-go-initial.svg'"/>
</div>
</div>
</form>
</div>
</div>
This is the working code for it.
if (Request.Headers["XYZComponent"].Count() > 0)
... will attempted to count the number of characters in the returned string, but if the header doesn't exist it will return NULL, hence why it's throwing an exception. Your second example effectively does the same thing, it will search through the collection of Headers and return NULL if it doesn't exist, which you then attempt to count the number of characters on:
Use this instead:
if(Request.Headers["XYZComponent"] != null)
Or if you want to treat blank or empty strings as not set then use:
if((Request.Headers["XYZComponent"] ?? "").Trim().Length > 0)
The Null Coalesce operator ?? will return a blank string if the header is null, stopping it throwing a NullReferenceException.
A variation of your second attempt will also work:
if (Request.Headers.AllKeys.Any(k => string.Equals(k, "XYZComponent")))
Edit: Sorry didn't realise you were explicitly checking for the value true:
bool isSet = Boolean.TryParse(Request.Headers["XYZComponent"], out isSet) && isSet;
Will return false if Header value is false, or if Header has not been set or if Header is any other value other than true or false. Will return true is the Header value is the string 'true'
In my situation, some pods were out of date after I updated my OS. Here's what fixed it:
In terminal:
cd /Users/quaisafzali/Desktop/AppFolder/Application/
pod install
Then, open your project in Xcode and Clean it (Cmd+Shift+K), then Build/Run.
This worked for me, hope it helps some of you!
In front-end JavaScript/HTML, you can load a binary file as an image, you do not have to convert to base64:
<img src="http://engci.nabisco.com/artifactory/repo/folder/my-image">
my-image is a binary image file. This will load just fine.
None of the above solutions worked for me. But this did:
myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));
var stringToSplit = "0, 10, 20, 30, 100, 200";
// To parse your string
var elements = test.Split(new[]
{ ',' }, System.StringSplitOptions.RemoveEmptyEntries);
// To Loop through
foreach (string items in elements)
{
// enjoy
}
There are solutions here that will work, but I don't see anyone explaining what is actually happening here, so even though this is 2 years old I'll explain it.
There is nothing "wrong" with the onclientclick javascript you are adding. The problem is that asp.net is adding it's on onclick stuff to run AFTER whatever code you put in there runs.
So for example this ASPX:
<asp:Button ID="btnDeny" runat="server" CommandName="Deny" Text="Mark 'Denied'" OnClientClick="return confirm('Are you sure?');" />
is turned into this HTML when rendered:
<input name="rgApplicants$ctl00$ctl02$ctl00$btnDeny" id="rgApplicants_ctl00_ctl02_ctl00_btnDeny"
onclick="return confirm('Are you sure?');__doPostBack('rgApplicants$ctl00$ctl02$ctl00$btnDeny','')" type="button" value="Mark 'Denied'" abp="547">
If you look closely, the __doPostBack stuff will never be reached, because the "confirm" will always return true/false before __doPostBack is reached.
This is why you need to have the confirm only return false and not return when the value is true. Technically, it doesn't matter if it returns true or false, any return in this instance would have the effect of preventing the __doPostBack from being called, but for convention I would leave it so that it returns false when false and does nothing for true.
You can find Module Pattern JavaScript here http://www.sga.su/module-pattern-javascript/
For each works with JQuery as in
$(<selector>).each(function() {
//this points to item
alert('<msg>');
});
JQuery also, for a popup, has in the UI library a dialog widget: http://jqueryui.com/demos/dialog/
Check it out, works really well.
HTH.
There are a lot of answers here, so let me add another:
import json
from typing import List
def dedup_dicts(items: List[dict]):
dedupped = [ json.loads(i) for i in set(json.dumps(item, sort_keys=True) for item in items)]
return dedupped
items = [
{'id': 1, 'name': 'john', 'age': 34},
{'id': 1, 'name': 'john', 'age': 34},
{'id': 2, 'name': 'hanna', 'age': 30},
]
dedup_dicts(items)
You are using older MySql version. Update your myqsl to 5.6.5+ it will work.
I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:
apt-get install -y --no-install-recommends python
And I should not have included the --no-install-recommends
flag:
apt-get install -y python
The 500 (internal server error)
means something went wrong on the server's side. It could be several things, but I would start by verifying that the URL and parameters are correct. Also, make sure that whatever handles the request is expecting the request as a GET and not a POST.
One useful way to learn more about what's going on is to use a tool like Fiddler which will let you watch all HTTP requests and responses so you can see exactly what you're sending and the server is responding with.
If you don't have a compelling reason to write your own Ajax code, you would be far better off using a library that handles the Ajax interactions for you. jQuery is one option.
I think you're looking for the ndenumerate.
>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
... print x,y
...
0 0
0 1
1 0
1 1
2 0
2 1
Regarding the performance. It is a bit slower than a list comprehension.
X = np.zeros((100, 100, 100))
%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop
%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop
If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate
, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords
attribute of the flat iterator.
a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop
It is very simple with colorama, just do this:
import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")
And here is the running result in Python3 REPL:
And call this to reset the color settings:
print(Style.RESET_ALL)
To avoid printing an empty line write this:
print(f"{Fore.BLUE}Hello World{Style.RESET_ALL}")
You can use the UpdateProgress control:
Your local branch likely has modifications to it you want to discard. To do this, you'll need to use git reset
to reset the branch head to the last spot that you diverged from the upstream repo's branch. Use git branch -v
to find the sha1 id of the upstream branch, and reset your branch it it using git reset SHA1ID
. Then you should be able to do a git checkout
to discard the changes it left in your directory.
Note: always do this on a backed-up repo. That way you can assure you're self it worked right. Or if it didn't, you have a backup to revert to.
In my case, I found that size of Writer have to matched with the frame size both from camera or files. So that I read the frame size first and apply to writer setting as below.
(grabbed, frame) = camera.read()
fshape = frame.shape
fheight = fshape[0]
fwidth = fshape[1]
print fwidth , fheight
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (fwidth,fheight))
In my case where I wanted to have something like this:
I had to follow the same thing as suggested by @Mdlc but probably slightly simpler (targeting only >= 21):
//kotlin
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val realSize = Point()
windowManager.defaultDisplay.getRealSize(realSize);
val usableRect = Rect()
windowManager.defaultDisplay.getRectSize(usableRect)
Toast.makeText(this, "Usable Screen: " + usableRect + " real:"+realSize, Toast.LENGTH_LONG).show()
window.decorView.setPadding(usableRect.left, usableRect.top, realSize.x - usableRect.right, realSize.y - usableRect.bottom)
It works on landscape too:
Edit The above solution does not work correctly in multi-window mode where the usable rectangle is not smaller just due to the navigation bar but also because of custom window size. One thing that I noticed is that in multi-window the navigation bar is not hovering over the app so even with no changes to DecorView padding we have the correct behaviour:
Note the difference between how navigation bar is hovering over the bottom of the app in these to scenarios. Fortunately, this is easy to fix. We can check if app is multi window. The code below also includes the part to calculate and adjust the position of toolbar (full solution: https://stackoverflow.com/a/14213035/477790)
// kotlin
// Let the window flow into where window decorations are
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
// calculate where the bottom of the page should end up, considering the navigation bar (back buttons, ...)
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val realSize = Point()
windowManager.defaultDisplay.getRealSize(realSize);
val usableRect = Rect()
windowManager.defaultDisplay.getRectSize(usableRect)
Toast.makeText(this, "Usable Screen: " + usableRect + " real:" + realSize, Toast.LENGTH_LONG).show()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N || !isInMultiWindowMode) {
window.decorView.setPadding(usableRect.left, usableRect.top, realSize.x - usableRect.right, realSize.y - usableRect.bottom)
// move toolbar/appbar further down to where it should be and not to overlap with status bar
val layoutParams = ConstraintLayout.LayoutParams(appBarLayout.layoutParams as ConstraintLayout.LayoutParams)
layoutParams.topMargin = getSystemSize(Constants.statusBarHeightKey)
appBarLayout.layoutParams = layoutParams
}
Result on Samsung popup mode:
Best solution end of 2020:
Just download Windows 10 SDK from Microsoft here:
https://go.microsoft.com/fwlink/?LinkID=698771
In setup, choose only Windows App Certification App (it's only 120 MB)
You can find signtool.exe here:
%PROGRAMFILES(X86)%\Windows Kits\10\bin\x64
Cheers!
Try selecting send and download
instead of send
when you make the request. (the blue button)
https://www.getpostman.com/docs/responses
"For binary response types, you should select Send and download
which will let you save the response to your hard disk. You can then view it using the appropriate viewer."
You can use timexe
It's simple to use, light weight, has no dependencies, has an improved syntax over cron, with a resolution in milliseconds and works in the browser.
Install:
npm install timexe
Use:
var timexe = require('timexe');
var res = timexe("* * * 15 30", function(){ console.log("It's now 3:30 pm"); });
(I'm the author)
cd myapp/trunk
svn commit -m "commit message" page1.html
For more information, see:
svn commit --help
I also recommend this free book, if you're just getting started with Subversion.
you can do it this way
private String GET(String url, Map<String, String> header) throws IOException {
Headers headerbuild = Headers.of(header);
Request request = new Request.Builder().url(url).headers(headerbuild).
build();
Response response = client.newCall(request).execute();
return response.body().string();
}
i think that is the solution
ArrayList<table> libel = new ArrayList<table>();
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
String hql = "FROM table ";
org.hibernate.Query query = s.createQuery(hql);
libel= (ArrayList<table>) query.list();
Iterator it = libel.iterator();
while(it.hasNext()) {
table cat = (table) it.next();
cat.getLibCat();//table colonm getter
combobox.addItem(cat.getLibCat());
}
s.getTransaction().commit();
s.close();
sf.close();
} catch (Exception e) {
System.out.println("Exception in getSelectedData::"+e.getMessage());
It works :
For security reasons on Firefox and Opera, you can't fire the click on file input, but you can simulate with MouseEvents :
<script>
click=function(element){
if(element!=null){
try {element.click();}
catch(e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
element.dispatchEvent(evt);
}
}
};
</script>
<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">
You could also use an ArrayObject, for example:
<?php
$arr = array("test",
array("one"=>1,"two"=>2,"three"=>3),
array("one"=>1,"two"=>2,"three"=>3)
);
$o = new ArrayObject($arr);
echo $o->offsetGet(2)["two"],"\n";
foreach ($o as $key=>$val){
if (is_array($val)) {
foreach($val as $k => $v) {
echo $k . ' => ' . $v,"\n";
}
}
else
{
echo $val,"\n";
}
}
?>
//Output:
2
test
one => 1
two => 2
three => 3
one => 1
two => 2
three => 3
May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.
var obj = [];
var elems = $("input[class=email]");
for (i = 0; i < elems.length; i += 1) {
var id = this.getAttribute('title');
var email = this.value;
tmp = {
'title': id,
'email': email
};
obj.push(tmp);
}
Adding a category to UIColor the following way will make it available to you anytime you need it or even change its definition accross your code:
@interface UIColor (iOS7Colors)
+ (instancetype)iOS7blueColor;
@end
@implementation UIColor (SpecialColors)
+ (instancetype)iOS7blueColor;
{
return [UIColor colorWithRed:0.0f green:0.22f blue:122.0/255.0 alpha:1.0f];
}
Once you import the Category in your code you can call the color by using:
UIColor *myBlueColor = [UIColor iOSblueColor];
You could probably use an inheritance structure although the more I played with this the dirtier I felt.
class AnimalEnum:
@classmethod
def verify(cls, other):
return issubclass(other.__class__, cls)
class Dog(AnimalEnum):
pass
def do_something(thing_that_should_be_an_enum):
if not AnimalEnum.verify(thing_that_should_be_an_enum):
raise OhGodWhy
Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.
The opposite is a much better strategy. If you have minSdkVersion
to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi
or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi
at all.
This is probably why the Android NDK doesn't even support armeabi
anymore as per revision r17b. [source]
From Django 1.8,
from django.db.models.functions import Length
Name.objects.annotate(alias_length=Length('alias')).filter(alias_length__gt=0)
To iterate over all the key-value pairs in a table you can use pairs
:
for k, v in pairs(arr) do
print(k, v[1], v[2], v[3])
end
outputs:
pears 2 p green
apples 0 a red
oranges 1 o orange
Edit: Note that Lua doesn't guarantee any iteration order for the associative part of the table. If you want to access the items in a specific order, retrieve the keys from arr
and sort it. Then access arr
through the sorted keys:
local ordered_keys = {}
for k in pairs(arr) do
table.insert(ordered_keys, k)
end
table.sort(ordered_keys)
for i = 1, #ordered_keys do
local k, v = ordered_keys[i], arr[ ordered_keys[i] ]
print(k, v[1], v[2], v[3])
end
outputs:
apples a red 5
oranges o orange 12
pears p green 7
Had the same issue, a 404 response for the web api controllers when served from the IIS but everything worked fine from VS2010. None of the above solutions worked for me. Eventually I found that the problem was that we added WSE 3.0 support for the application and the Microsoft.Web.Services3 dll was missing in the application's /bin directory. Weird, but after copying the dll, the route mapping started to work.
You can get free Virtual Machine and many more things online for 3 months provided by Microsoft Azure. I guess you need VPN for learning purpose. For that it would suffice.
<EditText android:id="@+id/EditText02" android:layout_width="120dp"
android:layout_height="wrap_content" android:lines="5" android:layout_centerInParent="true"
android:gravity="top|left" android:inputType="textMultiLine"
android:scrollHorizontally="false" android:minWidth="10.0dip"
android:maxWidth="180dip" />
it will work
Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security
. Your JAVA_HOME should always be ../JAVA/JDK
.
In the Tools -> Visual Studio Options Dialog -> Debugging -> Check the "Redirect All Output Window Text to the Immediate Window".
I've taked the solution of @AZ_ and converted it in a kotlin extension function:
So copy this in your code:
@SuppressLint("ClickableViewAccessibility")
fun EditText.setDrawableRightTouch(setClickListener: () -> Unit) {
this.setOnTouchListener(View.OnTouchListener { _, event ->
val DRAWABLE_LEFT = 0
val DRAWABLE_TOP = 1
val DRAWABLE_RIGHT = 2
val DRAWABLE_BOTTOM = 3
if (event.action == MotionEvent.ACTION_UP) {
if (event.rawX >= this.right - this.compoundDrawables[DRAWABLE_RIGHT].bounds.width()
) {
setClickListener()
return@OnTouchListener true
}
}
false
})
}
You can use it just calling the setDrawableRightTouch
function on your EditText
:
yourEditText.setDrawableRightTouch {
//your code
}
Using the RESTORE DATABASE
command most likely. bak
is a common extension used for a database backup file. You'll find documentation for this command on MSDN.
The most simple what I've found to get the XPath for a particular Element is to install FireBug extension for Firefox go to the site/webpage press F12 to bring up firebug; right select and right click the element on the page that you want to query and select "Inspect Element" Firebug will select the element in its IDE then right click the Element in Firebug and choose "Copy XPath" this function will give you the exact XPath Query you need to get the element you want using HTML Agility Library.
Your vncserver have a configuration file somewher that set the display number. To do it automaticaly, one solution is to parse this file, extract the number and set it correctly. A simpler (better) is to have this display number set in a config script and use it in both your VNC server config and in your init scripts.
This method is much faster. You can only tel when placing a lot of files in a directory. My A:\ external hard drive contains almost 1 terabit so it makes a big difference when dealing with a lot of files.
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo("A:\\");
FullDirList(di, "*");
Console.WriteLine("Done");
Console.Read();
}
static List<FileInfo> files = new List<FileInfo>(); // List that will hold the files and subfiles in path
static List<DirectoryInfo> folders = new List<DirectoryInfo>(); // List that hold direcotries that cannot be accessed
static void FullDirList(DirectoryInfo dir, string searchPattern)
{
// Console.WriteLine("Directory {0}", dir.FullName);
// list the files
try
{
foreach (FileInfo f in dir.GetFiles(searchPattern))
{
//Console.WriteLine("File {0}", f.FullName);
files.Add(f);
}
}
catch
{
Console.WriteLine("Directory {0} \n could not be accessed!!!!", dir.FullName);
return; // We alredy got an error trying to access dir so dont try to access it again
}
// process each directory
// If I have been able to see the files in the directory I should also be able
// to look at its directories so I dont think I should place this in a try catch block
foreach (DirectoryInfo d in dir.GetDirectories())
{
folders.Add(d);
FullDirList(d, searchPattern);
}
}
By the way I got this thanks to your comment Jim Mischel
Try resetting your network settings
Settings -> General -> Reset -> Reset Network Settings
And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".
http://support.apple.com/kb/ts2529
This one worked for me.
You can do it for arbitrary refs. This is how to move a branch pointer:
git update-ref -m "reset: Reset <branch> to <new commit>" refs/heads/<branch> <commit>
where -m
adds a message to the reflog for the branch.
The general form is
git update-ref -m "reset: Reset <branch> to <new commit>" <ref> <commit>
You can pick nits about the reflog message if you like - I believe the branch -f
one is different from the reset --hard
one, and this isn't exactly either of them.
My answer is not about static parent-child layout, its about animations.
I was doing an svg demo today, and i needed svg to be inside div (because svg is created with parent's div width and height, to animate the path around), and this parent div needed to be invisible during svg path animation (and then this div was supposed to animate opacity from 0 to 1
, it's the most important part). And because parent div with opacity: 0
was hiding my svg, i came across this hack with visibility
option (child with visibility: visible
can be seen inside parent with visibility: hidden
):
.main.invisible .test {
visibility: hidden;
}
.main.opacity-zero .test {
opacity: 0;
transition: opacity 0s !important;
}
.test { // parent div
transition: opacity 1s;
}
.test-svg { // child svg
visibility: visible;
}
And then, in js, you removing .invisible
class with timeout function, adding .opacity-zero
class, trigger layout with something like whatever.style.top;
and removing .opacity-zero
class.
var $main = $(".main");
setTimeout(function() {
$main.addClass('opacity-zero').removeClass("invisible");
$(".test-svg").hide();
$main.css("top");
$main.removeClass("opacity-zero");
}, 3000);
Better to check this demo http://codepen.io/suez/pen/54bbb2f09e8d7680da1af2faa29a0aef?editors=011
Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:
<
the start of a tag.>
the end of a tag."
the start and end of an attribute value.'
the alternative start and end of an attribute value.&
the start of an entity (which ends with ;
).In case of <
, the XML parser is implicitly looking for the tag name and the end tag >
. However, in your particular case, you were using <
as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:
The content of elements must consist of well-formed character data or markup.
In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The <
must be escaped as <
.
So, essentially, the
for (var i = 0; i < length; i++) {
must become
for (var i = 0; i < length; i++) {
to make it XML-valid.
However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:
<h:outputScript>
<![CDATA[
// ...
]]>
</h:outputScript>
The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".
But, much better is to just put the JS code in its own JS file which you include by <script src>
, or in JSF terms, the <h:outputScript>
.
<h:outputScript name="functions.js" target="head" />
This way you don't need to worry about XML-special characters in your JS code. Additional advantage is that this gives the browser the opportunity to cache the JS file so that average response size is smaller.
bootstrap.yml
or bootstrap.properties
It's only used/needed if you're using Spring Cloud and your application's configuration is stored on a remote configuration server (e.g. Spring Cloud Config Server).
From the documentation:
A Spring Cloud application operates by creating a "bootstrap" context, which is a parent context for the main application. Out of the box it is responsible for loading configuration properties from the external sources, and also decrypting properties in the local external configuration files.
Note that the bootstrap.yml
or bootstrap.properties
can contain additional configuration (e.g. defaults) but generally you only need to put bootstrap config here.
Typically it contains two properties:
spring.cloud.config.uri
)spring.application.name
)Upon startup, Spring Cloud makes an HTTP call to the config server with the name of the application and retrieves back that application's configuration.
application.yml
or application.properties
Contains standard application configuration - typically default configuration since any configuration retrieved during the bootstrap process will override configuration defined here.
The code is
document.addEventListener('keydown', function(event){
alert(event.keyCode);
} );
This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)
I actually found a better way using the jQuery approach
var box = {
config:{
color: 'red'
},
init:function(config){
$.extend(this.config,config);
}
};
var myBox = box.init({
color: blue
});
If you dont have a id or seed, like its its for a values list in insert:
REPLACE(RAND(), '.', '')
according to this link: http://www.authorcode.com/how-to-check-file-permission-to-write-in-c/
it's easier to use existing class SecurityManager
string FileLocation = @"C:\test.txt";
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, FileLocation);
if (SecurityManager.IsGranted(writePermission))
{
// you have permission
}
else
{
// permission is required!
}
but it seems it's been obsoleted, it is suggested to use PermissionSet instead.
[Obsolete("IsGranted is obsolete and will be removed in a future release of the .NET Framework. Please use the PermissionSet property of either AppDomain or Assembly instead.")]
for i in range(11):
string = "string{0}".format(i)
What you did (range[1,10]
) is
a[3]
) or a slice (a[3:5]
) of a list, [1,10]
is invalid, and range(1,10)
is [1, 2, 3, 4, 5, 6, 7, 8, 9]
, and you seem to want [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
And string = "string" + i
is a TypeError since you can't add an integer to a string (unlike JavaScript).
Look at the documentation for Python's new string formatting method, it is very powerful.
double value = 3.4555;
String value1 = String.format("% .3f", value) ;
String value2 = value1.substring(0, value1.length() - 1);
System.out.println(value2);
double doublevalue= Double.valueOf(value2);
System.out.println(doublevalue);
I have tested it. It works fine.
.row.vdivide [class*='col-']:not(:last-child):after {
background: #e0e0e0;
width: 1px;
content: "";
display:block;
position: absolute;
top:0;
bottom: 0;
right: 0;
min-height: 70px;
}
<div class="container">
<div class="row vdivide">
<div class="col-sm-3 text-center"><h1>One</h1></div>
<div class="col-sm-3 text-center"><h1>Two</h1></div>
<div class="col-sm-3 text-center"><h1>Three</h1></div>
<div class="col-sm-3 text-center"><h1>Four</h1></div>
</div>
</div>
An abstract function is "just" a signature, without an implementation. It is used in an interface to declare how the class can be used. It must be implemented in one of the derived classes.
Virtual function (method actually), is a function you declare as well, and should implemented in one of the inheritance hierarchy classes.
The inherited instances of such class, inherit the implementation as well, unless you implement it, in a lower hierarchy class.
I use following code for get different result from condition That worked for me.
Select A.column, B.column
FROM TABLE1 A
INNER JOIN
TABLE2 B
ON A.Id = (case when (your condition) then b.Id else (something) END)
It is a basic sequence that display or get a output of 1 1 2 3 5 8 it is a sequence that the sum of previous number the current number will be display next.
Try to watch link below Java Recursive Fibonacci sequence Tutorial
public static long getFibonacci(int number){
if(number<=1) return number;
else return getFibonacci(number-1) + getFibonacci(number-2);
}
Click Here Watch Java Recursive Fibonacci sequence Tutorial for spoon feeding
<select formControlName="preferredBankAccountId" class="form-control">
<option *ngFor="let item of societyAccountDtos" [value]="item.societyAccountId" >
{{item.nickName}}
</option>
</select>
In the Component:
this.formGroup.patchValue({
preferredBankAccountId: object_id_to_be_pre_selected
});
You can also give this value where you initialize your formGroup or later,depending on your requirement.
You can do this by using [(ngModel)] binding also where you don't have to initialize your formControl.
<select [(ngModel)]="matchedCity" formControlName="city" class="form-control input-sm">
<option *ngFor="let city of cities" [ngValue]="city">{{city.cityName}}</option>
</select>
Here, matchedCity is one of object within cities.
In homebrew the android-sdk
has migrated from homebrew/core
to homebrew/cask
.
brew tap homebrew/cask
and install android-sdk
using
brew cask install android-sdk
You will have to add the ANDROID_HOME
to profile (.zshrc or .bashrc)
export ANDROID_HOME=/usr/local/share/android-sdk
If you prefer otherwise, copy the package to
~/opt/local/android-sdk-mac
In R2013b or later you can use a table:
>> table = readtable('myfile.txt','Delimiter',';','ReadVariableNames',false)
>> table =
Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10
____ _____ _____ _____ _____ __________ __________ ________ ____ _____
4 'abc' 'def' 'ghj' 'klm' '' '' '' NaN NaN
NaN '' '' '' '' 'Test' 'text' '0xFF' NaN NaN
NaN '' '' '' '' 'asdfhsdf' 'dsafdsag' '0x0F0F' NaN NaN
Here is more info.
This is LITERALLY 1 google query away, but here goes:
http://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx
Understanding legacy document modes
Use the following value to display the webpage in edge mode, which is the highest standards mode supported by Internet Explorer, from Internet Explorer 6 through IE11.
<meta http-equiv="x-ua-compatible" content="IE=edge"
Note that this is functionally equivalent to using the HTML5 doctype. It places Internet Explorer into the highest supported document mode. Edge most is most useful for regularly maintained websites that are routinely tested for interoperability between multiple browsers, including Internet Explorer.
Note Starting with IE11, edge mode is considered the preferred document mode. (In earlier versions, it was considered experimental.) To learn more, see Document modes are deprecated. Starting with Windows Internet Explorer 8, some web developers used the edge mode meta element to hide the Compatibility View button on the address bar. As of IE11, this is no longer necessary as the button has been removed from the address bar. Because it forces all pages to be opened in standards mode, regardless of the version of Internet Explorer, you might be tempted to use edge mode for all pages viewed with Internet Explorer. Don't do this, as the X-UA-Compatible header is only supported starting with Internet Explorer 8.
Tip If you want all supported versions of Internet Explorer to open your pages in standards mode, use the HTML5 document type declaration, as shown in the earlier example.
Also among the search results is:
This is because $pjs
is an one-element-array of objects, so first you should access the array element, which is an object and then access its attributes.
echo $pjs[0]->player_name;
Actually dump result that you pasted tells it very clearly.
/html/body/table/tbody/tr[9]/td[1]
In Chrome (possible Safari too) you can inspect an element, then right click on the tag you want to get the xpath for, then you can copy the xpath to select that element.
This has happened to me . Jquery version : 3.3.
If you are looping through a list of objects, and want to add each object as a child of some parent dom element, then .html and .append will behave very different. .html
will end up adding only the last object to the parent element, whereas .append
will add all the list objects as children of the parent element.
Adding to what David Whittaker posted, I have created a query that generates the complete table and columns alter statement that will convert each table. It may be a good idea to run
SET SESSION group_concat_max_len = 100000;
first to make sure your group concat doesn't go over the very small limit as seen here.
SELECT a.table_name, concat('ALTER TABLE ', a.table_schema, '.', a.table_name, ' DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci, ',
group_concat(distinct(concat(' MODIFY ', column_name, ' ', column_type, ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ', if (is_nullable = 'NO', ' NOT', ''), ' NULL ',
if (COLUMN_DEFAULT is not null, CONCAT(' DEFAULT \'', COLUMN_DEFAULT, '\''), ''), if (EXTRA != '', CONCAT(' ', EXTRA), '')))), ';') as alter_statement
FROM information_schema.columns a
INNER JOIN INFORMATION_SCHEMA.TABLES b ON a.TABLE_CATALOG = b.TABLE_CATALOG
AND a.TABLE_SCHEMA = b.TABLE_SCHEMA
AND a.TABLE_NAME = b.TABLE_NAME
AND b.table_type != 'view'
WHERE a.table_schema = ? and (collation_name = 'latin1_swedish_ci' or collation_name = 'utf8mb4_general_ci')
GROUP BY table_name;
A difference here between the previous answer is it was using utf8 instead of ut8mb4 and using t1.data_type with t1.CHARACTER_MAXIMUM_LENGTH didn't work for enums. Also, my query excludes views since those will have to altered separately.
I simply used a Perl script to return all these alters as an array and iterated over them, fixed the columns that were too long (generally they were varchar(256) when the data generally only had 20 characters in them so that was an easy fix).
I found some data was corrupted when altering from latin1 -> utf8mb4. It appeared to be utf8 encoded latin1 characters in columns would get goofed in the conversion. I simply held data from the columns I knew was going to be an issue in memory from before and after the alter and compared them and generated update statements to fix the data.
I get this every time I want to create an application in VC++.
Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.
Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.
Try sleep(int number_of_seconds)
you can add bellow code in appdelegate.m .if your app is navigation based
// for background color
[nav.navigationBar setBarTintColor:[UIColor blueColor]];
// for change navigation title and button color
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],
NSForegroundColorAttributeName,
[UIFont fontWithName:@"FontNAme" size:20],
NSFontAttributeName, nil]];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
I stumbled upon this and I just wanted to say PLEASE DON'T USE @IMPORT IN CSS!!!! The import statement is sent to the client and the client does another request. If you want to divide your CSS between various files use Less. In Less the import statement happens on the server and the output is cached and does not create a performance penalty by forcing the client to make another connection. Sass is also an option another not one I have explored. Frankly, if you are not using Less or Sass then you should start. http://willseitz-code.blogspot.com/2013/01/using-less-to-manage-css-files.html
Your code will count the number of tabs and not the number of spaces. Also, the number of tabs will be one less than arr.length
.
I faced exactly the same issue in a Spring web app. In fact, I had removed spring-security by commenting the config annotation:
// @ImportResource({"/WEB-INF/spring-security.xml"})
but I had forgotten to remove the corresponding filters in web.xml
:
<!-- Filters -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Commenting filters solved the issue.
Before converting a function as promise In Node.JS
var request = require('request'); //http wrapped module
function requestWrapper(url, callback) {
request.get(url, function (err, response) {
if (err) {
callback(err);
}else{
callback(null, response);
}
})
}
requestWrapper(url, function (err, response) {
console.log(err, response)
})
After Converting It
var request = require('request');
function requestWrapper(url) {
return new Promise(function (resolve, reject) { //returning promise
request.get(url, function (err, response) {
if (err) {
reject(err); //promise reject
}else{
resolve(response); //promise resolve
}
})
})
}
requestWrapper('http://localhost:8080/promise_request/1').then(function(response){
console.log(response) //resolve callback(success)
}).catch(function(error){
console.log(error) //reject callback(failure)
})
Incase you need to handle multiple request
var allRequests = [];
allRequests.push(requestWrapper('http://localhost:8080/promise_request/1'))
allRequests.push(requestWrapper('http://localhost:8080/promise_request/2'))
allRequests.push(requestWrapper('http://localhost:8080/promise_request/5'))
Promise.all(allRequests).then(function (results) {
console.log(results);//result will be array which contains each promise response
}).catch(function (err) {
console.log(err)
});
Looping helps:
for row in matrix:
print ' '.join(row)
or use nested str.join()
calls:
print '\n'.join([' '.join(row) for row in matrix])
Demo:
>>> matrix = [['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']]
>>> for row in matrix:
... print ' '.join(row)
...
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
>>> print '\n'.join([' '.join(row) for row in matrix])
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
If you wanted to show the rows and columns transposed, transpose the matrix by using the zip()
function; if you pass each row as a separate argument to the function, zip()
recombines these value by value as tuples of columns instead. The *args
syntax lets you apply a whole sequence of rows as separate arguments:
>>> for cols in zip(*matrix): # transposed
... print ' '.join(cols)
...
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E
> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
a b
"numeric" "numeric"
You should register an event handler on the window or any element that you want to observe keystrokes on, and use the standard key values instead of keyCode. This modified code from MDN will respond to keydown when the left, right, up, or down arrow keys are pressed:
window.addEventListener("keydown", function (event) {_x000D_
if (event.defaultPrevented) {_x000D_
return; // Do nothing if the event was already processed_x000D_
}_x000D_
_x000D_
switch (event.key) {_x000D_
case "ArrowDown":_x000D_
// code for "down arrow" key press._x000D_
break;_x000D_
case "ArrowUp":_x000D_
// code for "up arrow" key press._x000D_
break;_x000D_
case "ArrowLeft":_x000D_
// code for "left arrow" key press._x000D_
break;_x000D_
case "ArrowRight":_x000D_
// code for "right arrow" key press._x000D_
break;_x000D_
default:_x000D_
return; // Quit when this doesn't handle the key event._x000D_
}_x000D_
_x000D_
// Cancel the default action to avoid it being handled twice_x000D_
event.preventDefault();_x000D_
}, true);_x000D_
// the last option dispatches the event to the listener first,_x000D_
// then dispatches event to window
_x000D_
If you just want to see what's installed on the machine you're currently logged in to, I think the most straightforward manual process is to just open the SQL Server Configuration Manager (from the Start menu), which displays all the SQL Services (and only SQL services) on that hardware (running or not). This assumes SQL Server 2005, or greater; dotnetengineer's recommendation to use the Services Management Console will show you all services, and should always be available (if you're running earlier versions of SQL Server, for example).
If you're looking for a broader discovery process, however, you might consider third party tools such as SQLRecon and SQLPing, which will scan your network and build a report of all SQL Service instances found on any server to which they have access. It's been a while since I've used tools like this, but I was surprised at what they found (namely, a handful of instances that I didn't know existed). YMMV. You might Google for details, but I believe this page has the relevant downloads: http://www.sqlsecurity.com/Tools/FreeTools/tabid/65/Default.aspx
Another sort of hacky approach is to do overflow-y: hidden
and then manually scroll the element with something like this:
function detectMouseWheelDirection(e) {
var delta = null, direction = false;
if (!e) { // If the event is not provided, we get it from the window object
e = window.event;
}
if (e.wheelDelta) { // Will work in most cases
delta = e.wheelDelta / 60;
} else if (e.detail) { // Fallback for Firefox
delta = -e.detail / 2;
}
if (delta !== null) {
direction = delta > 0 ? -200 : 200;
}
return direction;
}
if (element.addEventListener) {
element.addEventListener('DOMMouseScroll', function(e) {
element.scrollBy({
top: detectMouseWheelDirection(e),
left: 0,
behavior: 'smooth'
});
});
}
There's a great article about how to detect and deal with onmousewheel
events in deepmikoto's blog.
This might work for you, but it is definitively not an elegant solution.
Get "adbd insecure" from google play store, it helps give write access to custom roms that have it secured my the manufacturers.
According to the documentation, timestamp
is a synonym for rowversion
- it's automatically generated and guaranteed1 to be unique. datetime
isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.
1 Assuming you use it properly, of course. See comments.
build_exe_options = {"packages": ["os",'pandas','numpy']}
It works.
Correct Method is
.PopupPanel
{
border: solid 1px black;
position: fixed;
left: 50%;
top: 50%;
background-color: white;
z-index: 100;
height: 400px;
margin-top: -200px;
width: 600px;
margin-left: -300px;
}
Polymorphism simply means "Many Forms".
It does not REQUIRE inheritance to achieve...as interface implementation, which is not inheritance at all, serves polymorphic needs. Arguably, interface implementation serves polymorphic needs "Better" than inheritance.
For example, would you create a super-class to describe all things that can fly? I should think not. You would be be best served to create an interface that describes flight and leave it at that.
So, since interfaces describe behavior, and method names describe behavior (to the programmer), it is not too far of a stretch to consider method overloading as a lesser form of polymorphism.
Following on from Benjamin Muschko's answer (19 March 2011), you can use the -i
flag along with grep, to filter out 1000s of unwanted lines. Examples:
Strong filter - Only display each unit test name and test result and the overall build status. Setup errors or exceptions are not displayed.
./gradlew test -i | grep -E " > |BUILD"
Soft filter - Display each unit test name and test result, as well as setup errors/exceptions. But it will also include some irrelevant info:
./gradlew test -i | grep -E -v "^Executing |^Creating |^Parsing |^Using |^Merging |^Download |^title=Compiling|^AAPT|^future=|^task=|:app:|V/InstrumentationResultParser:"
Soft filter, Alternative syntax: (search tokens are split into individual strings)
./gradlew test -i | grep -v -e "^Executing " -e "^Creating " -e "^Parsing " -e "^Using " -e "^Merging " -e "^Download " -e "^title=Compiling" -e "^AAPT" -e "^future=" -e "^task=" -e ":app:" -e "V/InstrumentationResultParser:"
Explanation of how it works:
The first command is ./gradlew test -i
and "-i"
means "Info/Verbose" mode, which prints the result of each test in real-time, but also displays large amounts of unwanted debug lines.
So the output of the first command, ./gradlew test -i
, is piped to a second command grep
, which will filter out many unwanted lines, based on a regular expression. "-E"
enables the regular expression mode for a single string; "-e"
enables regular expressions for multiple strings; and "|"
in the regex string means "or".
In the strong filter, a unit test name and test result is allowed to display using " > "
, and the overall status is allowed with "BUILD"
.
In the soft filter, the "-v"
flag means "not containing" and "^"
means "start of line". So it strips out all lines that start with "Executing " or start with "Creating ", etc.
Example for Android instrumentation unit tests, with gradle 5.1:
./gradlew connectedDebugAndroidTest --continue -i | grep -v -e \
"^Transforming " -e "^Skipping " -e "^Cache " -e "^Performance " -e "^Creating " -e \
"^Parsing " -e "^file " -e "ddms: " -e ":app:" -e "V/InstrumentationResultParser:"
Example for Jacoco unit test coverage, with gradle 4.10:
./gradlew createDebugCoverageReport --continue -i | grep -E -v "^Executing |^Creating |^Parsing |^Using |^Merging |^Download |^title=Compiling|^AAPT|^future=|^task=|:app:|V/InstrumentationResultParser:"
Create WScript.Shell object and invoke Run() method on it.
http://msdn.microsoft.com/en-us/library/d5fk67ky(v=vs.85).aspx
If you forgot to add the repository HTTPS link then put it with git push <repo HTTPS>
In my case it was a simple type
$_SESSION['role' == 'ge']
I was missing the correct closing bracket
$_SESSION['role'] == 'ge'
Well, it's worth noting that they don't mean the same thing at all.
If the DEBUG symbol isn't defined, then in the first case the SetPrivateValue
itself won't be called... whereas in the second case it will exist, but any callers who are compiled without the DEBUG symbol will have those calls omitted.
If the code and all its callers are in the same assembly this difference is less important - but it means that in the first case you also need to have #if DEBUG
around the calling code as well.
Personally I'd recommend the second approach - but you do need to keep the difference between them clear in your head.
You can trigger a file input element by sending it a Javascript click event, e.g.
<input type="file" ... id="file-input">
$("#file-input").click();
You could put this in a click event handler for the image, for instance, then hide the file input with CSS. It'll still work even if it's invisible.
Once you've got that part working, you can set a change
event handler on the input element to see when the user puts a file into it. This event handler can create a temporary "blob" URL for the image by using window.URL.createObjectURL
, e.g.:
var file = document.getElementById("file-input").files[0];
var blob_url = window.URL.createObjectURL(file);
That URL can be set as the src
for an image on the page. (It only works on that page, though. Don't try to save it anywhere.)
Note that not all browsers currently support camera capture. (In fact, most desktop browsers don't.) Make sure your interface still makes sense if the user gets asked to pick a file.