[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.
There's no "direct" way of doing so but you can specify the pattern twice as in: a[^a]*a
that match up to the second "a".
The alternative is to use your programming language (perl? C#? ...) to match the first occurence and then the second one.
EDIT: I've seen other responded using the "non-greedy" operators which might be a good way to go, assuming you have them in your regex library!
This is an async method which first checks for the availability of arrayBuffer
method. This function is backward compatible and future proof.
async function blobToArrayBuffer(blob) {
if ('arrayBuffer' in blob) return await blob.arrayBuffer();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject;
reader.readAsArrayBuffer(blob);
});
}
I was debugging a menu hover
state with Chrome and did this to be able to see the hover state code:
In the Elements
panel click over Toggle Element state
button and select :hover
.
In the Scripts
panel go to Event Listeners Breakpoints
in the right bottom section and select Mouse -> mouseup
.
Now inspect the Menu and select the box you want. When you release the mouse button it should stop and show you the selected element hover state in the Elements
panel (look at the Styles
section).
if we consider your real site configuration, than you need to run ReactJS in the head
<!-- Babel ECMAScript 6 injunction -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
and add attribute to your js file - type="text/babel" like
<script src="../js/r1HeadBabel.js" type="text/babel"></script>
then the below code example will work:
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
Can keep global variables in webpack i.e. in webpack.config.js
externals: {
'config': JSON.stringify(GLOBAL_VARIABLE: "global var value")
}
In js module can read like
var config = require('config')
var GLOBAL_VARIABLE = config.GLOBAL_VARIABLE
Hope this will help.
If the branch is behind master, then delete the remote branch. Then go to local branch and run :
git pull origin master --rebase
Then, again push the branch to origin:
git push -u origin <branch-name>
html {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
min-height: 100%;
}
html body {
min-height: 100%
}
Works for all major browsers: FF, Chrome, Opera, IE9+. Works with Background images and gradients. Scrollbars are available as content needs.
According to Fixture finalization / executing teardown code, the current best practice for setup and teardown is to use yield
instead of return
:
import pytest
@pytest.fixture()
def resource():
print("setup")
yield "resource"
print("teardown")
class TestResource:
def test_that_depends_on_resource(self, resource):
print("testing {}".format(resource))
Running it results in
$ py.test --capture=no pytest_yield.py
=== test session starts ===
platform darwin -- Python 2.7.10, pytest-3.0.2, py-1.4.31, pluggy-0.3.1
collected 1 items
pytest_yield.py setup
testing resource
.teardown
=== 1 passed in 0.01 seconds ===
Another way to write teardown code is by accepting a request
-context object into your fixture function and calling its request.addfinalizer
method with a function that performs the teardown one or multiple times:
import pytest
@pytest.fixture()
def resource(request):
print("setup")
def teardown():
print("teardown")
request.addfinalizer(teardown)
return "resource"
class TestResource:
def test_that_depends_on_resource(self, resource):
print("testing {}".format(resource))
Since Qt 5.5 you can use QTextStream::readLineInto
. It behaves similar to std::getline
and is maybe faster as QTextStream::readLine
, because it reuses the string:
QIODevice* device;
QTextStream in(&device);
QString line;
while (in.readLineInto(&line)) {
// ...
}
Eclipse Collections has Pair
and all combinations of primitive/object Pairs (for all eight primitives).
The Tuples
factory can create instances of Pair
, and the PrimitiveTuples
factory can be used to create all combinations of primitive/object pairs.
We added these before Java 8 was released. They were useful to implement key/value Iterators for our primitive maps, which we also support in all primitive/object combinations.
If you're willing to add the extra library overhead, you can use Stuart's accepted solution and collect the results into a primitive IntList
to avoid boxing. We added new methods in Eclipse Collections 9.0 to allow for Int/Long/Double
collections to be created from Int/Long/Double
Streams.
IntList list = IntLists.mutable.withAll(intStream);
Note: I am a committer for Eclipse Collections.
You can "abort" a task by running it on a thread you control and aborting that thread. This causes the task to complete in a faulted state with a ThreadAbortException
. You can control thread creation with a custom task scheduler, as described in this answer. Note that the caveat about aborting a thread applies.
(If you don't ensure the task is created on its own thread, aborting it would abort either a thread-pool thread or the thread initiating the task, neither of which you typically want to do.)
you can enter the jdk path required as th full path for java.exe in sql developer for oracle 11g.
I found the jdk at the following path in my system.
c:\app\sony\product\11.0.0\db_1\jdk
Thank you all for your answers but I figured out how to do it and the final procedure looks like that :
Create Procedure sp_ADD_RESPONSABLE_EXTRANET_CLIENT
(
@ParLngId int output
)
as
Begin
if not exists (Select ParLngId from T_Param where ParStrIndex = 'RES' and ParStrP2 = 'Web')
Begin
INSERT INTO T_Param values('RES','¤ExtranetClient', 'ECli', 'Web', 1, 1, Null, Null, 'non', 'ExtranetClient', 'ExtranetClient', 25032, Null, '[email protected]', 'Extranet-Client', Null, 27, Null, Null, Null, Null, Null, Null, Null, Null, 1, Null, Null, 0 )
SET @ParLngId = @@IDENTITY
End
Else
Begin
SET @ParLngId = (Select top 1 ParLngId from T_Param where ParStrNom = 'Extranet Client')
Return @ParLngId
End
End
So the thing that I found out and which made it works is:
if not exists
It allows us to use a boolean instead of Null or 0 or a number resulted of count()
I got this from using a custom component inside a <Card.Text>
section of a <Card>
component in React. None of my components were in p tags
I'm not sure that you want to send two SELECT statements in one request statement because you may not be able to access both ResultSet
s. The database may only return the last result set.
Multiple ResultSets
However, if you're calling a stored procedure that you know can return multiple resultsets something like this will work
CallableStatement stmt = con.prepareCall(...);
try {
...
boolean results = stmt.execute();
while (results) {
ResultSet rs = stmt.getResultSet();
try {
while (rs.next()) {
// read the data
}
} finally {
try { rs.close(); } catch (Throwable ignore) {}
}
// are there anymore result sets?
results = stmt.getMoreResults();
}
} finally {
try { stmt.close(); } catch (Throwable ignore) {}
}
Multiple SQL Statements
If you're talking about multiple SQL statements and only one SELECT then your database should be able to support the one String
of SQL. For example I have used something like this on Sybase
StringBuffer sql = new StringBuffer( "SET rowcount 100" );
sql.append( " SELECT * FROM tbl_books ..." );
sql.append( " SET rowcount 0" );
stmt = conn.prepareStatement( sql.toString() );
This will depend on the syntax supported by your database. In this example note the addtional spaces
padding the statements so that there is white space between the staments.
Your selector won't select the input field, and if it did it would return a jQuery object. Try this:
$('#test2').is(':checked');
Use Convert.ToDouble(value)
rather than (double)value
. It takes an object
and supports all of the types you asked for! :)
Also, your method is always returning a string
in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value)
)
I believe this applies to all statically typed languages:
String s = "some string";
Object o = s; // ok
String x = o; // gives compile-time error, o is not neccessarily a string
String x = (String)o; // ok compile-time, but might give a runtime exception if o is not infact a String
The typecast effectively says: assume this is a reference to the cast class and use it as such. Now, lets say o is really an Integer, assuming this is a String makes no sense and will give unexpected results, thus there needs to be a runtime check and an exception to notify the runtime environment that something is wrong.
In practical use, you can write code working on a more general class, but cast it to a subclass if you know what subclass it is and need to treat it as such. A typical example is overriding Object.equals(). Assume we have a class for Car:
@Override
boolean equals(Object o) {
if(!(o instanceof Car)) return false;
Car other = (Car)o;
// compare this to other and return
}
You mean something like this?
long key = -1L;
PreparedStatement preparedStatement = connection.prepareStatement(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setXXX(index, VALUE);
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
key = rs.getLong(1);
}
What I don't understand is what's the point of having a byte? Why not say 8 bits?
Apart from the technical point that a byte isn't necessarily 8 bits, the reasons for having a term is simple human nature:
economy of effort (aka laziness) - it is easier to say "byte" rather than "eight bits"
tribalism - groups of people like to use jargon / a private language to set them apart from others.
Just go with the flow. You are not going to change 50+ years of accumulated IT terminology and cultural baggage by complaining about it.
FWIW - the correct term to use when you mean "8 bits independent of the hardware architecture" is "octet".
ng-bind-html-unsafe is deprecated from 1.2. The correct answer should be currently:
HTML-side: (the same as the accepted answer stated):
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text">
{{ opt.text }}
</li>
</ul>
<p>{{opt}}</p>
</div>
But in the controller-side:
myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
// ...
$scope.opts.map(function(opt) {
opt = $sce.trustAsHtml(opt);
});
}
By default Jsonresult "Deny get"
Suppose if we have method like below
[HttpPost]
public JsonResult amc(){}
By default it "Deny Get".
In the below method
public JsonResult amc(){}
When you need to allowget or use get ,we have to use JsonRequestBehavior.AllowGet.
public JsonResult amc()
{
return Json(new Modle.JsonResponseData { Status = flag, Message = msg, Html = html }, JsonRequestBehavior.AllowGet);
}
try using INSTALL_ROOT.
make install INSTALL_ROOT=$INSTALL_DIRECTORY
You can use ARG
- see https://docs.docker.com/engine/reference/builder/#arg
The
ARG
instruction defines a variable that users can pass at build-time to the builder with thedocker build
command using the--build-arg <varname>=<value>
flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.
Easy Way
Add usesCleartextTraffic
to AndroidManifest.xml
<application
...
android:usesCleartextTraffic="true"
...>
Indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP. The default value for apps that target API level 27 or lower is "true". Apps that target API level 28 or higher default to "false".
Using Random function to generate number and iterating them on al
using for loop
ArrayList<Integer> al=new ArrayList<Integer>(5);
for (int i=0;i<=4;i++){
Random rand=new Random();
al.add(i,rand.nextInt(100));
System.out.println(al);
}
System.out.println(al.size());
When an element, such as a div
is floated
, its parent container no longer considers its height, i.e.
<div id="main">
<div id="child" style="float:left;height:40px;"> Hi</div>
</div>
The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.
So the clearfix
class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.
Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.
Can read more here
YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".
save and open in excel, try refresh data and excel will be monit about parameters.
All the updates for new version of xcode will be available in appstore if you have installed the version from appstore. If you just paste the downloaded version appstore will show install not update. Hence keep the stable version downloaded from appstore in your applications folder.
To try new beta releases i usually put it in separate drive and unzip and install it there. This will avoid confusion while working on stable version.
To avoid confusion you can keep only the stable version in your dock and open the beta version from spotlight(Command + Space). This will place beta temporarily on dock. But it will make sure you don't accidentally edit your client project in beta version.
Most Important:- Working on same project on two different xcode might create some unwanted results. Like there was a bug in interface builder that got introduced in certain version of xcode. Which broke the constraints. It got fixed again in the next one.
Keep track of release notes to know exactly what are additional features and what are known issues.
Alternatively, while in your screen session all you have to do is type exit
This will kill the shell session initiated by the screen, which effectively terminates the screen session you are on.
No need to bother with screen session id, etc.
As a slight improvement over the other answers, you can do the mkdir
and chmod
as a single operation using mkdir
's -m
switch.
$ mkdir -m 700 ${HOME}/.ssh
From a Linux system
$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.
Mandatory arguments to long options are mandatory for short options too.
-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask
...
...
This is the safest solution:
git stash
Now you can do whatever you want without fear of conflicts.
For instance:
git checkout origin/master
If you want to include the remote changes in the master branch you can do:
git reset --hard origin/master
This will make you branch "master" to point to "origin/master".
If your integer is timestamp in milliseconds use:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format milliseconds to yyyy-mm-dd string.
You can hide StackNavigator header like this:
const Stack = createStackNavigator();
function StackScreen() {
return (
<Stack.Navigator
screenOptions={{ headerShown: false }}>
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="Training" component={Training} />
<Stack.Screen name="Course" component={Course} />
<Stack.Screen name="Signup" component={Signup} />
</Stack.Navigator>
);
}
If you are using MySQL, you can use order by FIELD(id, ...)
approach:
Company.findAll({
where: {id : {$in : companyIds}},
order: sequelize.literal("FIELD(company.id,"+companyIds.join(',')+")")
})
Keep in mind, it might be slow. But should be faster, than manual sorting with JS.
dbo is the default schema in SQL Server. You can create your own schemas to allow you to better manage your object namespace.
Ok, I think I have worked out "git stash unapply". It's more complex than git apply --reverse
because you need reverse merging action in case there was any merging done by the git stash apply
.
The reverse merge requires that all current changes be pushed into the index:
git add -u
Then invert the merge-recursive
that was done by git stash apply
:
git merge-recursive stash@{0}: -- $(git write-tree) stash@{0}^1
Now you will be left with just the non-stash changes. They will be in the index. You can use git reset
to unstage your changes if you like.
Given that your original git stash apply
failed I assume the reverse might also fail since some of the things it wants to undo did not get done.
Here's an example showing how the working copy (via git status
) ends up clean again:
$ git status
# On branch trunk
nothing to commit (working directory clean)
$ git stash apply
Auto-merging foo.c
# On branch trunk
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: foo.c
#
no changes added to commit (use "git add" and/or "git commit -a")
$ git add -u
$ git merge-recursive stash@{0}: -- $(git write-tree) stash@{0}^1
Auto-merging foo.c
$ git status
# On branch trunk
nothing to commit (working directory clean)
Code
DELETE DUP
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY Clientid ORDER BY Clientid ) AS Val
FROM ClientMaster
) DUP
WHERE DUP.Val > 1
Explanation
Use an inner query to construct a view over the table which includes a field based on Row_Number()
, partitioned by those columns you wish to be unique.
Delete from the results of this inner query, selecting anything which does not have a row number of 1; i.e. the duplicates; not the original.
The order by
clause of the row_number window function is needed for a valid syntax; you can put any column name here. If you wish to change which of the results is treated as a duplicate (e.g. keep the earliest or most recent, etc), then the column(s) used here do matter; i.e. you want to specify the order such that the record you wish to keep will come first in the result.
To change the app name when in Android, go to res/values/strings.xml
and change app_name
to what you want.
I use nice set of useful filter library "Angular-filter" and one of them called "truncate" is useful too.
https://github.com/a8m/angular-filter#truncate
usage is:
text | truncate: [length]: [suffix]: [preserve-boolean]
You can generate a data URI. However, there are browser-specific limitations.
Works Fine. Try this,
private void addImageButton_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
//For any other formats
of.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG";
if (of.ShowDialog() == DialogResult.OK)
{
pictureBox1.ImageLocation = of.FileName;
}
}
ideally we should never catch Error in our Java application as it is an abnormal condition. The application would be in abnormal state and could result in carshing or giving some seriously wrong result.
exponent
is a 1D array. This means that exponent[0]
is a scalar, and exponent[0][i]
is trying to access it as if it were an array.
Did you mean to say:
L = identity(len(l))
for i in xrange(len(l)):
L[i][i] = exponent[i]
or even
L = diag(exponent)
?
You need to extract the number from the string, and pass it into the Date constructor
:
var x = [{
"id": 1,
"start": "\/Date(1238540400000)\/"
}, {
"id": 2,
"start": "\/Date(1238626800000)\/"
}];
var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);
The parts are:
x[0].start - get the string from the JSON
x[0].start.match(/\d+/)[0] - extract the numeric part
x[0].start.match(/\d+/)[0] * 1 - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object
Since Node 7.6, you can combine the functions promisify
function from the utils module with setTimeout()
.
const sleep = require('util').promisify(setTimeout)
const sleep = m => new Promise(r => setTimeout(r, m))
(async () => {
console.time("Slept for")
await sleep(3000)
console.timeEnd("Slept for")
})()
Cookie-Based Authentication
Cookies based Authentication works normally in these 4 steps-
Browser will submit this session Id on each subsequent requests, the session ID is verified against the database, based on this session id website will identify the session belonging to which client and then give access the request.
Once a user logs out of the app, the session is destroyed both client-side and server-side.
Use Escape sequence.
\"Hello\"
This will print "Hello".
This solution did the trick for me
<a ng-style="{true: {paddingLeft: '25px'}, false: {}}[deleteTriggered]">...</a>
Was facing same issue. In my case it was non-compatible GIT versions across multiple users who are accessing(pull/push) same project.
have just updated GIT version and updated the path on Android studio settings and its working fine for me.
Edit -
Git for Windows (1.9.5) having some problem, updating the same may helps.
php.ini:
xdebug.max_nesting_level = -1
I'm not entirely sure if the value will ever overflow and reach -1, but it'll either never reach -1, or it'll set the max_nesting_level pretty high.
Below is one of the way by which you can achieve that, may not be an ideal way to do.
Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.
@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
//handle both get and post request here
// first check request type and do respective actions needed for get and post.
if(GET REQUEST){
//WORK RELATED TO GET
}else if(POST REQUEST){
//WORK RELATED TO POST
}
commonMethod(param1, param2....);
}
So your myscript
output 3 lines, could look like:
myscript() { echo $'abc\ndef\nghi'; }
or
myscript() { local i; for i in abc def ghi ;do echo $i; done ;}
Ok this is a function, not a script (no need of path ./
), but output is same
myscript
abc
def
ghi
To check for result code, test function will become:
myscript() { local i;for i in abc def ghi ;do echo $i;done;return $((RANDOM%128));}
Your operation is correct:
RESULT=$(myscript)
About result code, you could add:
RCODE=$?
even in same line:
RESULT=$(myscript) RCODE=$?
Then
echo $RESULT
abc def ghi
echo "$RESULT"
abc
def
ghi
echo ${RESULT@Q}
$'abc\ndef\nghi'
printf "%q\n" "$RESULT"
$'abc\ndef\nghi'
but for showing variable definition, use declare -p
:
declare -p RESULT
declare -- RESULT="abc
def
ghi"
mapfile
Storing answer into myvar
variable:
mapfile -t myvar < <(myscript)
echo ${myvar[2]}
ghi
Showing $myvar
:
declare -p myvar
declare -a myvar=([0]="abc" [1]="def" [2]="ghi")
In case you have to check for result code, you could:
RESULT=$(myscript) RCODE=$?
mapfile -t myvar <<<"$RESULT"
read
in command group{ read firstline; read secondline; read thirdline;} < <(myscript)
echo $secondline
def
Showing variables:
declare -p firstline secondline thirdline
declare -- firstline="abc"
declare -- secondline="def"
declare -- thirdline="ghi"
I often use:
{ read foo;read foo total use free foo ;} < <(df -k /)
Then
declare -p use free total
declare -- use="843476"
declare -- free="582128"
declare -- total="1515376"
Same prepended step:
RESULT=$(myscript) RCODE=$?
{ read firstline; read secondline; read thirdline;} <<<"$RESULT"
declare -p firstline secondline thirdline RCODE
declare -- firstline="abc"
declare -- secondline="def"
declare -- thirdline="ghi"
declare -- RCODE="50"
If you run SHOW VARIABLES
from a mysql console you can look for basedir.
When I run the following:
mysql> SHOW VARIABLES WHERE `Variable_name` = 'basedir';
on my system I get /usr/local/mysql
as the Value returned.
(I am not using MAMP - I installed MySQL with homebrew.
mysqld
on my machine is in /usr/local/mysql/bin
so the basedir is where most everything will be installed to.
Also util:
mysql> SHOW VARIABLES WHERE `Variable_name` = 'datadir';
To find where the DBs are stored.
For more: http://dev.mysql.com/doc/refman/5.0/en/show-variables.html
and http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_basedir
Comparison expressions should each be in their own brackets:
{% if (a == 'foo') or (b == 'bar') %}
...
{% endif %}
Alternative if you are inspecting a single variable and a number of possible values:
{% if a in ['foo', 'bar', 'qux'] %}
...
{% endif %}
Primary key attributes are just as updateable as any other attributes of a table. Stability is often a desirable property of a key but definitely not an absolute requirement. If it makes sense from a business perpective to update a key then there's no fundamental reason why you shouldn't.
I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.
You may consider declaring the variables with moudule level scope. Module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules
For details on Scope of variables
refer this link
Please copy the below code into any module, save the workbook and then run the code.
Here is what code does
The sample subroutine sets the folder path & later the file path. Kindly set them accordingly before you run the code.
I have added a function IsWorkBookOpen to check if workbook is already then set the workbook variable the workbook name else open the workbook which will be assigned to workbook variable accordingly.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
folderPath = ThisWorkbook.Path & "\"
fileNm1 = "file1.xlsx"
fileNm2 = "file2.xlsx"
filePath1 = folderPath & fileNm1
filePath2 = folderPath & fileNm2
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Using Prompt to select the file use below code.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
Dim filePath As String
cmdBrowse_Click filePath, 1
filePath1 = filePath
'reset the variable
filePath = vbNullString
cmdBrowse_Click filePath, 2
filePath2 = filePath
fileNm1 = GetFileName(filePath1, "\")
fileNm2 = GetFileName(filePath2, "\")
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Private Sub cmdBrowse_Click(ByRef filePath As String, num As Integer)
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select workbook " & num
fd.InitialView = msoFileDialogViewSmallIcons
Dim FileChosen As Integer
FileChosen = fd.Show
fd.Filters.Clear
fd.Filters.Add "Excel macros", "*.xlsx"
fd.FilterIndex = 1
If FileChosen <> -1 Then
MsgBox "You chose cancel"
filePath = ""
Else
filePath = fd.SelectedItems(1)
End If
End Sub
Function GetFileName(fullName As String, pathSeparator As String) As String
Dim i As Integer
Dim iFNLenght As Integer
iFNLenght = Len(fullName)
For i = iFNLenght To 1 Step -1
If Mid(fullName, i, 1) = pathSeparator Then Exit For
Next
GetFileName = Right(fullName, iFNLenght - i)
End Function
Very simple to fix, you just need to turn the parameter to writerow into a list.
for item in RESULTS:
wr.writerow([item,])
Remove a block of code from multiple files
To expand on @Markus Olsson's answer, I needed to remove a block of code from multiple files. I had problems with Swedish characters in a core project, so I needed to install System.Text.CodePagesEncodingProvider nuget package and use System.Text.Encoding.GetEncoding(1252) instead of System.Text.Encoding.UTF8.
public static void Main(string[] args)
{
try
{
var dir = @"C:\Test";
//Get all html and htm files
var files = DirSearch(dir);
foreach (var file in files)
{
RmCode(file);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
private static void RmCode(string file)
{
string tempFile = Path.GetTempFileName();
using (var sr = new StreamReader(file, Encoding.UTF8))
using (var sw = new StreamWriter(new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite), Encoding.UTF8))
{
string line;
var startOfBadCode = "<div>";
var endOfBadCode = "</div>";
var deleteLine = false;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(startOfBadCode))
{
deleteLine = true;
}
if (!deleteLine)
{
sw.WriteLine(line);
}
if (line.Contains(endOfBadCode))
{
deleteLine = false;
}
}
}
File.Delete(file);
File.Move(tempFile, file);
}
private static List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return files.Where(s => s.EndsWith(".htm") || s.EndsWith(".html")).ToList();
}
I've done some timings over the various recommendations here, and the results really depend on the size of the table involved, but the most consistent solution is using the CROSS APPLY These tests were run against SQL Server 2008-R2, using a table with 6,500 records, and another (identical schema) with 137 million records. The columns being queried are part of the primary key on the table, and the table width is very small (about 30 bytes). The times are reported by SQL Server from the actual execution plan.
Query Time for 6500 (ms) Time for 137M(ms)
CROSS APPLY 17.9 17.9
SELECT WHERE col = (SELECT MAX(COL)…) 6.6 854.4
DENSE_RANK() OVER PARTITION 6.6 907.1
I think the really amazing thing was how consistent the time was for the CROSS APPLY regardless of the number of rows involved.
Use setImmediate
if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick
to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.
So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate
rather than process.nextTick
to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.
The minimal setup for an HTTPS server in Node.js would be something like this :
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
https.createServer(httpsOptions, app).listen(4433);
If you also want to support http requests, you need to make just this small modification :
var http = require('http');
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);
Since I prefer to list required arguments before optional, I hack around it via:
parser = argparse.ArgumentParser()
parser._action_groups.pop()
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
return parser.parse_args()
and this outputs:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
--optional_arg OPTIONAL_ARG
I can live without 'help' showing up in the optional arguments group.
PHP 7.1.0 has introduced the iterable
pseudo-type and the is_iterable()
function, which is specially designed for such a purpose:
This […] proposes a new
iterable
pseudo-type. This type is analogous tocallable
, accepting multiple types instead of one single type.
iterable
accepts anyarray
or object implementingTraversable
. Both of these types are iterable usingforeach
and can be used withyield
from within a generator.
function foo(iterable $iterable) {
foreach ($iterable as $value) {
// ...
}
}
This […] also adds a function
is_iterable()
that returns a boolean:true
if a value is iterable and will be accepted by theiterable
pseudo-type,false
for other values.
var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)
You can also use the function is_array($var)
to check if the passed variable is an array:
<?php
var_dump( is_array(array()) ); // true
var_dump( is_array(array(1, 2, 3)) ); // true
var_dump( is_array($_SERVER) ); // true
?>
Read more in How to check if a variable is an array in PHP?
Here's another way this can be done (just adding it to the answers because reduce
is a very effective functional tool that is often overlooked as a replacement for loops. In this particular case, neither of these are significantly faster than do.call)
using base R:
df <- Reduce(rbind, listOfDataFrames)
or, using the tidyverse:
library(tidyverse) # or, library(dplyr); library(purrr)
df <- listOfDataFrames %>% reduce(bind_rows)
You may use the following code to remove non-English letters:
import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)
This will return
123456790 ABC#%? .()
Front :
<Image Name="camImage"/>
Back:
public async void Base64ToImage(string base64String)
{
// read stream
var bytes = Convert.FromBase64String(base64String);
var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();
// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);
// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
camImage.Source = output;
}
For large datasets, it is memory efficient to read only selected rows via the skiprows
parameter.
Example
pred = lambda x: x not in [1, 3]
pd.read_csv("data.csv", skiprows=pred, index_col=0, names=...)
This will now return a DataFrame from a file that skips all rows except 1 and 3.
Details
From the docs:
skiprows
: list-like or integer or callable, defaultNone
...
If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be
lambda x: x in [0, 2]
This feature works in version pandas 0.20.0+. See also the corresponding issue and a related post.
use this (in kotlin)
activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// in here you can do logic when backPress is clicked
}
})
i think this is the most elegant way to do it
For version 4.0, 4.5 on Windows
File -> Settings
Then,
Editor -> General -> Appearance -> Show line numbers
For version 4.0 on Mac OSX
PyCharm-->Preferences
Then,
Editor-->General-->Appearance-->checkbox: "Show line numbers"
Nice article explaining the basics (does not cover line breaks, however).
A Whole Bunch of Amazing Stuff Pseudo Elements Can Do
If you need to have two inline elements where one breaks into the next line within another element, you can accomplish this by adding a pseudo-element :after with content:'\A' and white-space: pre
HTML
<h3>
<span class="label">This is the main label</span>
<span class="secondary-label">secondary label</span>
</h3>
CSS
.label:after {
content: '\A';
white-space: pre;
}
Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers
It looks like you want to use a list instead:
group=[]
for i in range(3):
group[i]=self.getGroup(selected, header+i)
if you have scenario in which you have to remove more then one values from the foreach array in this case you have to pass value by reference in for each: I try to explain this scenario:
foreach ($manSkuQty as $man_sku => &$man_qty) {
foreach ($manufacturerSkus as $key1 => $val1) {
// some processing here and unset first loops entries
// here dont include again for next iterations
if(some condition)
unset($manSkuQty[$key1]);
}
}
}
in second loop you want to unset first loops entries dont come again in the iteration for performance purpose or else then unset from memory as well because in memory they present and will come in iterations.
There's a far more simpler solution to tackle this.
The reason why you get ValueError: Index contains duplicate entries, cannot reshape
is because, once you unstack "Location
", then the remaining index columns "id
" and "date
" combinations are no longer unique.
You can avoid this by retaining the default index column (row #) and while setting the index using "id
", "date
" and "location
", add it in "append
" mode instead of the default overwrite mode.
So use,
e.set_index(['id', 'date', 'location'], append=True)
Once this is done, your index columns will still have the default index along with the set indexes. And unstack
will work.
Let me know how it works out.
After doing what everyone else said above, i.e.:
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.isTranslucent = true
... my navigation bar was still white. So I added this line:
navigationController?.navigationBar.backgroundColor = .clear
... et voila! That seemed to do the trick.
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('dan red',
(SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')
it is advisable to store your values in lowercase to make retrieval easier and less error prone
INSERT INTO tab_teacher (name_teacher)
VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('rich man', LAST_INSERT_ID())
As to why atof()
isn't working in the original question: the fact that it's cast to double makes me suspicious. The code shouldn't compile without #include <stdlib.h>
, but if the cast was added to solve a compile warning, then atof()
is not correctly declared. If the compiler assumes atof()
returns an int, casting it will solve the conversion warning, but it will not cause the return value to be recognized as a double.
#include <stdlib.h>
#include <string>
...
std::string num = "0.6";
double temp = atof(num.c_str());
should work without warnings.
Thanks Philip this helped me - my use case was I had a form with lot of input fields so I maintained initial state as object and I was not able to update the object state.The above post helped me :)
const [projectGroupDetails, setProjectGroupDetails] = useState({
"projectGroupId": "",
"projectGroup": "DDD",
"project-id": "",
"appd-ui": "",
"appd-node": ""
});
const inputGroupChangeHandler = (event) => {
setProjectGroupDetails((prevState) => ({
...prevState,
[event.target.id]: event.target.value
}));
}
<Input
id="projectGroupId"
labelText="Project Group Id"
value={projectGroupDetails.projectGroupId}
onChange={inputGroupChangeHandler}
/>
I'm using HttpClient 4.5.3, using CloseableHttpResponse#close
worked for me.
CloseableHttpResponse response = client.execute(request);
try {
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
checkResult(body);
EntityUtils.consume(entity);
} finally {
response.close();
}
With Java7 and beyond:
try (CloseableHttpResponse response = client.execute(request)) {
...
}
I had this problem. As stated it is probably a static declaration issue. In my case it was because I had a static within a DEBUG clause. That is (in c#)
#if DEBUG
public static bool DOTHISISINDEBUGONLY = false;
#endif
Everything worked fine until I complied a Release version of the code and after that I got this error - even on old release versions of the code. Once I took the variable out of the DEBUG clause everything returned to normal.
Not with an iterator.
For org.json.JSONArray
, you can do:
for (int i = 0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
For javax.json.JsonArray
, you can do:
for (int i = 0; i < arr.size(); i++) {
arr.getJsonObject(i);
}
it suggests that you fail to link the explicitly instantiated basetype public gameCore (whereas the header file forward declares it).
Since we know nothing about your build config/library dependencies, we can't really tell which link flags/source files are missing, but I hope the hint alone helps you fix ti.
In my case i never put return inside a arrow function so my code is follow
`<ProductConsumer>
{(myvariable)=>{
return <h1>{myvariable}</h1>
}}
</ProductConsumer> `
Ensure that all the libraries you're using in your project are not being referenced from other project int the workspace. That was my problem.
Many commands are already attached to simple ctrl+[key], you can also do chorded keybinding like ctrl a+b.
(In case this is your first time reading about chorded keybindings: They work by not letting go of the ctrl key and pressing a second key after the first.)
I have my Emmet: Wrap with Abbreviation
bound to ((ctrl) (w+a)).
In windows: File > Preferences > Keyboard Shortcuts ((ctrl) (k+s))> search for Wrap with Abbreviation > double-click > add your combonation.
You can access the values in a vector just as you access any other array.
for (int i = 0; i < v.size(); i++)
{
v[i] -= 1;
}
They must have included this as a feature, because now setting a different @JsonProperty
for a getter and setter results in exactly what you would expect (different property name during serialization and deserialization for the same field). Jackson version 2.6.7
select distinct owner
from dba_segments
where owner in (select username from dba_users where default_tablespace not in ('SYSTEM','SYSAUX'));
Sometimes you have to npm install package_name -g
for it to work.
The following is easy to remember
ls -ltrapR
list directory contents
-l use a long listing format
-t sort by modification time, newest first
-r, --reverse reverse order while sorting
-a, --all do not ignore entries starting with .
-p, --indicator-style=slash append / indicator to directories
-R, --recursive list subdirectories recursively
Short answer: download Linux Device Drivers and read the chapter on memory management.
Seriously, there are a lot of subtle issues related to kernel memory management that you need to understand - I spend a lot of my time debugging problems with it.
vmalloc() is very rarely used, because the kernel rarely uses virtual memory. kmalloc() is what is typically used, but you have to know what the consequences of the different flags are and you need a strategy for dealing with what happens when it fails - particularly if you're in an interrupt handler, like you suggested.
An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —
In order to run natively, you will likely need to use Cygwin (which I cannot live without when using Windows). So right off the bat, +1 for Cygwin. Anything else would be uncivilized.
HOWEVER, that being said, I have recently begun using a combination of utilities to easily PORT Bash scripts to Windows so that my anti-Linux coworkers can easily run complex tasks that are better handled by GNU utilities.
I can usually port a Bash script to Batch in a very short time by opening the original script in one pane and writing a Batch file in the other pane. The tools that I use are as follows:
I prefer UnxUtils to GnuWin32 because of the fact that [someone please correct me if I'm wrong] GnuWin utils normally have to be installed, whereas UnxUtils are standalone binaries that just work out-of-the-box.
However, the CoreUtils do not include some familiar *NIX utilities such as cURL, which is also available for Windows (curl.haxx.se/download.html).
I create a folder for the projects, and always SET PATH=. in the .bat file so that no other commands other than the basic CMD shell commands are referenced (as well as the particular UnxUtils required in the project folder for the Batch script to function as expected).
Then I copy the needed CoreUtils .exe files into the project folder and reference them in the .bat file such as ".\curl.exe -s google.com", etc.
The Bat2Exe program is where the magic happens. Once your Batch file is complete and has been tested successfully, launch Bat2Exe.exe, and specify the path to the project folder. Bat2Exe will then create a Windows binary containing all of the files in that specific folder, and will use the first .bat that it comes across to use as the main executable. You can even include a .ico file to use as the icon for the final .exe file that is generated.
I have tried a few of these type of programs, and many of the generated binaries get flagged as malware, but the Bat2Exe version that I referenced works perfectly and the generated .exe files scan completely clean.
The resulting executable can be run interactively by double-clicking, or run from the command line with parameters, etc., just like a regular Batch file, except you will be able to utilize the functionality of many of the tools that you will normally use in Bash.
I realize this is getting quite long, but if I may digress a bit, I have also written a Batch script that I call PortaBashy that my coworkers can launch from a network share that contains a portable Cygwin installation. It then sets the %PATH% variable to the normal *NIX format (/usr/bin:/usr/sbin:/bin:/sbin), etc. and can either launch into the Bash shell itself or launch the more-powerful and pretty MinTTY terminal emulator.
There are always numerous ways to accomplish what you are trying to set out to do; it's just a matter of combining the right tools for the job, and many times it boils down to personal preference.
Now you can use insert
method instead add
' Visual Basic
CheckedListBox1.Items.Insert(0, "Copenhagen")
Don’t need to specify a type
value of “text/css”
Every time you link to a CSS file:
<link rel="stylesheet" type="text/css" href="file.css">
You can simply write:
<link rel="stylesheet" href="file.css">
Look this:
List<Client> result = clients
.stream()
.filter(c ->
(users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
.collect(Collectors.toList());
Assuming you have a list of object of type Person, using Lambda expression, you can sort the last names of users for instance by doing the following:
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public String getLastName(){
return this.lastName;
}
public String getFirstName(){
return this.firstName;
}
@Override
public String toString(){
return "Person: "+ this.getFirstName() + " " + this.getLastName();
}
}
class TestSort {
public static void main(String[] args){
List<Person> people = Arrays.asList(
new Person("John", "Max"),
new Person("Coolio", "Doe"),
new Person("Judith", "Dan")
);
//Making use of lambda expression to sort the collection
people.sort((p1, p2)->p1.getLastName().compareTo(p2.getLastName()));
//Print sorted
printPeople(people);
}
public static void printPeople(List<Person> people){
for(Person p : people){
System.out.println(p);
}
}
}
Very Simple way to create an object in Java using Class<?>
with constructor argument(s) passing:
Case 1:-
Here, is a small code in this Main
class:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Main {
public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Get class name as string.
String myClassName = Base.class.getName();
// Create class of type Base.
Class<?> myClass = Class.forName(myClassName);
// Create constructor call with argument types.
Constructor<?> ctr = myClass.getConstructor(String.class);
// Finally create object of type Base and pass data to constructor.
String arg1 = "My User Data";
Object object = ctr.newInstance(new Object[] { arg1 });
// Type-cast and access the data from class Base.
Base base = (Base)object;
System.out.println(base.data);
}
}
And, here is the Base
class structure:
public class Base {
public String data = null;
public Base()
{
data = "default";
System.out.println("Base()");
}
public Base(String arg1) {
data = arg1;
System.out.println("Base("+arg1+")");
}
}
Case 2:- You, can code similarly for constructor with multiple argument and copy constructor. For example, passing 3 arguments as parameter to the Base
constructor will need the constructor to be created in class and a code change in above as:
Constructor<?> ctr = myClass.getConstructor(String.class, String.class, String.class);
Object object = ctr.newInstance(new Object[] { "Arg1", "Arg2", "Arg3" });
And here the Base class should somehow look like:
public class Base {
public Base(String a, String b, String c){
// This constructor need to be created in this case.
}
}
Note:- Don't forget to handle the various exceptions which need to be handled in the code.
Using JODA:
PeriodFormatter periodFormat = new PeriodFormatterBuilder()
.minimumParsedDigits(2)
.appendHour() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendMinute() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendSecond()
.appendSeparator(".")
.appendMillis3Digit()
.toFormatter();
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();
additionally you may want mongo to run on another port, then paste this command on terminal,
mongod --dbpath /data/db/ --port 27018
where 27018 is the port we want mongo to run on
/usr/local/bin/
for mac ( which would be if you installed with brew), otherwise you'd need to navigate to the path where mongo is installed/data/db/
existsYou might try using a library like redux-saga. It allows for a very clean way to sequence async functions, fire off actions, use delays and more. It is very powerful!
Run project as Maven test, then Run as JUnit Test.
The html_safe version works well in Rails 4...
<%= "<center style=\"color: green; font-size: 1.1em\" > Administrators only </center>".html_safe if current_user.admin? %
>
You can do either:
$("h1").css("background-color", "yellow");
Or:
$("h1").css({backgroundColor: "yellow"});
You could just download jq
binary for your platform and run (chmod +x jq
):
$ curl 'https://twitter.com/users/username.json' | ./jq -r '.name'
It extracts "name"
attribute from the json object.
jq
homepage says it is like sed
for JSON data.
compiler changes checks your source code for errors and changes it into object code.this is the code that operating system runs.
You often don't write a whole program in single file so linker links all your object code files.
your program wont get executed unless it is in main memory
If you want to select particular element use below code
var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];
UPDATE
The bookmarklet hack below is broken due to XHR issues and API changes.
Thankfully Github now has "A Whole New Code Search" which does the job superbly.
Checkout this voodoo: Github code search userscript.
Follow the directions there, or if you hate bloating your browser with scripts and extensions, use my bookmarkified bundle of the userscript:
javascript:(function(){var s='https://raw.githubusercontent.com/skratchdot/github-enhancement-suite/master/build/github-enhancement-suite.user.js',t='text/javascript',d=document,n=navigator,e;(e=d.createElement('script')).src=s;e.type=t;d.getElementsByTagName('head')[0].appendChild(e)})();doIt('');void('');
Save the source above as the URL of a new bookmark. Browse to any Github repo, click the bookmark, and bam: in-page, ajaxified code search.
CAVEAT Github must index a repo before you can search it.
Abracadabra...
Here's a sample search from the annotated ECMAScript 5.1 specification repository:
Probably for the same reason that there is no tree container in boost. There are many ways to implement such a container, and there is no good way to satisfy everyone who would use it.
Some issues to consider:
In the end, the problem ends up being that a tree container that would be useful enough to everyone, would be too heavyweight to satisfy most of the people using it. If you are looking for something powerful, Boost Graph Library is essentially a superset of what a tree library could be used for.
Here are some other generic tree implementations:
You should use either indexing or the subset
function. For example :
R> df <- data.frame(x=1:5, y=2:6, z=3:7, u=4:8)
R> df
x y z u
1 1 2 3 4
2 2 3 4 5
3 3 4 5 6
4 4 5 6 7
5 5 6 7 8
Then you can use the which
function and the -
operator in column indexation :
R> df[ , -which(names(df) %in% c("z","u"))]
x y
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
Or, much simpler, use the select
argument of the subset
function : you can then use the -
operator directly on a vector of column names, and you can even omit the quotes around the names !
R> subset(df, select=-c(z,u))
x y
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
Note that you can also select the columns you want instead of dropping the others :
R> df[ , c("x","y")]
x y
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
R> subset(df, select=c(x,y))
x y
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
2016 update:
You can create a new stacking context, as seen on Coderwall:
<div style="transform: translate3d(0,0,0);overflow:hidden">
<img style="position:fixed; ..." />
</div>
Which refers to http://dev.w3.org/csswg/css-transforms/#transform-rendering
For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.
You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.
run conda navigator, you can upgrade your packages easily in the friendly GUI
angle = Math.toDegrees(Math.atan2(target.x - x, target.y - y));
now for orientation of circular values to keep angle between 0 and 359 can be:
angle = angle + Math.ceil( -angle / 360 ) * 360
My 2p solution:
#include <random>
#include <string>
std::string random_string(std::string::size_type length)
{
static auto& chrs = "0123456789"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
thread_local static std::mt19937 rg{std::random_device{}()};
thread_local static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(chrs) - 2);
std::string s;
s.reserve(length);
while(length--)
s += chrs[pick(rg)];
return s;
}
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
If one is getting this message during saving or compiling the build, just close all the files and then open any file to compile and save.
For me the reason was that I had rename the file and old file was still open.
I found this to be the simplest way.
>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>>
Alternative to egaga's constructor method of copy. You probably already have a POJO, so just add another method copy()
which returns a copy of the initialized object.
class DummyBean {
private String dummyStr;
private int dummyInt;
public DummyBean(String dummyStr, int dummyInt) {
this.dummyStr = dummyStr;
this.dummyInt = dummyInt;
}
public DummyBean copy() {
return new DummyBean(dummyStr, dummyInt);
}
//... Getters & Setters
}
If you already have a DummyBean
and want a copy:
DummyBean bean1 = new DummyBean("peet", 2);
DummyBean bean2 = bean1.copy(); // <-- Create copy of bean1
System.out.println("bean1: " + bean1.getDummyStr() + " " + bean1.getDummyInt());
System.out.println("bean2: " + bean2.getDummyStr() + " " + bean2.getDummyInt());
//Change bean1
bean1.setDummyStr("koos");
bean1.setDummyInt(88);
System.out.println("bean1: " + bean1.getDummyStr() + " " + bean1.getDummyInt());
System.out.println("bean2: " + bean2.getDummyStr() + " " + bean2.getDummyInt());
Output:
bean1: peet 2 bean2: peet 2 bean1: koos 88 bean2: peet 2
But both works well, it is ultimately up to you...
bool IsExist = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("/UploadedFiles/"));
if (!IsExist)
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/UploadedFiles/"));
StreamWriter textWriter = File.CreateText(Path.Combine(HttpContext.Current.Server.MapPath("/UploadedFiles/") + "FileName.csv"));
var csvWriter = new CsvWriter(textWriter, System.Globalization.CultureInfo.CurrentCulture);
csvWriter.WriteRecords(classVM);
Copy everything (in the folder containing the .git) to a backup, then delete everything and restart. Make sure you have the git remote handy:
git remote -v
origin [email protected]:rwldrn/idiomatic.js.git (fetch)
origin [email protected]:rwldrn/idiomatic.js.git (push)
Then
mkdir mygitfolder.backup
cp mygitfolder/* mygitfolder.backup/
cd mygitfolder
rm -r * .git*
git init
git remote add origin [email protected]:rwldrn/idiomatic.js.git
Then merge any new files manually, and try to keep your computer turned on.
Update 3: There is an official api added for this, please use ActivityLifecycleCallbacks instead.
This is worked for me using JAVA script for chrome extension.
document.body.innerHTML = myFunction();
function myFunction()
{
var phonedef = new RegExp("(?:(?:\\+|0{0,2})91(\\s*[\\- ]\\s*)?|[0 ]?)?[789]\\d{9}|(\\d[ -]?){10}\\d", "g");
var str = document.body.innerHTML;
var res = str.replace(phonedef, function myFunction(x){return "<a href='tel:"+x.replace( /(\s|-)/g, "")+"'>"+x+"</a>";});
return res;
}
This covers following numbers pattern
9883443344
8888564723
7856128945
09883443344
0 9883443344
0-9883443344
919883443344
91 8834433441
91-9883443344
91 -9883443344
91- 9883443344
91 - 9883443344
91 -9883443344
+917878525200
+91 8834433441
+91-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
+91 -9883443344
0919883443344
0091-7779015989
0091 - 8834433440
022-24130000
080 25478965
0416-2565478
08172-268032
04512-895612
02162-240000
022-24141414
079-22892350
Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.
I think your answer is fine (and it's OK to accept it if you like). This is just "extra".
import numpy as np
a = np.arange(4,10).reshape(2,3)
wh = np.where(a>7)
gt = a>7
x = np.where(gt)
print "wh: ", wh
print "gt: ", gt
print "x: ", x
gives:
wh: (array([1, 1]), array([1, 2]))
gt: [[False False False]
[False True True]]
x: (array([1, 1]), array([1, 2]))
... but:
print "a[wh]: ", a[wh]
print "a[gt] ", a[gt]
print "a[x]: ", a[x]
gives:
a[wh]: [8 9]
a[gt] [8 9]
a[x]: [8 9]
If the indexes are continuous:
foreach ($arr as $key => $val) {
if (isset($arr[$key+1])) {
echo $arr[$key+1]; // next element
} else {
// end of array reached
}
}
If you guys are generating your stylesheets with LESS/SASS and are importing Bootstrap there, I've found that overriding the @navbar-height variable lets your set the height of the navbar, which is originally defined in the variables.less file.
add the transformRequest as below to send multiple params to backend
var jq = jQuery.noConflict();
var transform = function(data) {
return jq.param(data);
};
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},transformRequest: transform
};
var params={
blogPostJson:JSON.stringify($scope.blogPost),
publish:$scope.blogPost.active
};
var url = "${createLink(controller : 'cms', action : 'saveBlog')}";
$http.post(url,params, config).then(function onSuccess(response) {
var data = response.data;
// var status = response.status;
if (data.error) {
alert('error :' + data.error);
} else {
// alert('Success');
}
}).catch(function onError(response) {
//console.log ("Unable to save Alcohol information");
});
There is another explanation from the real world:
A book belongs to an owner, and an owner can own multiple books. But, the book can exist also without the owner, and ownership of it can change from one owner to another. The relationship between a book and an owner is a non-identifying relationship.
A book, however, is written by an author, and the author could have written multiple books. But, the book needs to be written by an author - it cannot exist without an author. Therefore, the relationship between the book and the author is an identifying relationship.
The list.append
function does not return any value(but None
), it just adds the value to the list you are using to call that method.
In the first loop round you will assign None
(because the no-return of append
) to a
, then in the second round it will try to call a.append
, as a is None
it will raise the Exception you are seeing
You just need to change it to:
a=[]
for i in range(5):
a.append(i)
print(a)
# [0, 1, 2, 3, 4]
list.append
is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).
If you would like to create a new list based in one list without destroying or mutating it you can do something like this:
a=['a', 'b', 'c']
result = a + ['d']
print result
# ['a', 'b', 'c', 'd']
print a
# ['a', 'b', 'c']
As a corollary only, you can mimic the append
method by doing the following:
a=['a', 'b', 'c']
a = a + ['d']
print a
# ['a', 'b', 'c', 'd']
The problem is that flex: 1
sets flex-basis: 0
. Instead, you need
.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</div>
_x000D_
The best way to get the id of the entity you added is like this:
public int InsertEntity(Entity factor)
{
Db.Entities.Add(factor);
Db.SaveChanges();
var id = factor.id;
return id;
}
On Ubuntu and Debian
apt-get install python-six
does the trick.
Use sudo apt-get install python-six
if you get an error saying "permission denied".
If you're not religious about keeping your HTML valid then I can see use cases where having the same ID on multiple elements may be useful.
One example is testing. Often we identify elements to test against by finding all elements with a particular class. However, if we find ourselves adding classes purely for testing purposes, then I would contend that that's wrong. Classes are for styling, not identification.
If IDs are for identification, why must it be that only one element can have a particular identifier? Particularly in today's frontend world, with reusable components, if we don't want to use classes for identification, then we need to use IDs. But, if we use multiples of a component, we'll have multiple elements with the same ID.
I'm saying that's OK. If that's anathema to you, that's fine, I understand your view. Let's agree to disagree and move on.
If you want a solution that actually finds all IDs of the same name though, then it's this:
function getElementsById(id) {
const elementsWithId = []
const allElements = document.getElementsByTagName('*')
for(let key in allElements) {
if(allElements.hasOwnProperty(key)) {
const element = allElements[key]
if(element.id === id) {
elementsWithId.push(element)
}
}
}
return elementsWithId
}
EDIT, ES6 FTW:
function getElementsById(id) {
return [...document.getElementsByTagName('*')].filter(element => element.id === id)
}
Another solution is:
>>> "".join(list(hex(255))[2:])
'ff'
Probably an archaic answer, but functional.
A Pair class :
public class Pair<K, V> {
private final K element0;
private final V element1;
public static <K, V> Pair<K, V> createPair(K element0, V element1) {
return new Pair<K, V>(element0, element1);
}
public Pair(K element0, V element1) {
this.element0 = element0;
this.element1 = element1;
}
public K getElement0() {
return element0;
}
public V getElement1() {
return element1;
}
}
usage :
Pair<Integer, String> pair = Pair.createPair(1, "test");
pair.getElement0();
pair.getElement1();
Immutable, only a pair !
You shouldn't. a Collection
avoids talking about indexes specifically because it might not make sense for the specific collection. For example, a List
implies some form of ordering, but a Set
does not.
Collection<String> myCollection = new HashSet<String>();
myCollection.add("Hello");
myCollection.add("World");
for (String elem : myCollection) {
System.out.println("elem = " + elem);
}
System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);
gives me:
elem = World
elem = Hello
myCollection.toArray()[0] = World
whilst:
myCollection = new ArrayList<String>();
myCollection.add("Hello");
myCollection.add("World");
for (String elem : myCollection) {
System.out.println("elem = " + elem);
}
System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);
gives me:
elem = Hello
elem = World
myCollection.toArray()[0] = Hello
Why do you want to do this? Could you not just iterate over the collection?
Since Spring 3.0, you can add a line like
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean" />
to your applicationContext.xml
(or where you configure things).
As Dmitry Chornyi points out in a comment, Java based configuration looks like:
@Bean public ConversionService conversionService() {
return new DefaultConversionService();
}
This activates the new configuration service which supports converting String
to Collection
types.
If you do not activate this configuration service, Spring falls back on its legacy property editors as configuration services, which do not support this kind of conversion.
Converting to collections of other types works, too:
@Value("${my.list.of.ints}")
private List<Integer> myList
will work with a line like
my.list.of.ints= 1, 2, 3, 4
No problems with whitespace there, the ConversionServiceFactoryBean
takes care of it.
In a Spring application, you typically configure a ConversionService instance per Spring container (or ApplicationContext). That ConversionService will be picked up by Spring and then used whenever a type conversion needs to be performed by the framework. [...] If no ConversionService is registered with Spring, the original PropertyEditor-based system is used.
Better late than never! Here is how we can do it(for learning purpose only)-
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class SoftDrink {
String name;
String color;
int volume;
SoftDrink (String name, String color, int volume) {
this.name = name;
this.color = color;
this.volume = volume;
}
}
public class ListItemComparision {
public static void main (String...arg) {
List<SoftDrink> softDrinkList = new ArrayList<SoftDrink>() ;
softDrinkList .add(new SoftDrink("Faygo", "ColorOne", 4));
softDrinkList .add(new SoftDrink("Fanta", "ColorTwo", 3));
softDrinkList .add(new SoftDrink("Frooti", "ColorThree", 2));
softDrinkList .add(new SoftDrink("Freshie", "ColorFour", 1));
Collections.sort(softDrinkList, new Comparator() {
@Override
public int compare(Object softDrinkOne, Object softDrinkTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((SoftDrink)softDrinkOne).name
.compareTo(((SoftDrink)softDrinkTwo).name);
}
});
for (SoftDrink sd : softDrinkList) {
System.out.println(sd.name + " - " + sd.color + " - " + sd.volume);
}
Collections.sort(softDrinkList, new Comparator() {
@Override
public int compare(Object softDrinkOne, Object softDrinkTwo) {
//comparision for primitive int uses compareTo of the wrapper Integer
return(new Integer(((SoftDrink)softDrinkOne).volume))
.compareTo(((SoftDrink)softDrinkTwo).volume);
}
});
for (SoftDrink sd : softDrinkList) {
System.out.println(sd.volume + " - " + sd.color + " - " + sd.name);
}
}
}
The limit of the enhanced format notifications is documented here.
It explicitly states:
The payload must not exceed 256 bytes and must not be null-terminated.
ascandroli claims above that they were able to send messages with 1400 characters. My own testing with the new notification format showed that a message just 1 byte over the 256 byte limit was rejected. Given that the docs are very explicit on this point I suggest it is safer to use 256 regardless of what you may be able to achieve experimentally as there is no guarantee Apple won't change it to 256 in the future.
As for the alert text itself, if you can fit it in the 256 total payload size then it will be displayed by iOS. They truncate the message that shows up on the status bar, but if you open the notification center, the entire message is there. It even renders newline characters \n
.
Use std::make_pair
:
revenue.push_back(std::make_pair("string",map[i].second));
Either run basicConfig
with stream=sys.stdout
as the argument prior to setting up any other handlers or logging any messages, or manually add a StreamHandler
that pushes messages to stdout to the root logger (or any other logger you want, for that matter).
This is best answered with examples.
Think of Floyd-Warshall for example. We have to use an adjacency matrix, or the algorithm will be asymptotically slower.
Or what if it's a dense graph on 30,000 vertices? Then an adjacency matrix might make sense, as you'll be storing 1 bit per pair of vertices, rather than the 16 bits per edge (the minimum that you would need for an adjacency list): that's 107 MB, rather than 1.7 GB.
But for algorithms like DFS, BFS (and those that use it, like Edmonds-Karp), Priority-first search (Dijkstra, Prim, A*), etc., an adjacency list is as good as a matrix. Well, a matrix might have a slight edge when the graph is dense, but only by an unremarkable constant factor. (How much? It's a matter of experimenting.)
I would suggest two interesting lectures:
1.
The with
statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try...except...finally
usage patterns to be encapsulated for convenient reuse.
2. You could do something like:
with open("foo.txt") as foo_file:
data = foo_file.read()
OR
from contextlib import nested
with nested(A(), B(), C()) as (X, Y, Z):
do_something()
OR (Python 3.1)
with open('data') as input_file, open('result', 'w') as output_file:
for line in input_file:
output_file.write(parse(line))
OR
lock = threading.Lock()
with lock:
# Critical section of code
3.
I don't see any Antipattern here.
Quoting Dive into Python:
try..finally is good. with is better.
4.
I guess it's related to programmers's habit to use try..catch..finally
statement from other languages.
I faced similar issue due to local vs remote referencing
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script src="lib/js/ui-grid/3.0.7/ui-grid.js"></script>
As ui-grid.js is dependent on angular.js, ui-grid requires angular.js by the time its loaded. But in the above case, ui-grid.js [locally saved reference file] is loaded before angularjs was loaded [from internet],
The problem was solved if I had both angular.js and ui-grid referenced locally and as well declaring angular.js before ui-grid
<script src="lib/js/angularjs/1.4.3/angular.js"></script>
<script src="lib/js/ui-grid/3.0.7/ui-grid.js"></script>
This is an old question (2008) so there are many more options now than there were then:
UPDATES (projects still active in 2020):
A caveat on picking HTTP/REST clients. Make sure to check what your framework stack is using for an HTTP client, how it does threading, and ideally use the same client if it offers one. That is if your using something like Vert.x or Play you may want to try to use its backing client to participate in whatever bus or reactor loop the framework provides... otherwise be prepared for possibly interesting threading issues.
if [ ${foo:+1} ]
then
echo "yes"
fi
prints yes
if the variable is set. ${foo:+1}
will return 1 when the variable is set, otherwise it will return empty string.
ngStyle
accepts a map:
$scope.myStyle = {
"width" : "900px",
"background" : "red"
};
you can do:
for k in ax.get_xmajorticklabels():
if some-condition:
k.set_color(any_colour_you_like)
draw()
LinkedHashMap will return the elements in the order they were inserted into the map when you iterate over the keySet(), entrySet() or values() of the map.
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("id", "1");
map.put("name", "rohan");
map.put("age", "26");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
This will print the elements in the order they were put into the map:
id = 1
name = rohan
age = 26
You can use a link to invoke history.go(-1)
in Javascript, which is essentially equivalent to clicking the Back button. Ideally, however, it'd be better to just create a link back to the URL from whence the user was posted to the form - that way the proper "flow" of history is preserved and the user doesn't wonder why they have something to click "Forward" to which is actually just submitting the form again.
A tricky way is add an empty section for header. Because section has no cell, it will not floating at all.
As mentioned in have debugger run application as different user (linked above), another extremely simple way to do this which doesn't require any more tools:
Click "Run as different user"
Enter credentials of the other user in the next pop-up window
Now when you debug the solution it will be with the other user's permissions.
Hint: if you are going to run multiple instances of Visual Studio, change the theme of it (like to "dark") so you can keep track of which one is which easily).
PHP has several libraries for XML Manipulation.
The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows
<?php
$doc = new DOMDocument( );
$ele = $doc->createElement( 'Root' );
$ele->nodeValue = 'Hello XML World';
$doc->appendChild( $ele );
$doc->save('MyXmlFile.xml');
?>
Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.
You can sort-of do that with objects, as in the following.
Dim w As New Widget
But not with strings or variants.
http://developer.android.com/guide/topics/ui/layout-objects.html#linearlayout
layout_weight defines how much space the control must obtain respectively to other controls.
I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out
params. In JavaScript it can be implemented in the following manner:
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
}
The usage:
var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);
I'm not sure if your findElements statement gets you all the divs. I would try the following:
List<WebElement> elementsRoot = driver.findElements(By.xpath("//div[@class=\"facetContainerDiv\"]/div));
for(int i = 0; i < elementsRoot.size(); ++i) {
WebElement checkbox = elementsRoot.get(i).findElement(By.xpath("./label/input"));
checkbox.click();
blah blah blah
}
The idea here is that you get the root element then use another a 'sub' xpath or any selector you like to find the node element. Of course the xpath or selector may need to be adjusted to properly find the element you want.
Easiest and clearest way I'd say is:
var maxHeight = 0, maxHeightElement = null;
$('.panel').each(function(){
if ($(this).height() > maxHeight) {
maxHeight = $(this).height();
maxHeightElement = $(this);
}
});
\r
instead of \n
.Substituting by \n
inserts a null character into the text. To get a newline, use \r
. When searching for a newline, you’d still use \n
, however. This asymmetry is due to the fact that \n
and \r
do slightly different things:
\n
matches an end of line (newline), whereas \r
matches a carriage return. On the other hand, in substitutions \n
inserts a null character whereas \r
inserts a newline (more precisely, it’s treated as the input CR). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it). xxd
shows a hexdump of the resulting file.
echo bar > test
(echo 'Before:'; xxd test) > output.txt
vim test '+s/b/\n/' '+s/a/\r/' +wq
(echo 'After:'; xxd test) >> output.txt
more output.txt
Before:
0000000: 6261 720a bar.
After:
0000000: 000a 720a ..r.
In other words, \n
has inserted the byte 0x00 into the text; \r
has inserted the byte 0x0a.
No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?
$array = array(
"foo" => "bar",
"bar" => "foo"
);
// as of PHP 5.4
$array = [
"foo" => "bar",
"bar" => "foo",
];
The following line is allowed with the above array but would give an error if it was a dictionary.
print $array[0]
Python has both arrays and dictionaries.
"If you want the root of your module's export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports instead of exports." - http://nodejs.org/api/modules.html
Yeah, resolved the exception by adding commons-collections4-4.1 jar file to the CLASSPATH user varible of system. Downloaded from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1
Visual Studio should now ask your GitHub credentials and then proceed to upload your solution.
Since I have my Windows account connected to Visual Studio to work with Team Foundation I don't know if it works without an account, Visual Studio will keep track of who commits so if you are not logged in it will probably ask you to first.
I have written code that sniffs IE4 or greater and is currently functioning perfectly in sites for my company's clients, as well as my own personal sites.
Include the following enumerated constant and function variables into a javascript include file on your page...
//methods
var BrowserTypes = {
Unknown: 0,
FireFox: 1,
Chrome: 2,
Safari: 3,
IE: 4,
IE7: 5,
IE8: 6,
IE9: 7,
IE10: 8,
IE11: 8,
IE12: 8
};
var Browser = function () {
try {
//declares
var type;
var version;
var sVersion;
//process
switch (navigator.appName.toLowerCase()) {
case "microsoft internet explorer":
type = BrowserTypes.IE;
sVersion = navigator.appVersion.substring(navigator.appVersion.indexOf('MSIE') + 5, navigator.appVersion.length);
version = parseFloat(sVersion.split(";")[0]);
switch (parseInt(version)) {
case 7:
type = BrowserTypes.IE7;
break;
case 8:
type = BrowserTypes.IE8;
break;
case 9:
type = BrowserTypes.IE9;
break;
case 10:
type = BrowserTypes.IE10;
break;
case 11:
type = BrowserTypes.IE11;
break;
case 12:
type = BrowserTypes.IE12;
break;
}
break;
case "netscape":
if (navigator.userAgent.toLowerCase().indexOf("chrome") > -1) { type = BrowserTypes.Chrome; }
else { if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) { type = BrowserTypes.FireFox } };
break;
default:
type = BrowserTypes.Unknown;
break;
}
//returns
return type;
} catch (ex) {
}
};
Then all you have to do is use any conditional functionality such as...
ie. value = (Browser() >= BrowserTypes.IE) ? node.text : node.textContent;
or WindowWidth = (((Browser() >= BrowserTypes.IE9) || (Browser() < BrowserTypes.IE)) ? window.innerWidth : document.documentElement.clientWidth);
or sJSON = (Browser() >= BrowserTypes.IE) ? xmlElement.text : xmlElement.textContent;
Get the idea? Hope this helps.
Oh, you might want to keep it in mind to QA the Browser() function after IE10 is released, just to verify they didn't change the rules.
For me, an issue where json_encode would return null encoding of an entity was because my jsonSerialize implementation fetched entire objects for related entities; I solved the issue by making sure that I fetched the ID of the related/associated entity and called ->toArray() when there were more than one entity associated with the object to be json serialized. Note, I'm speaking about cases where one implements JsonSerializable
on entities.
There is one caveat when you want to plot the histogram from a 2-d numpy array. You need to swap the 2 axes.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.normal(size=(2, 300))
# swapped_data.shape == (300, 2)
swapped_data = np.swapaxes(x, axis1=0, axis2=1)
plt.hist(swapped_data, bins=30, label=['x', 'y'])
plt.legend()
plt.show()
The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.
Many of the answers seem to me to be ignoring the stated requirements:
These two together rule out a LINQ sequence of bytes - anything with yield
is going to make it impossible to get the final size without iterating through the whole sequence.
If those aren't the real requirements of course, LINQ could be a perfectly good solution (or the IList<T>
implementation). However, I'll assume that Superdumbell knows what he wants.
(EDIT: I've just had another thought. There's a big semantic difference between making a copy of the arrays and reading them lazily. Consider what happens if you change the data in one of the "source" arrays after calling the Combine
(or whatever) method but before using the result - with lazy evaluation, that change will be visible. With an immediate copy, it won't. Different situations will call for different behaviour - just something to be aware of.)
Here are my proposed methods - which are very similar to those contained in some of the other answers, certainly :)
public static byte[] Combine(byte[] first, byte[] second)
{
byte[] ret = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
return ret;
}
public static byte[] Combine(byte[] first, byte[] second, byte[] third)
{
byte[] ret = new byte[first.Length + second.Length + third.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
Buffer.BlockCopy(third, 0, ret, first.Length + second.Length,
third.Length);
return ret;
}
public static byte[] Combine(params byte[][] arrays)
{
byte[] ret = new byte[arrays.Sum(x => x.Length)];
int offset = 0;
foreach (byte[] data in arrays)
{
Buffer.BlockCopy(data, 0, ret, offset, data.Length);
offset += data.Length;
}
return ret;
}
Of course the "params" version requires creating an array of the byte arrays first, which introduces extra inefficiency.
Definition
Aggregate method is an extension method for generic collections. Aggregate method applies a function to each item of a collection. Not just only applies a function, but takes its result as initial value for the next iteration. So, as a result, we will get a computed value (min, max, avg, or other statistical value) from a collection.
Therefore, Aggregate method is a form of safe implementation of a recursive function.
Safe, because the recursion will iterate over each item of a collection and we can’t get any infinite loop suspension by wrong exit condition. Recursive, because the current function’s result is used as a parameter for the next function call.
Syntax:
collection.Aggregate(seed, func, resultSelector);
How it works:
var nums = new[]{1, 2};
var result = nums.Aggregate(1, (result, n) => result + n); //result = (1 + 1) + 2 = 4
var result2 = nums.Aggregate(0, (result, n) => result + n, response => (decimal)response/2.0); //result2 = ((0 + 1) + 2)*1.0/2.0 = 3*1.0/2.0 = 3.0/2.0 = 1.5
Practical usage:
int n = 7;
var numbers = Enumerable.Range(1, n);
var factorial = numbers.Aggregate((result, x) => result * x);
which is doing the same thing as this function:
public static int Factorial(int n)
{
if (n < 1) return 1;
return n * Factorial(n - 1);
}
var numbers = new[]{3, 2, 6, 4, 9, 5, 7};
var avg = numbers.Aggregate(0.0, (result, x) => result + x, response => (double)response/(double)numbers.Count());
var min = numbers.Aggregate((result, x) => (result < x)? result: x);
var path = @“c:\path-to-folder”;
string[] txtFiles = Directory.GetFiles(path).Where(f => f.EndsWith(“.txt”)).ToArray<string>();
var output = txtFiles.Select(f => File.ReadAllText(f, Encoding.Default)).Aggregate<string>((result, content) => result + content);
File.WriteAllText(path + “summary.txt”, output, Encoding.Default);
Console.WriteLine(“Text files merged into: {0}”, output); //or other log info
You need something to center your form into. But because you didn't specify a height for your html and body, it would just wrap content - and not the viewport. In other words, there was no room where to center the item in.
html, body {
height: 100%;
}
.container, .row.justify-content-center.align-items-center {
height: 100%;
min-height: 100%;
}
There are at least two ways to do that:
defining context param in web.xml – that breaks "one package for all environments" statement. I don't recommend that
defining system property -Dspring.profiles.active=your-active-profile
I believe that defining system property is a much better approach. So how to define system property for Tomcat? On the internet I could find a lot of advice like "modify catalina.sh" because you will not find any configuration file for doing stuff like that. Modifying catalina.sh is a dirty unmaintainable solution. There is a better way to do that.
Just create file setenv.sh in Tomcat's bin directory with content:
JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=dev"
and it will be loaded automatically during running catalina.sh start or run.
Here is a blog describing the above solution.
In my case, it wasn't working until I also installed the following package : libatlas-base-dev, gfortran
sudo apt-get install libatlas-base-dev gfortran
Then run pip install scipy
By default, post_max_size should be 4 times greater than upload_max_filesize.
In turn
memory_limit should be 16 times greater than post_max_size
Sharing files between a docker container and the host system, or between separate containers is best accomplished using volumes.
Having your app running in another container is probably your best solution since it will ensure that your whole application can be well isolated and easily deployed. What you're trying to do sounds very close to the setup described in this excellent blog post, take a look!
Example using std::vector
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
int main()
{
/// Initilaize vector using intitializer list ( requires C++11 )
std::vector<std::string> names = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
// Sort names using std::sort
std::sort(names.begin(), names.end() );
// Print using range-based and const auto& for ( both requires C++11 )
for(const auto& currentName : names)
{
std::cout << currentName << std::endl;
}
//... or by using your orignal for loop ( vector support [] the same way as plain arrays )
for(int y = 0; y < names.size(); y++)
{
std:: cout << names[y] << std::endl; // you were outputting name[z], but only increasing y, thereby only outputting element z ( 14 )
}
return 0;
}
This completely avoids using plain arrays, and lets you use the std::sort function. You might need to update you compiler to use the = {...}
You can instead add them by using vector.push_back("name")
So you want the code to the pin it button without installing the button? If so just paste this code in the place of the url of the page you're pinning from. It should function as a pin it button without the button.
javascript:void((function(){var%20e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);document.body.appendChild(e)})());
you just need to put this
($('#{{ form.email.id_for_label }}').attr("placeholder","Work email address"));
($('#{{ form.password1.id_for_label }}').attr("placeholder","Password"));
I'll throw another method on the pile...
scipy.interpolate
's many interpolating splines are capable of providing derivatives. So, using a linear spline (k=1
), the derivative of the spline (using the derivative()
method) should be equivalent to a forward difference. I'm not entirely sure, but I believe using a cubic spline derivative would be similar to a centered difference derivative since it uses values from before and after to construct the cubic spline.
from scipy.interpolate import InterpolatedUnivariateSpline
# Get a function that evaluates the linear spline at any x
f = InterpolatedUnivariateSpline(x, y, k=1)
# Get a function that evaluates the derivative of the linear spline at any x
dfdx = f.derivative()
# Evaluate the derivative dydx at each x location...
dydx = dfdx(x)
If you know the dimensions of your image, then adding a border to the UIImageView's layer is the best solution AFAIK. Infact, you can simply setFrame your imageView to x,y,image.size.width,image.size.height
In case you have an ImageView of a fixed size with dynamically loaded images which are getting resized (or scaled to AspectFit), then your aim is to resize the imageview to the new resized image.
The shortest way to do this:
// containerView is my UIImageView
containerView.layer.borderWidth = 7;
containerView.layer.borderColor = [UIColor colorWithRed:0.22 green:0.22 blue:0.22 alpha:1.0].CGColor;
// this is the key command
[containerView setFrame:AVMakeRectWithAspectRatioInsideRect(image.size, containerView.frame)];
But to use the AVMakeRectWithAspectRatioInsideRect, you need to add this
#import <AVFoundation/AVFoundation.h>
import statement to your file and also include the AVFoundation framework in your project (comes bundled with the SDK).
The php mysql api is deprecated. It's kaput --- going away -- not to be used, finito.
If you have a modern version of PHP (> 5.6) then Wordpress should automatically switch to make use of mysqli. That should be your first attempt.
If you can not update your php, rather than attempting to resurrect something that php no longer supports, just patch your wordpress: http://wordpress.org/plugins/mysqli/
To grant a permission:
grant select on schema_name.sequence_name to user_or_role_name;
To check which permissions have been granted
select * from all_tab_privs where TABLE_NAME = 'sequence_name'
If you define function type first then it would be looked like
type Callback = (n: number) => void;
class Foo {
save(callback: Callback) : void {
callback(42);
}
}
var foo = new Foo();
var stringCallback = (result: string) : void => {
console.log(result);
}
var numberCallback = (result: number) : void => {
console.log(result);
}
foo.save(stringCallback); //--will be showing error
foo.save(numberCallback);
Without function type by using plain property syntax it would be:
class Foo {
save(callback: (n: number) => void) : void {
callback(42);
}
}
var foo = new Foo();
var stringCallback = (result: string) : void => {
console.log(result);
}
var numberCallback = (result: number) : void => {
console.log(result);
}
foo.save(stringCallback); //--will be showing error
foo.save(numberCallback);
If you want by using an interface function like c# generic delegates it would be:
interface CallBackFunc<T, U>
{
(input:T): U;
};
class Foo {
save(callback: CallBackFunc<number,void>) : void {
callback(42);
}
}
var foo = new Foo();
var stringCallback = (result: string) : void => {
console.log(result);
}
var numberCallback = (result: number) : void => {
console.log(result);
}
let strCBObj:CallBackFunc<string,void> = stringCallback;
let numberCBObj:CallBackFunc<number,void> = numberCallback;
foo.save(strCBObj); //--will be showing error
foo.save(numberCBObj);
The purpose is that you can give a default value if the key is not found, which is very useful
dictionary.get("Name",'harry')
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])
#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)
#legend
cbar = plt.colorbar(heatmap)
cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()
#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()
You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.
QueryTypes is the canonical answer as of EF Core 2.1, but there is another way I have used when migrating from a database first approach (the view is already created in the database):
you should use
"bAutoWidth
" property of datatable and give width to each td/column in %
$(".table").dataTable({"bAutoWidth": false ,
aoColumns : [
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "10%"},
]
});
Hope this will help.
For what it is worth: I was experiencing a similar issue trying to update a MySQL table via Perl. The update would fail when an empty string value (translated from a null value from a read from another platform) was passed to the date column ('dtcol' in the code sample below). I was finally successful getting the data updated by using an IF statement embedded in my update statement:
...
my $stmnt='update tbl set colA=?,dtcol=if(?="",null,?) where colC=?';
my $status=$dbh->do($stmt,undef,$iref[1],$iref[2],$iref[2],$ref[0]);
...
modify the file:build.gradle(app directory). in fact:you should not change this file , only by this to get sync tips,then sync project.
Many others have provided good info for sleeping. I agree with Wedge that a sleep seldom the most appropriate solution.
If you are sleeping as you wait for something, then you are better off actually waiting for that thing/event. Look at Condition Variables for this.
I don't know what OS you are trying to do this on, but for threading and synchronisation you could look to the Boost Threading libraries (Boost Condition Varriable).
Moving now to the other extreme if you are trying to wait for exceptionally short periods then there are a couple of hack style options. If you are working on some sort of embedded platform where a 'sleep' is not implemented then you can try a simple loop (for/while etc) with an empty body (be careful the compiler does not optimise it away). Of course the wait time is dependant on the specific hardware in this case. For really short 'waits' you can try an assembly "nop". I highly doubt these are what you are after but without knowing why you need to wait it's hard to be more specific.
import("time")
layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
fmt.Println(err)
}
fmt.Println(t)
gives:
>> 2014-11-12 11:45:26.371 +0000 UTC
Sparx's Enterprise Architect performs round-tripping of Python source. They have a free time-limited trial edition.
Here's an example of getting the stack via the traceback module, and printing it:
import traceback
def f():
g()
def g():
for line in traceback.format_stack():
print(line.strip())
f()
# Prints:
# File "so-stack.py", line 10, in <module>
# f()
# File "so-stack.py", line 4, in f
# g()
# File "so-stack.py", line 7, in g
# for line in traceback.format_stack():
If you really only want to print the stack to stderr, you can use:
traceback.print_stack()
Or to print to stdout (useful if want to keep redirected output together), use:
traceback.print_stack(file=sys.stdout)
But getting it via traceback.format_stack()
lets you do whatever you like with it.
Note:drawRect
and fillRect
are different.
Draws the outline of the specified rectangle:
public void drawRect(int x,
int y,
int width,
int height)
Fills the specified rectangle. The rectangle is filled using the graphics context's current color:
public abstract void fillRect(int x,
int y,
int width,
int height)
I think is that the best is to install the virtual environment in a path inside the repository folder, maybe is better inclusive to use a subdirectory dedicated to the environment (I have deleted accidentally my entire project when force installing a virtual environment in the repository root folder, good that I had the project saved in its latest version in Github).
Either the automated installer, or the documentation should indicate the virtualenv path as a relative path, this way you won't run into problems when sharing the project with other people. About the packages, the packages used should be saved by pip freeze -r requirements.txt
.
adb devices
.This works on Windows and Ubuntu Linux, and should work on Mac as well.
If you ensure that every place holder, in each of the contexts involved, is ignoring unresolvable keys then both of these approaches work. For example:
<context:property-placeholder
location="classpath:dao.properties,
classpath:services.properties,
classpath:user.properties"
ignore-unresolvable="true"/>
or
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:dao.properties</value>
<value>classpath:services.properties</value>
<value>classpath:user.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>