I believe that is is a move operator. operator=
is the assignment operator, say vector x = vector y
. The clear()
function call sounds like as if it is deleting the contents of the vector to prevent a memory leak. The operator returns a pointer to the new vector.
This way,
std::vector<int> a(100, 10);
std::vector<int> b = a;
for(unsigned int i = 0; i < b.size(); i++)
{
std::cout << b[i] << ' ';
}
Even though we gave vector a values, vector b has the values. It's the magic of the operator=()
!
That is the output of Object's "toString()" implementation. If your class overrides toString(), it will print something entirely different.
A logical address is the address at which an item (memory cell, storage element, network host) appears to reside from the perspective of an executing application program.
According to the manual, in CPython id()
is the actual memory address of the variable. If you want it in hex format, call hex()
on it.
x = 5
print hex(id(x))
this will print the memory address of x.
Use %p
, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u
expects an unsigned int
, but what if void*
has a different size or alignment requirement than unsigned int
?)
*) [See Jonathan's fine answer!] Alternatively to %p
, you can use pointer-specific macros from <inttypes.h>
, added in C99.
All object pointers are implicitly convertible to void*
in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):
printf("x lives at %p.\n", (void*)&x);
With ctypes, you can achieve the same thing with
>>> import ctypes
>>> a = (1,2,3)
>>> ctypes.addressof(a)
3077760748L
Documentation:
addressof(C instance) -> integer
Return the address of the C instance internal buffer
Note that in CPython, currently id(a) == ctypes.addressof(a)
, but ctypes.addressof
should return the real address for each Python implementation, if
Edit: added information about interpreter-independence of ctypes
When you intend to print the memory address of any variable or a pointer, using %d
won't do the job and will cause some compilation errors, because you're trying to print out a number instead of an address, and even if it does work, you'd have an intent error, because a memory address is not a number. the value 0xbfc0d878
is surely not a number, but an address.
What you should use is %p
. e.g.,
#include<stdio.h>
int main(void) {
int a;
a = 5;
printf("The memory address of a is: %p\n", (void*) &a);
return 0;
}
Good luck!
Since you already seem to have solved the basic pointer address display, here's how you would check the address of a double pointer:
char **a;
char *b;
char c = 'H';
b = &c;
a = &b;
You would be able to access the address of the double pointer a
by doing:
printf("a points at this memory location: %p", a);
printf("which points at this other memory location: %p", *a);
I had the same problem ! but to solve it just modify your code as following.
public static void startMusic() {
URL songPath = YouClassName.class.getClassLoader().getResource("background.midi");
}
this worked fine with me hope it will also work fine with you.
There is a package called timeout-decorator that you can use to time out any python function.
@timeout_decorator.timeout(5)
def mytest():
print("Start")
for i in range(1,10):
time.sleep(1)
print("{} seconds have passed".format(i))
It uses the signals approach that some answers here suggest. Alternatively, you can tell it to use multiprocessing instead of signals (e.g. if you are in a multi-thread environment).
I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was
<?xmlversion="1.0"encoding="utf-8"?>
which was causing the error. When I removed that line, so that the stylesheet started with the line
<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:
<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8" />
<xsl:template match="/">
<xsl:text>From,To~</xsl:text>
<xsl:text>
</xsl:text>
<xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
<xsl:value-of select="@DTS:From"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="@DTS:To"/>
<xsl:text>~</xsl:text>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.
Trying to solve the same problem (validation without getting into complex plugins and libraries), I created jQuery.serializeJSON, that improves serializeArray to support any kind of nested objects.
This plugin got very popular, but in another project I was using Backbone.js, where I would like to write the validation logic in the Backbone.js models. Then I created Backbone.Formwell, which allows you to show the errors returned by the validation method directly in the form.
See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:
Session session = entityManager.unwrap(Session.class);
Not particularly easily- if you've lost the pointer to the tip of a branch, it's rather like finding a needle in a haystack. You can find all the commits that don't appear to be referenced any more- git fsck --unreachable
will do this for you- but that will include commits that you threw away after a git commit --amend
, old commits on branches that you rebased etc etc. So seeing all these commits at once is quite likely far too much information to wade through.
So the flippant answer is, don't lose track of things you're interested in. More seriously, the reflogs will hold references to all the commits you've used for the last 60 days or so by default. More importantly, they will give some context about what those commits are.
In my case Mac OS High Sierra 10.13.6
brew -v
OutPut-
Homebrew 2.2.2
Homebrew/homebrew-core (git revision 71aa; last commit 2020-01-07)
Homebrew/homebrew-cask (git revision 84f00; last commit 2020-01-07)
Today, you could try editorconfig, there is also a vim plugin for it. With this, you are able not only change indentation size in vim, but in many other editors, keep consistent coding styles.
Below is a simple editorconfig, as you can see, the python files will have 4 spaces for indentation, and pug template files will only have 2.
# 4 space indentation for python files
[*.py]
indent_style = space
indent_size = 4
# 2 space indentation for pug templates
[*.pug]
indent_size = 2
To check if a string variable contains a valid email address, the easiest way is to test it against a regular expression. There is a good discussion of various regex's and their trade-offs at regular-expressions.info.
Here is a relatively simple one that leans on the side of allowing some invalid addresses through: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$
How you can use regular expressions depends on the version of iOS you are using.
You can use NSRegularExpression
, which allows you to compile and test against a regular expression directly.
Does not include the NSRegularExpression
class, but does include NSPredicate
, which can match against regular expressions.
NSString *emailRegex = ...;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:checkString];
Read a full article about this approach at cocoawithlove.com.
Does not include any regular expression matching in the Cocoa libraries. However, you can easily include RegexKit Lite in your project, which gives you access to the C-level regex APIs included on iOS 2.0.
use dos2unix
on your script file.
When to use extends and super
Wildcards are most useful in method parameters. They allow for the necessary flexibility in method interfaces.
People are often confused when to use extends and when to use super bounds. The rule of thumb is the get-put principle. If you get something from a parametrized container, use extends.
int totalFuel(List<? extends Vehicle> list) {
int total = 0;
for(Vehicle v : list) {
total += v.getFuel();
}
return total;}
The method totalFuel gets Vehicles from the list, asks them about how much fuel they have, and computes the total. If you put objects into a parameterized container, use super.
int totalValue(Valuer<? super Vehicle> valuer) {
int total = 0;
for(Vehicle v : vehicles) {
total += valuer.evaluate(v);
}
return total;}
The method totalValue puts Vehicles into the Valuer. It's useful to know that extends bound is much more common than super.
PUT http://{rm http address:port}/ws/v1/cluster/apps/{appid}/state
{
"state":"KILLED"
}
I suggest you run:
$ brew update && brew upgrade
Until couple of minutes ago I had this problem, too. Because I have an up to date PHP version, I solved it with:
$ brew reinstall php55
Hope that helps.
Nested if's in Excel Are ugly:
=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))
That should cover it.
The value of __FILE__
is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.chdir
anywhere else in your application, this path will expand incorrectly.
puts __FILE__
Dir.chdir '../../'
puts __FILE__
One workaround to this problem is to store the expanded value of __FILE__
outside of any application code. As long as your require
statements are at the top of your definitions (or at least before any calls to Dir.chdir
), this value will continue to be useful after changing directories.
$MY_FILE_PATH = File.expand_path(File.dirname(__FILE__))
# open class and do some stuff that changes directory
puts $MY_FILE_PATH
There is a nice form plugin that allows you to send an HTML form asynchroniously.
$(document).ready(function() {
$('#myForm1').ajaxForm();
});
or
$("select").change(function(){
$('#myForm1').ajaxSubmit();
});
to submit the form immediately
Just tried this solution, we don't have to even write int.
int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);
This thing will also work, it automatically detects the type of string.
There are two kinds of input value: field's property and field's html attribute.
If you use keyup event and field.value you shuld get current value of the field. It's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=""). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).
I upgraded to my Git for Windows to latest (2.30.0) 64-bit and it works fine now. get the latest from the url https://git-scm.com/download/win and run the commands below to verify. $ git --version $ git version 2.30.0.windows.1
$files = array_diff(scandir($dir,SCANDIR_SORT_DESCENDING), array('..', '.'));
print_r($files);
I found the solution with this link : http://pixelsvsbytes.com/blog/2013/02/nice-web-fonts-for-every-browser/
Step by step method :
apt-get install ttfautohint
):ttfautohint --strong-stem-width=g neosansstd-black.ttf neosansstd-black.changed.ttf
I hope this will help.
I like Clay Eclipse plugin. I've only used it with MySQL, but it claims Firebird support.
Usually your testing framework will have an answer for this. But if it's not flexible enough, you can always do this:
try {
somethingThatShouldThrowAnException();
Assert.Fail(); // If it gets to this line, no exception was thrown
} catch (GoodException) { }
As @Jonas points out, this DOES NOT work for catching a base Exception:
try {
somethingThatShouldThrowAnException();
Assert.Fail(); // raises AssertionException
} catch (Exception) {
// Catches the assertion exception, and the test passes
}
If you absolutely must catch Exception, you need to rethrow the Assert.Fail(). But really, this is a sign you shouldn't be hand-writing this; check your test framework for options, or see if you can throw a more meaningful exception to test for.
catch (AssertionException) { throw; }
You should be able to adapt this approach to whatever you like -- including specifying what kinds of exceptions to catch. If you only expect certain types, finish the catch
blocks off with:
} catch (GoodException) {
} catch (Exception) {
// not the right kind of exception
Assert.Fail();
}
Simplest way is to use dimensions in % or em. Just change the base font size everything will change.
Less
@media (max-width: @screen-xs) {
body{font-size: 10px;}
}
@media (max-width: @screen-sm) {
body{font-size: 14px;}
}
h5{
font-size: 1.4rem;
}
Look at all the ways at https://stackoverflow.com/a/21981859/406659
You could use viewport units (vh,vw...) but they dont work on Android < 4.4
Remove annotation type configuration like @Service from the thread run method.
@Service, @Component
Continuing the evolution of this solution I've upped the ante by adding support for multiple root selections and deeper nested selections. This is a further development of JavierCane's solution (which in turn built on tarheel's).
/**_x000D_
* "on edit" event handler_x000D_
*_x000D_
* Based on JavierCane's answer in _x000D_
* _x000D_
* http://stackoverflow.com/questions/21744547/how-do-you-do-dynamic-dependent-drop-downs-in-google-sheets_x000D_
*_x000D_
* Each set of options has it own sheet named after the option. The _x000D_
* values in this sheet are used to populate the drop-down._x000D_
*_x000D_
* The top row is assumed to be a header._x000D_
*_x000D_
* The sub-category column is assumed to be the next column to the right._x000D_
*_x000D_
* If there are no sub-categories the next column along is cleared in _x000D_
* case the previous selection did have options._x000D_
*/_x000D_
_x000D_
function onEdit() {_x000D_
_x000D_
var NESTED_SELECTS_SHEET_NAME = "Sitemap"_x000D_
var NESTED_SELECTS_ROOT_COLUMN = 1_x000D_
var SUB_CATEGORY_COLUMN = NESTED_SELECTS_ROOT_COLUMN + 1_x000D_
var NUMBER_OF_ROOT_OPTION_CELLS = 3_x000D_
var OPTION_POSSIBLE_VALUES_SHEET_SUFFIX = ""_x000D_
_x000D_
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()_x000D_
var activeSheet = SpreadsheetApp.getActiveSheet()_x000D_
_x000D_
if (activeSheet.getName() !== NESTED_SELECTS_SHEET_NAME) {_x000D_
_x000D_
// Not in the sheet with nested selects, exit!_x000D_
return_x000D_
}_x000D_
_x000D_
var activeCell = SpreadsheetApp.getActiveRange()_x000D_
_x000D_
// Top row is the header_x000D_
if (activeCell.getColumn() > SUB_CATEGORY_COLUMN || _x000D_
activeCell.getRow() === 1 ||_x000D_
activeCell.getRow() > NUMBER_OF_ROOT_OPTION_CELLS + 1) {_x000D_
_x000D_
// Out of selection range, exit!_x000D_
return_x000D_
}_x000D_
_x000D_
var sheetWithActiveOptionPossibleValues = activeSpreadsheet_x000D_
.getSheetByName(activeCell.getValue() + OPTION_POSSIBLE_VALUES_SHEET_SUFFIX)_x000D_
_x000D_
if (sheetWithActiveOptionPossibleValues === null) {_x000D_
_x000D_
// There are no further options for this value, so clear out any old_x000D_
// values_x000D_
activeSheet_x000D_
.getRange(activeCell.getRow(), activeCell.getColumn() + 1)_x000D_
.clearDataValidations()_x000D_
.clearContent()_x000D_
_x000D_
return_x000D_
}_x000D_
_x000D_
// Get all possible values_x000D_
var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues_x000D_
.getSheetValues(1, 1, -1, 1)_x000D_
_x000D_
var possibleValuesValidation = SpreadsheetApp.newDataValidation()_x000D_
possibleValuesValidation.setAllowInvalid(false)_x000D_
possibleValuesValidation.requireValueInList(activeOptionPossibleValues, true)_x000D_
_x000D_
activeSheet_x000D_
.getRange(activeCell.getRow(), activeCell.getColumn() + 1)_x000D_
.setDataValidation(possibleValuesValidation.build())_x000D_
_x000D_
} // onEdit()
_x000D_
As Javier says:
And if you wanted to see it in action I've created a demo sheet and you can see the code if you take a copy.
you can use the following command in SQL Developer or SQLPLUS in command prompt to find out the Oracle server version number.
select * from v$version;
in my case it gave me the below mentioned info.
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
PL/SQL Release 11.2.0.1.0 - Production
"CORE 11.2.0.1.0 Production"
TNS for 64-bit Windows: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
import pkg_resources
packages = [dist.project_name for dist in pkg_resources.working_set]
try:
for count, item in enumerate(packages):
print(item, pkg_resources.get_distribution(item).version)
except:
pass here
The indentations might not be perfect. The reason I am using a Try- Except block is that few library names will throw errors because of parsing the library names to process the versions. even though packages variable will contain all the libraries install in your environment.
EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value
syntax is incorrect.
I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
error message. In 2008, the modified script is still successful.
declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)
There's no need for the outer try in your example, so you can at least go down from 3 to 2, and also you don't need closing ;
at the end of the resource list. The advantage of using two try blocks is that all of your code is present up front so you don't have to refer to a separate method:
public List<User> getUser(int userId) {
String sql = "SELECT id, username FROM users WHERE id = ?";
List<User> users = new ArrayList<>();
try (Connection con = DriverManager.getConnection(myConnectionURL);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, userId);
try (ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
users.add(new User(rs.getInt("id"), rs.getString("name")));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
If you're using
To get IntelliJ to recognize custom sourceset as test sources root:
plugin {
idea
}
idea {
module {
testSourceDirs = testSourceDirs + sourceSets["intTest"].allJava.srcDirs
testResourceDirs = testResourceDirs + sourceSets["intTest"].resources.srcDirs
}
}
The target
attribute is your best way of doing this.
<a href="http://www.starfall.com" target="_blank">
will open it in a new tab or window. As for which, it depends on the users settings.
<a href="http://www.starfall.com" target="_self">
is default. It makes the page open in the same tab (or iframe, if that's what you're dealing with).
The next two are only good if you're dealing with an iframe.
<a href="http://www.starfall.com" target="_parent">
will open the link in the iframe that the iframe that had the link was in.
<a href="http://www.starfall.com" target="_top">
will open the link in the tab, no matter how many iframes it has to go through.
Remember that Raspberry Pi does not have real time clock. So even you are connected to internet have to set the time every time you power on or restart.
This is how it works:
sudo raspi-config
in the Raspberry Pi command lineNext thing you can set time using this command
sudo date -s "Mon Aug 12 20:14:11 UTC 2014"
More about data and time
man date
When Pi is connected to computer should have to manually set data and time
Step 1: Add new column with integer or numeric as per your requirement
Step 2: Populate data from varchar column to numeric column
Step 3: drop varchar column
Step 4: change new numeric column name as per old varchar column
I too had the same problem.
I was running node v 6.2 alongside using purgecss within my gulpfile. Problem only occurred when I created a new Laravel project; up until that point, I never had an issue with purgecss.
Following @Quentin's statement - how node versions prior to 7.6 do not support async functions - I decided to update my node version to 9.11.2
This worked for me:
1-
$ npm install -g n
$ n 9.11.2
2-
delete 'node_modules' from the route directory
3-
$ npm install
Still not sure how node/purgecss worked prior to updating.. but this did the trick.
In addition to VAV's answer, The first one was most useful in my environment
select * from USER_ROLE_PRIVS where USERNAME='SAMPLE';
select * from USER_TAB_PRIVS where Grantee = 'SAMPLE';
select * from USER_SYS_PRIVS where USERNAME = 'SAMPLE';
IF (OBJECT_ID('FK_ChannelPlayerSkins_Channels') IS NOT NULL)
It seems that in VBA macro code for an ActiveX checkbox control you use
If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)
and for a Form checkbox control you use
If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)
Also it'd work to just specify ifelse()
twice:
plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))
This is not a Hibernate specific issue (it's just SQL nature), and YES, there IS a solution for both SQL and HQL:
@Peter Lang had the right idea, and you had the correct HQL query. I guess you just needed a new clean run to pick up the query changes ;-)
The below code absolutely works and it is great if you keep all your queries in orm.xml
from CountryDTO c where ((:status is null and c.status is null) or c.status = :status) and c.type =:type
If your parameter String is null then the query will check if the row's status is null as well. Otherwise it will resort to compare with the equals sign.
Notes:
The issue may be a specific MySql quirk. I only tested with Oracle.
The above query assumes that there are table rows where c.status is null
The where clause is prioritized so that the parameter is checked first.
The parameter name 'type' may be a reserved word in SQL but it shouldn't matter since it is replaced before the query runs.
If you needed to skip the :status where_clause altogether; you can code like so:
from CountryDTO c where (:status is null or c.status = :status) and c.type =:type
and it is equivalent to:
sql.append(" where ");
if(status != null){
sql.append(" c.status = :status and ");
}
sql.append(" c.type =:type ");
i faced this issue but i was able to correct this issue by renaming the controller, please have a try on it.
ctrlSub.execSummaryDocuments = function(){};
Even more meaningful :
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
// ...
verify(dependency, never()).someMethod();
The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never
javadoc is here.
You may get some information viewing it in assembly, but I think the easiest thing to do is fire up a virtual machine and see what it does. Make sure you have no open shares or anything like that that it can jump through though ;)
Update: In EF 6.2 there is a like operator
Where(obj => DbFunctions.Like(obj.Column , "%expression%")
If you're going to compile a 64bit version(x86_64) of php use: /usr/lib64/
For architectures (i386 ... i686) use /usr/lib/
I recommend compiling php to the same architecture as apache. As you're using a 64bit linux i asume your apache is also compiled for x86_64.
Principles to keep in mind if you want your applications to be secure:
There are some excellent books and articles online about making your applications secure:
Train your developers on application security best pratices
Codebashing (paid)
Security Innovation(paid)
Security Compass (paid)
OWASP WebGoat (free)
I was facing the same problem. What I did is I right clicked the project->properties and from "Select/Binary Format" combo box, I selected JDK 6. Then I did clean and built and now when I click the Jar, It works just fine.
I agree with @haha on this one, for the most part. But there are several cross-browser related issues with using the "float:right" and could ultimately give you more of a headache than you want. If you know what the widths are going to be for each column use a float:left on both and save yourself the trouble. Another thing you can incorporate into your methodology is build column classes into your CSS.
So try something like this:
CSS
.col-wrapper{width:960px; margin:0 auto;}
.col{margin:0 10px; float:left; display:inline;}
.col-670{width:670px;}
.col-250{width:250px;}
HTML
<div class="col-wrapper">
<div class="col col-670">[Page Content]</div>
<div class="col col-250">[Page Sidebar]</div>
</div>
The results are not in the Output window but in the Test Results Detail (TestResult Pane at the bottom, right click on on Test Results and go to TestResultDetails).
This works with Debug.WriteLine and Console.WriteLine.
An alternative approach is to set the width of the html element to 100vw. On many if not most browsers, this negates the effect of scrollbars on the width.
html { width: 100vw; }
Running source
from a cronfile won't work as cron uses /bin/sh
as its default shell, which doesn't support source
. You need to set the SHELL environment variable to be /bin/bash
:
SHELL=/bin/bash
*/10 * * * * root source /path/to/virtualenv/bin/activate && /path/to/build/manage.py some_command > /dev/null
It's tricky to spot why this fails as /var/log/syslog
doesn't log the error details. Best to alias yourself to root so you get emailed with any cron errors. Simply add yourself to /etc/aliases
and run sendmail -bi
.
More info here: http://codeinthehole.com/archives/43-Running-django-cronjobs-within-a-virtualenv.html
the link above is changed to: https://codeinthehole.com/tips/running-django-cronjobs-within-a-virtualenv/
df[df['Value']==df['Value'].max()]
This will return the entire row with max value
Select * from table where name like search_criteria
if you are expecting the user to add their own wildcards...
On Windows 7 for example, the following set of commands/operations could be used.
Create an personal environment variable, double backslashes are mandatory:
%NPM_HOME%
C:\\SomeFolder\\SubFolder\\
Now, set the config values to the new folders (examplary file names):
npm config set prefix "%NPM_HOME%\\npm"
npm config set cache "%NPM_HOME%\\npm-cache"
npm config set tmp "%NPM_HOME%\\temp"
Optionally, you can purge the contents of the original folders before the config is changed.
Delete the npm-cache npm cache clear
List the npm modules npm -g ls
Delete the npm modules
npm -g rm name_of_package1 name_of_package2
The command line for that is:
node -v
Or
node --version
Note:
If node -v
doesn't work, but nodejs -v
does, then something's not set up quite right on your system. See this other question for ways to fix it.
It's convenient to define a macro for get current timestamp
class Constant {
struct Time {
let now = { round(NSDate().timeIntervalSince1970) } // seconds
}
}
Then you can use let timestamp = Constant.Time.now()
Use Array.prototype.map()
with an arrow function:
const arrayColumn = (arr, n) => arr.map(x => x[n]);_x000D_
_x000D_
const twoDimensionalArray = [_x000D_
[1, 2, 3],_x000D_
[4, 5, 6],_x000D_
[7, 8, 9],_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 0));
_x000D_
Note: Array.prototype.map()
and arrow functions are part of ECMAScript 6 and not supported everywhere, see ECMAScript 6 compatibility table.
@echo off :start :: Insert your code here echo.%%1 is now:%~1 :: End insert your code here if "%~2" NEQ "" ( shift goto :start )
SET NOCOUNT ON; Above code will stop the message generated by sql server engine to fronted result window after the DML/DDL command execution.
Why we do it? As SQL server engine takes some resource to get the status and generate the message, it is considered as overload to the Sql server engine.So we set the noncount message on.
git config --system http.sslcainfo /bin/curl-ca-bundle.crt
This works. You don't have to give full path.
There is a special function made for this Path.Combine()
var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");
If you right click on any result of "Edit Top 200 Rows" query in SSMS you will see the option "Pane -> SQL". It then shows the SQL Query that was run, which you can edit as you wish.
In SMSS 2012 and 2008, you can use Ctrl+3 to quickly get there.
Flexbox spec editor here.
This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.
Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.
Since your header and footer aren't meant to flex, they should both have flex: none;
set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto
, so they start at their auto height and can shrink but not grow, but they're also overflow:visible
by default, which triggers their default min-height:auto
to prevent them from shrinking at all. If you ever set an overflow
on them, the behavior of min-height:auto
changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article>
element.)
You can simplify the <article>
flex
too - just set flex: 1;
and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.
This solution preserves the index of the df2
DataFrame, unlike any solution that uses tolist()
:
df3 = df2.teams.apply(pd.Series)
df3.columns = ['team1', 'team2']
Here's the result:
team1 team2
0 SF NYG
1 SF NYG
2 SF NYG
3 SF NYG
4 SF NYG
5 SF NYG
6 SF NYG
With C#6.0 you also have a new way of formatting date when using string interpolation e.g.
$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.
This code illustrates what happytime harry and I are trying to say. When the mouse enters, a tooltip comes out, when the mouse leaves it sets a delay for it to disappear. If the mouse enters the same element before the delay is triggered, then we destroy the trigger before it goes off using the data we stored before.
$("someelement").mouseenter(function(){
clearTimeout($(this).data('timeoutId'));
$(this).find(".tooltip").fadeIn("slow");
}).mouseleave(function(){
var someElement = $(this),
timeoutId = setTimeout(function(){
someElement.find(".tooltip").fadeOut("slow");
}, 650);
//set the timeoutId, allowing us to clear this trigger if the mouse comes back over
someElement.data('timeoutId', timeoutId);
});
PHP provides a function just for that: array_rand()
http://php.net/manual/en/function.array-rand.php
$ran = array(1,2,3,4);
$randomElement = $ran[array_rand($ran, 1)];
From the documentation, "the right way is to define a separate server for example.org":
server {
listen 80;
server_name example.com;
return 301 http://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
...
}
For those who want a solution including https://
...
server {
listen 80;
server_name www.domain.com;
# $scheme will get the http protocol
# and 301 is best practice for tablet, phone, desktop and seo
return 301 $scheme://domain.com$request_uri;
}
server {
listen 80;
server_name domain.com;
# here goes the rest of your config file
# example
location / {
rewrite ^/cp/login?$ /cp/login.php last;
# etc etc...
}
}
Note: I have not originally included https://
in my solution since we use loadbalancers and our https:// server is a high-traffic SSL payment server: we do not mix https:// and http://.
To check the nginx version, use nginx -v
.
Strip www from url with nginx redirect
server {
server_name www.domain.com;
rewrite ^(.*) http://domain.com$1 permanent;
}
server {
server_name domain.com;
#The rest of your configuration goes here#
}
So you need to have TWO server codes.
Add the www to the url with nginx redirect
If what you need is the opposite, to redirect from domain.com to www.domain.com, you can use this:
server {
server_name domain.com;
rewrite ^(.*) http://www.domain.com$1 permanent;
}
server {
server_name www.domain.com;
#The rest of your configuration goes here#
}
As you can imagine, this is just the opposite and works the same way the first example. This way, you don't get SEO marks down, as it is complete perm redirect and move. The no WWW is forced and the directory shown!
server {
server_name www.google.com;
rewrite ^(.*) http://google.com$1 permanent;
}
server {
listen 80;
server_name google.com;
index index.php index.html;
####
# now pull the site from one directory #
root /var/www/www.google.com/web;
# done #
location = /favicon.ico {
log_not_found off;
access_log off;
}
}
Try this one. It centers vertically and horizontally.
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: children,
),
)
I'm adding a response for those that use the httpclient-4.5, and probably works for 4.4 as well.
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.fluent.ContentResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
public class HttpClientUtils{
public static HttpClient getHttpClientWithoutSslValidation_UsingHttpClient_4_5_2() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new NoopHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
I am using React-Native 0.40 and below code works for me both on IOS and Android.
(Android-only) Sets the elevation of a view, using Android's underlying elevation API. This adds a drop shadow to the item and affects z-order for overlapping views. Only supported on Android 5.0+, has no effect on earlier versions.
class MainApp extends Component {
render() {
return (
<View style={styles.container}>
<View elevation={5} style={styles.buttonContainer}>
<Text style={styles.textStyle}>Shadow Applied</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF'
},
textStyle: {
color: '#FFFFFF'
},
buttonContainer: {
backgroundColor: '#2E9298',
borderRadius: 10,
padding: 10,
shadowColor: '#000000',
shadowOffset: {
width: 0,
height: 3
},
shadowRadius: 5,
shadowOpacity: 1.0
}
})
Tested on iPhone.
Edit
Comment from @ James. Thanks.
Note: For those on android, the backgroundColor is critical. I was using View as a container for another element and couldn't get a shadow until I specified a background color.
On Windows, I got this error when running under a non-administrator command prompt. When I ran this as administrator, the error went away.
Another approach if you are using Directory.EnumerateFiles
and want to read files in latest modified by first.
foreach (string file in Directory.EnumerateFiles(fileDirectory, fileType).OrderByDescending(f => new FileInfo(f).LastWriteTime))
}
System.out.println("First Name: " + firstname);
System.out.println("Last Name: " + lastname);
or
System.out.println(String.format("First Name: %s", firstname));
System.out.println(String.format("Last Name: %s", lastname));
var init = function() {
console.log("logges only once");
init = false;
};
if(init) { init(); }
/* next time executing init() will cause error because now init is
-equal to false, thus typing init will return false; */
To build on JJC's helpful answer that builds on Louis's helpful answer...
With PhantomJS 2.1.1-windows this line works:
driver.execute_script("return navigator.userAgent")
If it doesn't work, you can still get the user agent via the log (to build on Mma's answer):
from selenium import webdriver
import json
from fake_useragent import UserAgent
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (UserAgent().random)
driver = webdriver.PhantomJS(executable_path=r"your_path", desired_capabilities=dcap)
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('user agent: ', har['log']['entries'][0]['request']['headers'][1]['value'])
This works for me to reduce select tag's width;
<select id ="Select1" class="input-small">
You can use any one of these classes;
class="input-small"
class="input-medium"
class="input-large"
class="input-xlarge"
class="input-xxlarge"
@AlexCuse I wanted to add this as comment to your answer but gave up after making multiple failed attempt to add newlines in comments.
That said, t1ID is unique in table_1 but that doesn't makes it unique in INFO table as well.
For example:
Table_1 has:
Id Field
1 A
2 B
Table_2 has:
Id Field
1 X
2 Y
INFO then can have:
t1ID t2ID field
1 1 some
1 2 data
2 1 in-each
2 2 row
So in INFO table to uniquely identify a row you need both t1ID and t2ID
In short, no. You cannot autowire or manually wire static fields in Spring. You'll have to write your own logic to do this.
Override the handleIntent
Method of the FirebaseMessageService
works for me.
here the code in C# (Xamarin)
public override void HandleIntent(Intent intent)
{
try
{
if (intent.Extras != null)
{
var builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
foreach (string key in intent.Extras.KeySet())
{
builder.AddData(key, intent.Extras.Get(key).ToString());
}
this.OnMessageReceived(builder.Build());
}
else
{
base.HandleIntent(intent);
}
}
catch (Exception)
{
base.HandleIntent(intent);
}
}
and thats the Code in Java
public void handleIntent(Intent intent)
{
try
{
if (intent.getExtras() != null)
{
RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
for (String key : intent.getExtras().keySet())
{
builder.addData(key, intent.getExtras().get(key).toString());
}
onMessageReceived(builder.build());
}
else
{
super.handleIntent(intent);
}
}
catch (Exception e)
{
super.handleIntent(intent);
}
}
is there some other clause in the language specification that this exploits?
Yes, see 12.8 §34 and §35:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...] This elision of copy/move operations, called copy elision, is permitted [...] in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type [...]
When the criteria for elision of a copy operation are met and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.
Just wanted to add one more point that returning by value should be the default choice here because a named value in the return statement in the worst case, i.e. without elisions in C++11, C++14 and C++17 is treated as an rvalue. So for example the following function compiles with the -fno-elide-constructors
flag
std::unique_ptr<int> get_unique() {
auto ptr = std::unique_ptr<int>{new int{2}}; // <- 1
return ptr; // <- 2, moved into the to be returned unique_ptr
}
...
auto int_uptr = get_unique(); // <- 3
With the flag set on compilation there are two moves (1 and 2) happening in this function and then one move later on (3).
A bind implementation might look something like so:
Function.prototype.bind = function () {
const self = this;
const args = [...arguments];
const context = args.shift();
return function () {
return self.apply(context, args.concat([...arguments]));
};
};
The bind function can take any number of arguments and return a new function.
The new function will call the original function using the JS Function.prototype.apply
method.
The apply
method will use the first argument passed to the target function as its context (this
), and the second array argument of the apply
method will be a combination of the rest of the arguments from the target function, concat with the arguments used to call the return function (in that order).
An example can look something like so:
function Fruit(emoji) {_x000D_
this.emoji = emoji;_x000D_
}_x000D_
_x000D_
Fruit.prototype.show = function () {_x000D_
console.log(this.emoji);_x000D_
};_x000D_
_x000D_
const apple = new Fruit('');_x000D_
const orange = new Fruit('');_x000D_
_x000D_
apple.show(); // _x000D_
orange.show(); // _x000D_
_x000D_
const fruit1 = apple.show;_x000D_
const fruit2 = apple.show.bind();_x000D_
const fruit3 = apple.show.bind(apple);_x000D_
const fruit4 = apple.show.bind(orange);_x000D_
_x000D_
fruit1(); // undefined_x000D_
fruit2(); // undefined_x000D_
fruit3(); // _x000D_
fruit4(); //
_x000D_
.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.
That delay you're talking about is actually a filter to prevent false (unwanted) orientation change notifications.
For instant recognition of device orientation change you're just gonna have to monitor the accelerometer yourself.
Accelerometer measures acceleration (gravity included) in all 3 axes so you shouldn't have any problems in figuring out the actual orientation.
Some code to start working with accelerometer can be found here:
How to make an iPhone App – Part 5: The Accelerometer
And this nice blog covers the math part:
In MySQL, <>
means Not Equal To, just like !=
.
mysql> SELECT '.01' <> '0.01';
-> 1
mysql> SELECT .01 <> '0.01';
-> 0
mysql> SELECT 'zapp' <> 'zappp';
-> 1
see the docs for more info
Another simple approach:
package org.yourpackagename;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(PreferenceController.class);
}
public static void main(String[] args) {
SpringApplication.run(PreferenceController.class, args);
}
}
This worked for me, since none of the other solutions worked for me. NOT EVEN FORCE!
Just had to go through Git Bash
cd REPOSITORY-NAME
git add .
git commit -m "Resolved merge conflict by incorporating both suggestions."
Then back to my cmd and I could: git push heroku master
which in my case was the problem.
For any versions of SQL Server: dateadd(dd, datediff(dd, 0, getdate()), 0)
It's one of those annoying functions that you might not want to re-implement:
from annoying.functions import get_object_or_None
#...
user = get_object_or_None(Content, name="baby")
"2020 Update? Url::forceScheme was acting funky for me, but this worked liked a dime."
https
code snippet.
resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');
app/providers/RouteServiceProvider.php
. /**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');
parent::boot();
}
php artisan route:clear && composer dumpautoload
to clear Laravel's cached routes and cached Service Providers.UIButton responds to addTarget:action:forControlEvents: since it inherits from UIControl. But it does not respond to addTarget:action:withObject:forControlEvents:
see reference for the method and for UIButton
You could extend UIButton with a category to implement that method, thought.
As @kojiro said, you don't want to "run" this file. Source it as he says. It should get "sourced" at startup. Sourcing just means running every line in the file, including the one you want to get run. If you want to make sure a folder is in a certain path environment variable (as it seems you want from one of your comments on another solution), execute
$ echo $PATH
At the command line. If you want to check that your ~/.bash_profile is being sourced, either at startup as it should be, or when you source it manually, enter the following line into your ~/.bash_profile file:
$ echo "Hello I'm running stuff in the ~/.bash_profile!"
You can just add the DISTINCT(ip)
, but it has to come at the start of the query. Be sure to escape PHP variables that go into the SQL string.
SELECT DISTINCT(ip), name, COUNT(name) nameCnt,
time, price, SUM(price) priceSum
FROM tablename
WHERE time >= $yesterday AND time <$today
GROUP BY ip, name
Firstly, of all I recommend that the pictures are in the same folder as the workbook. You need to enter some codes in the Worksheet_Change procedure of the worksheet. For example, we can enter the following codes to add the image that with the same name as the value of cell in column A to the cell in column D:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim pic As Picture
If Intersect(Target, [A:A]) Is Nothing Then Exit Sub
On Error GoTo son
For Each pic In ActiveSheet.Pictures
If Not Application.Intersect(pic.TopLeftCell, Range(Target.Offset(0, 3).Address)) Is Nothing Then
pic.Delete
End If
Next pic
ActiveSheet.Pictures.Insert(ThisWorkbook.Path & "\" & Target.Value & ".jpg").Select
Selection.Top = Target.Offset(0, 2).Top
Selection.Left = Target.Offset(0, 3).Left
Selection.ShapeRange.LockAspectRatio = msoFalse
Selection.ShapeRange.Height = Target.Offset(0, 2).Height
Selection.ShapeRange.Width = Target.Offset(0, 3).Width
son:
End Sub
With the codes above, the picture is sized according to the cell it is added to.
Details and sample file here : Vba Insert image to cell
It can also be used as below:
from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)
Adding my two cents here since I have not seen an answer that uses the option "Build with parameters" in Jenkins.
Here I am using Jenkins CI browser console for project starwars_api and I was able to build directly with "Build with parameters" with value refs/tags/tag-name
I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn [email protected] ... basic username.
If using the .NET 2.0 (or later) framework you can use the CopyFromScreen()
method detailed here:
http://www.geekpedia.com/tutorial181_Capturing-screenshots-using-Csharp.html
//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);
KeyGenerator
is used to generate keys
You may want to check KeySpec
, SecretKey
and SecretKeyFactory
classes
http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/package-summary.html
The function will not return the local variable, but rather a copy of it. Your compiler might however perform an optimization where no actual copy action is made.
See this question & answer for further details.
The function will move the value. See this answer for further details.
Try executing 'mysql' or 'mysql -- version' without quotes on terminal. it will prompt version otherwise Command Not Found
Old style string formatting:
In [3]: "%02x" % 127
Out[3]: '7f'
New style
In [7]: '{:x}'.format(127)
Out[7]: '7f'
Using capital letters as format characters yields uppercase hexadecimal
In [8]: '{:X}'.format(127)
Out[8]: '7F'
Docs are here.
You are calling:
JSON.parse(scatterSeries)
But when you defined scatterSeries
, you said:
var scatterSeries = [];
When you try to parse it as JSON it is converted to a string (""
), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.
scatterSeries
is not JSON. Do not try to parse it as JSON.
data
is not JSON either (getJSON
will parse it as JSON automatically).
ch
is JSON … but shouldn't be. You should just create a plain object in the first place:
var ch = {
"name": "graphe1",
"items": data.results[1]
};
scatterSeries.push(ch);
In short, for what you are doing, you shouldn't have JSON.parse
anywhere in your code. The only place it should be is in the jQuery library itself.
The syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression $(command)
is a modern synonym for `command`
which stands for command substitution; it means run command
and put its output here. So
echo "Today is $(date). A fine day."
will run the date
command and include its output in the argument to echo
. The parentheses are unrelated to the syntax for running a command in a subshell, although they have something in common (the command substitution also runs in a separate subshell).
By contrast, ${variable}
is just a disambiguation mechanism, so you can say ${var}text
when you mean the contents of the variable var
, followed by text
(as opposed to $vartext
which means the contents of the variable vartext
).
The while
loop expects a single argument which should evaluate to true or false (or actually multiple, where the last one's truth value is examined -- thanks Jonathan Leffler for pointing this out); when it's false, the loop is no longer executed. The for
loop iterates over a list of items and binds each to a loop variable in turn; the syntax you refer to is one (rather generalized) way to express a loop over a range of arithmetic values.
A for
loop like that can be rephrased as a while
loop. The expression
for ((init; check; step)); do
body
done
is equivalent to
init
while check; do
body
step
done
It makes sense to keep all the loop control in one place for legibility; but as you can see when it's expressed like this, the for
loop does quite a bit more than the while
loop.
Of course, this syntax is Bash-specific; classic Bourne shell only has
for variable in token1 token2 ...; do
(Somewhat more elegantly, you could avoid the echo
in the first example as long as you are sure that your argument string doesn't contain any %
format codes:
date +'Today is %c. A fine day.'
Avoiding a process where you can is an important consideration, even though it doesn't make a lot of difference in this isolated example.)
const handleClick = async (item: NavheadersType, index: number) => {
const newNavHeaders = [...navheaders];
if (item.url) {
await router.push(item.url); =>>>> line causing error (causing route to happen)
// router.push(item.url); =>>> coreect line
newNavHeaders.forEach((item) => (item.active = false));
newNavHeaders[index].active = true;
setnavheaders([...newNavHeaders]);
}
};
While the answers above are more or less correct, you may run into trouble if the size of your array isn't divisible by 2, as the result of a / 2
, a being odd, is a float in python 3.0, and in earlier version if you specify from __future__ import division
at the beginning of your script. You are in any case better off going for integer division, i.e. a // 2
, in order to get "forward" compatibility of your code.
Change string[] lines = File.ReadLines("c:\\file.txt");
to IEnumerable<string> lines = File.ReadLines("c:\\file.txt");
The rest of your code should work fine.
You can use a FileReader
object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Here is the codepen demo
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
</script>
BigDecimal no = new BigDecimal(10); //you can add like this also
no = no.add(new BigDecimal(10));
System.out.println(no);
20
See the Integer class and the static parseInt()
method:
http://developer.android.com/reference/java/lang/Integer.html
Integer.parseInt(et.getText().toString());
You will need to catch NumberFormatException
though in case of problems whilst parsing, so:
int myNum = 0;
try {
myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder
It is actually a 3 step process to connect to a PostgreSQL server remotely through pgAdmin3.
Note: I use Ubuntu 11.04 and PostgreSQL 8.4.
You have to make PostgreSQL listening for remote incoming TCP connections because the default settings allow to listen only for connections on the loopback interface. To be able to reach the server remotely you have to add the following line into the file /etc/postgresql/8.4/main/postgresql.conf:
listen_addresses = '*'
PostgreSQL by default refuses all connections it receives from any remote address, you have to relax these rules by adding this line to /etc/postgresql/8.4/main/pg_hba.conf:
host all all 0.0.0.0/0 md5
This is an access control rule that let anybody login in from any address if he can provide a valid password (the md5 keyword). You can use needed network/mask instead of 0.0.0.0/0 .
When you have applied these modifications to your configuration files you need to restart PostgreSQL server. Now it is possible to login to your server remotely, using the username and password.
Try out cat
and sprintf
in your for loop.
eg.
cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))
See here
<parent>
<groupId>com.test.vaquar.khan</groupId>
<artifactId>vk-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../projectname/pom.xml</relativePath>
</parent>
Add following line in parent
<relativePath>../projectname/pom.xml</relativePath>
You need relative path if you are building from local parent pom not available in nexsus, add pom in nexus then no need this path
Do you want to select all rows or all columns?
Either way, you don't actually need to do anything.
The DataContext has a property for each table; you can simply use that property to access the entire table.
For example:
foreach(var line in context.Orders) {
//Do something
}
I agree with Chris, checking the extension is not validation of the type of file any way you look at it. Telerik's radUpload is probably your best option, it provides a ContentType property of the file being uploaded, which you can compare to known mime types. You should check for:
application/vnd.ms-excel,
application/excel,
application/x-msexcel
and for the new 2k7 format:
application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet
Telerik used to sell radUpload as an individual component, but now its wrapped into the controls suite, which makes it a little more expensive, but by far its the easiest way to check for the true type
I recommend using this HttpURLConnection
instead HttpGet
. As HttpGet
is already deprecated in Android API level 22.
HttpURLConnection httpcon;
String url = null;
String data = null;
String result = null;
try {
//Connect
httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
//Write
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.close();
os.close();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
which means that cacerts keystore isn't password protected
That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:
In order to verify its integrity, you must provide your keystore password.
Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.
I was successful using tidy
command line utility. On linux I installed it quickly with apt-get install tidy
. Then the command:
tidy -q -asxml --numeric-entities yes source.html >file.xml
gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.
This is their homepage: html-tidy.org (and the legacy one: HTML Tidy)
After using the wrong quotation mark characters in install.packages()
, correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.
You can find the log within you Magento root directory under
var/log
there are two types of log files system.log and exception.log
you need to give the correct permission to var folder, then enable logging from your Magento admin by going to
System > Configuration> Developer > Log Settings > Enable = Yes
system.log is used for general debugging and catches almost all log entries from Magento, including warning, debug and errors messages from both native and custom modules.
exception.log is reserved for exceptions only, for example when you are using try-catch statement.
To output to either the default system.log or the exception.log see the following code examples:
Mage::log('My log entry');
Mage::log('My log message: '.$myVariable);
Mage::log($myArray);
Mage::log($myObject);
Mage::logException($e);
You can create your own log file for more debugging
Mage::log('My log entry', null, 'mylogfile.log');
If using Maven you can context click and run 'Maven/Update Project...'
Use cut:
echo 'someletters_12345_moreleters.ext' | cut -d'_' -f 2
More generic:
INPUT='someletters_12345_moreleters.ext'
SUBSTRING=$(echo $INPUT| cut -d'_' -f 2)
echo $SUBSTRING
static final int safeAdd(int left, int right)
throws ArithmeticException {
if (right > 0 ? left > Integer.MAX_VALUE - right
: left < Integer.MIN_VALUE - right) {
throw new ArithmeticException("Integer overflow");
}
return left + right;
}
static final int safeSubtract(int left, int right)
throws ArithmeticException {
if (right > 0 ? left < Integer.MIN_VALUE + right
: left > Integer.MAX_VALUE + right) {
throw new ArithmeticException("Integer overflow");
}
return left - right;
}
static final int safeMultiply(int left, int right)
throws ArithmeticException {
if (right > 0 ? left > Integer.MAX_VALUE/right
|| left < Integer.MIN_VALUE/right
: (right < -1 ? left > Integer.MIN_VALUE/right
|| left < Integer.MAX_VALUE/right
: right == -1
&& left == Integer.MIN_VALUE) ) {
throw new ArithmeticException("Integer overflow");
}
return left * right;
}
static final int safeDivide(int left, int right)
throws ArithmeticException {
if ((left == Integer.MIN_VALUE) && (right == -1)) {
throw new ArithmeticException("Integer overflow");
}
return left / right;
}
static final int safeNegate(int a) throws ArithmeticException {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return -a;
}
static final int safeAbs(int a) throws ArithmeticException {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return Math.abs(a);
}
Everything in the java.lang
package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util
package, which is not implicitly imported.
The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.
DECLARE @records varchar(400)
SELECT @records = 'a,b,c,d'
select LEN(@records) as 'Before removing Commas' , LEN(@records) - LEN(REPLACE(@records, ',', '')) 'After Removing Commans'
The Real Solution:
add <!DOCTYPE something>
to the begining of each problematic XML,
after the xml tag <?xml version="1.0" encoding="utf-8"?>
you can write anything for doctype, but basically it's supposed to be manifest, activity, etc. from what I understand
You can try
SELECT ROUND((SYSDATE - TO_DATE('12-MAY-16'))/365.25, 5) AS AGE from DUAL;
You can configure ROUND
to show as many decimal places as you wish.
Placing the date in decimal format like aforementioned helps with calculations of age groups, etc.
This is just a contrived example. In real world scenarios, you wouldn't be converting strings to date using TO_DATE
.
However, if you have date of birth in date format, you can subtract two dates safely.
Your code is drawing the center of the baseline of the text, at the center of the view. In order to center the text at some point, x, y, you need to calculate the center of the text, and put that at the point.
This method will draw text centered at the point x, y. If you pass it the center of your view, it will draw the text centered.
private void drawTextCentered(String text, int x, int y, Paint paint, Canvas canvas) {
int xPos = x - (int)(paint.measureText(text)/2);
int yPos = (int) (y - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
canvas.drawText(text, xPos, yPos, textPaint);
}
You can't stretch a background image (until CSS 3).
You would have to use absolute positioning, so that you can put an image tag inside the cell and stretch it to cover the entire cell, then put the content on top of the image.
table {_x000D_
width: 230px;_x000D_
}_x000D_
_x000D_
.style1 {_x000D_
text-align: center;_x000D_
height: 35px;_x000D_
}_x000D_
_x000D_
.bg {_x000D_
position: relative;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.bg img {_x000D_
display: block;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.bg .linkcontainer {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
overflow: hidden;_x000D_
width: 100%;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="10">_x000D_
<tr>_x000D_
<td class="style1">_x000D_
<div class="bg">_x000D_
<img src="http://placekitten.com/20/20" alt="" />_x000D_
<div class="linkcontainer">_x000D_
<a class="link" href="#">_x000D_
<span>Answer</span>_x000D_
</a>_x000D_
</div>_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
I tried lashrah's answer and it worked after changing syntax a little bit. this is what worked for me:
@(
((HomeController)this.ViewContext.Controller).Method1();
)
Here is your solution for the problem,
$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
if(ord($i) % 2 != 0)
$letter[] .= $i;
}
print_r($letter);
You need to get the ASCII value for that character which will solve your problem.
Here is ord doc and working code.
For your requirement, you can do like this,
for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
$letter[] .= $i;
}
print_r($letter);
Here set $x as per your requirement.
You must remove the data from the TableModel
used for the table.
If using the DefaultTableModel
, just set the row count to zero. This will delete the rows and fire the TableModelEvent
to update the GUI.
JTable table; … DefaultTableModel model = (DefaultTableModel) table.getModel(); model.setRowCount(0);
If you are using other TableModel
, please check the documentation.
Use the two argument for of Collections.sort
. You will want a suitable Comparator
that treats case appropriate (i.e. does lexical, not UTF16 ordering), such as that obtainable through java.text.Collator.getInstance
.
LocalDateTime#plusHours
LocalDateTime
is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation.
Use LocalDateTime#plusHours
to get a copy of this LocalDateTime
with the specified number of hours added.
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the timezone of your JVM. It is also the
// default timezone for date-time type i.e.
// LocalDateTime.now(ZoneId.systemDefault()) is same as LocalDateTime.now().
// Change the timezone as per your requirement e.g. ZoneId.of("Europe/London")
LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
System.out.println(ldt);
LocalDateTime after8Hours = ldt.plusHours(8);
System.out.println(after8Hours);
// Custom format
DateTimeFormatter dtfTimeFormat24H = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss", Locale.ENGLISH);
DateTimeFormatter dtfTimeFormat12h = DateTimeFormatter.ofPattern("dd/MM/uuuu hh:mm:ss a", Locale.ENGLISH);
System.out.println(dtfTimeFormat24H.format(after8Hours));
System.out.println(dtfTimeFormat12h.format(after8Hours));
}
}
Output:
2021-01-07T15:24:52.736612
2021-01-07T23:24:52.736612
07/01/2021 23:24:52
07/01/2021 11:24:52 PM
Learn more about the modern date-time API from Trail: Date Time.
Using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date currentDateTime = calendar.getTime();
System.out.println(currentDateTime);
// After 8 hours
calendar.add(Calendar.HOUR_OF_DAY, 8);
Date after8Hours = calendar.getTime();
System.out.println(after8Hours);
// Custom formats
SimpleDateFormat sdf24H = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
// Change the timezone as per your requirement e.g.
// TimeZone.getTimeZone("Europe/London")
sdf24H.setTimeZone(TimeZone.getDefault());
SimpleDateFormat sdf12h = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.ENGLISH);
sdf12h.setTimeZone(TimeZone.getDefault());
System.out.println(sdf24H.format(after8Hours));
System.out.println(sdf12h.format(after8Hours));
}
}
Output:
Thu Jan 07 15:34:10 GMT 2021
Thu Jan 07 23:34:10 GMT 2021
07/01/2021 23:34:10
07/01/2021 11:34:10 PM
String
with the pattern of your choice using date-time formatting API.
java.time.format
e.g. java.time.format.DateTimeFormatter
, java.time.format.DateTimeFormatterBuilder
etc.java.text
e.g. java.text.SimpleDateFormat
, java.text.DateFormat
etc.java.util.Date
object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970
. When you print an object of java.util.Date
, its toString
method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat
and obtain the formatted string from it.java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
<video src="videofile.webm" poster="posterimage.jpg" controls preload="metadata">
Sorry, your browser doesn't support embedded videos.
</video>
Cover
video{
object-fit: cover; /*to cover all the box*/
}
Fill
video{
object-fit: fill; /*to add black content at top and bottom*/
object-position: 0 -14px; /* to center our image*/
}
Note that the video controls are over our image, so our image is not completly showed. If you are using object-fit cover, edit your image on a visual app as photoshop and add a margin bottom content.
For Windows OS
For Uppercase CTRL + K + U
For Lowercase CTRL + K + L
While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this
mkdir -p {main,test}/{resources,scala/com/company}
It will create following directory structure under the directory from where it is invoked
+-- main
¦ +-- resources
¦ +-- scala
¦ +-- com
¦ +-- company
+-- test
+-- resources
+-- scala
+-- com
+-- company
The example was taken from this link for creating SBT directory structure
$about = DB::where('page', 'about-me')->first();
in stead of get()
.
It works on my project. Thanks.
It stands indeed for whatever, as in whatever works for you
MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.
For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.
Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.
Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".
Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.
For setting Top Border and Bottom Border for a UIView in Swift.
let topBorder = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 1))
topBorder.backgroundColor = UIColor.black
myView.addSubview(topBorder)
let bottomBorder = UIView(frame: CGRect(x: 0, y: myView.frame.size.height - 1, width: 10, height: 1))
bottomBorder.backgroundColor = UIColor.black
myView.addSubview(bottomBorder)
Hide the file input. Create a new input to capture a click event and forward it to the hidden input:
<input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('file').click();" />
<input type="file" style="display:none;" id="file" name="file"/>
As of Visual Studio 2019, the modern .csproj
format supports adding a condition directly on the Target
element:
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Debug'">
<Exec Command="nswag run nswag.json" />
</Target>
The UI doesn't provide a way to set this up, but it does appear to safely leave the Configuration
attribute in place if you make changes via the UI.
The script package does exactly what you're looking for: https://atom.io/packages/script
The package's documentation also contains the key mappings, which you can easily customize.
I was facing the same issue. After many tries below solution worked for me.
Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.
After that you can follow the below steps.
@ABHI KUMAR
Download the Visual C++ Redistributable 2015
Visual C++ Redistributable for Visual Studio 2015 (64-bit)
Visual C++ Redistributable for Visual Studio 2015 (32-bit)
(Reinstal if already installed) then restart your computer or use windows updates for download auto.
For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.
raise
without any arguments is a special use of python syntax. It means get the exception and re-raise it. If this usage it could have been called reraise
.
raise
From The Python Language Reference:
If no expressions are present, raise re-raises the last exception that was active in the current scope.
If raise
is used alone without any argument is strictly used for reraise-ing. If done in the situation that is not at a reraise of another exception, the following error is shown:
RuntimeError: No active exception to reraise
There doesn't seem to be justify-self
, but you can achieve similar result setting appropriate margin
to auto
¹. E. g. for flex-direction: row
(default) you should set margin-right: auto
to align the child to the left.
.container {_x000D_
height: 100px;_x000D_
border: solid 10px skyblue;_x000D_
_x000D_
display: flex;_x000D_
justify-content: flex-end;_x000D_
}_x000D_
.block {_x000D_
width: 50px;_x000D_
background: tomato;_x000D_
}_x000D_
.justify-start {_x000D_
margin-right: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="block justify-start"></div>_x000D_
<div class="block"></div>_x000D_
</div>
_x000D_
¹ This behaviour is defined by the Flexbox spec.
I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:
inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
int curRow = r * sectors;
int nextRow = (r+1) * sectors;
indices.push_back(curRow + s);
indices.push_back(nextRow + s);
indices.push_back(nextRow + (s+1));
indices.push_back(curRow + s);
indices.push_back(nextRow + (s+1));
indices.push_back(curRow + (s+1));
}
void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
float radius, unsigned int rings, unsigned int sectors)
{
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
for(int r = 0; r < rings; ++r) {
for(int s = 0; s < sectors; ++s) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
texcoords.push_back(vec2(s*S, r*R));
vertices.push_back(vec3(x,y,z) * radius);
push_indices(indices, sectors, r, s);
}
}
}
How was your 2D array declared?
If it something like:
int arr[20][30];
You can zero it by doing:
memset(arr, sizeof(int)*20*30);
I know this may be obvious for most people who use RegEx frequently, but in case any readers are new to RegEx, I thought I should point out an observation I made that was helpful for one of my projects.
In a previous answer from @kennytm:
^\d{5}(?:[-\s]\d{4})?$
…? = The pattern before it is optional (for condition 1)
If you want to allow both standard 5 digit and +4 zip codes, this is a great example.
To match only zip codes in the US 'Zip + 4' format as I needed to do (conditions 2 and 3 only), simply remove the last ?
so it will always match the last 5 character group.
A useful tool I recommend for tinkering with RegEx is linked below:
I use this tool frequently when I find RegEx that does something similar to what I need, but could be tailored a bit better. It also has a nifty RegEx reference menu and informative interface that keeps you aware of how your changes impact the matches for the sample text you entered.
If I got anything wrong or missed an important piece of information, please correct me.
Additional to tomaskazemekas's answer: you should install spyder in that virtual environment by:
conda install -n myenv spyder
(on Windows, for Linux or MacOS, you can search for similar commands)
If that's what I understood, it's like this:
C:\Users\(username)\AppData\Local\Programs\Python\Python(version)
COPY (not delete) python.exe and rename to py.exe and execute:
py filename.py
Just running the SELECT
statement will have no effect on the data. You have to use an UPDATE
statement with the REPLACE
to make the change occur:
UPDATE photos
SET caption = REPLACE(caption,'"','\'')
Here is a working sample: http://sqlize.com/7FjtEyeLAh
the simpleset solution
look at my selector
$myForm.find('#fieldsetUserInfo input:disabled').prop("disabled", false);
the fieldsetUserInfo
is div contains all inputs I want to disabled or Enable
hope this helps you
Don't know if you solved the problem but if anyone has this problem in future.
$python
>>import numpy
>>print(numpy)
Go to the location printed and delete the numpy
installation found there. You can then use pip
or easy_install
This is a verbose translation of what Symfony uses to get the host name (see the second example for a more literal translation):
function getHost() {
$possibleHostSources = array('HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR');
$sourceTransformations = array(
"HTTP_X_FORWARDED_HOST" => function($value) {
$elements = explode(',', $value);
return trim(end($elements));
}
);
$host = '';
foreach ($possibleHostSources as $source)
{
if (!empty($host)) break;
if (empty($_SERVER[$source])) continue;
$host = $_SERVER[$source];
if (array_key_exists($source, $sourceTransformations))
{
$host = $sourceTransformations[$source]($host);
}
}
// Remove port number from host
$host = preg_replace('/:\d+$/', '', $host);
return trim($host);
}
Outdated:
This is my translation to bare PHP of a method used in Symfony framework that tries to get the hostname from every way possible in order of best practice:
function get_host() {
if ($host = $_SERVER['HTTP_X_FORWARDED_HOST'])
{
$elements = explode(',', $host);
$host = trim(end($elements));
}
else
{
if (!$host = $_SERVER['HTTP_HOST'])
{
if (!$host = $_SERVER['SERVER_NAME'])
{
$host = !empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '';
}
}
}
// Remove port number from host
$host = preg_replace('/:\d+$/', '', $host);
return trim($host);
}
From a display perspective .container
gives you more control over the what the users are seeing, and makes it easier to see what the users will see as you only have 4 variations of display (5 in the case of bootstrap 5) because the sizes relate to the same as the grid sizes. e.g. .col-xs
, .col-sm
, .col
, and .col-lg
.
What this means, is that when you are doing user testing if you test on a displays with the 4 different sizes you see all the veriations in display.
When using .container-fluid
because the witdh is related to the viewport width the display is dynamic, so the varations are much greater and users with very large screens or uncommon screen widths may see results you weren't expecting.
I had this issue I tried Jmr's solution however it didn't work for me. As all input fields have ng-model attributes I could pull the the attribute and evaluate it and get the value.
HTML
<input ng-model="qty" type="number">
Protractor
var qty = element( by.model('qty') );
qty.sendKeys('10');
qty.evaluate(qty.getAttribute('ng-model')) //-> 10
This is not accurately addressing the question but since i stumbled across this and the above solutions didn't work for me or had requirements i couldn't meet, here is another way to add the BOM when you have access to vim:
vim -e -s +"set bomb|set encoding=utf-8|wq" filename.csv
Based on Haim's answer I created a PHP code to test and display all the differences between two databases. This will also display if a table is present in source or test databases. You have to change with your details the <> variables content.
<?php
$User = "<DatabaseUser>";
$Pass = "<DatabasePassword>";
$SourceDB = "<SourceDatabase>";
$TestDB = "<DatabaseToTest>";
$link = new mysqli( "p:". "localhost", $User, $Pass, "" );
if ( mysqli_connect_error() ) {
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
mysqli_set_charset( $link, "utf8" );
mb_language( "uni" );
mb_internal_encoding( "UTF-8" );
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $SourceDB .'";';
$SourceDB_Content = query( $link, $sQuery );
if ( !is_array( $SourceDB_Content) ) {
echo "Table $SourceDB cannot be accessed";
exit(0);
}
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $TestDB .'";';
$TestDB_Content = query( $link, $sQuery );
if ( !is_array( $TestDB_Content) ) {
echo "Table $TestDB cannot be accessed";
exit(0);
}
$SourceDB_Tables = array();
foreach( $SourceDB_Content as $item ) {
$SourceDB_Tables[] = $item["TABLE_NAME"];
}
$TestDB_Tables = array();
foreach( $TestDB_Content as $item ) {
$TestDB_Tables[] = $item["TABLE_NAME"];
}
//var_dump( $SourceDB_Tables, $TestDB_Tables );
$LookupTables = array_merge( $SourceDB_Tables, $TestDB_Tables );
$NoOfDiscrepancies = 0;
echo "
<table border='1' width='100%'>
<tr>
<td>Table</td>
<td>Found in $SourceDB (". count( $SourceDB_Tables ) .")</td>
<td>Found in $TestDB (". count( $TestDB_Tables ) .")</td>
<td>Test result</td>
<tr>
";
foreach( $LookupTables as $table ) {
$FoundInSourceDB = in_array( $table, $SourceDB_Tables ) ? 1 : 0;
$FoundInTestDB = in_array( $table, $TestDB_Tables ) ? 1 : 0;
echo "
<tr>
<td>$table</td>
<td><input type='checkbox' ". ($FoundInSourceDB == 1 ? "checked" : "") ."></td>
<td><input type='checkbox' ". ($FoundInTestDB == 1 ? "checked" : "") ."></td>
<td>". compareTables( $SourceDB, $TestDB, $table ) ."</td>
</tr>
";
}
echo "
</table>
<br><br>
No of discrepancies found: $NoOfDiscrepancies
";
function query( $link, $q ) {
$result = mysqli_query( $link, $q );
$errors = mysqli_error($link);
if ( $errors > "" ) {
echo $errors;
exit(0);
}
if( $result == false ) return false;
else if ( $result === true ) return true;
else {
$rset = array();
while ( $row = mysqli_fetch_assoc( $result ) ) {
$rset[] = $row;
}
return $rset;
}
}
function compareTables( $source, $test, $table ) {
global $link;
global $NoOfDiscrepancies;
$sQuery = "
SELECT column_name,ordinal_position,data_type,column_type FROM
(
SELECT
column_name,ordinal_position,
data_type,column_type,COUNT(1) rowcount
FROM information_schema.columns
WHERE
(
(table_schema='$source' AND table_name='$table') OR
(table_schema='$test' AND table_name='$table')
)
AND table_name IN ('$table')
GROUP BY
column_name,ordinal_position,
data_type,column_type
HAVING COUNT(1)=1
) A;
";
$result = query( $link, $sQuery );
$data = "";
if( is_array( $result ) && count( $result ) > 0 ) {
$NoOfDiscrepancies++;
$data = "<table><tr><td>column_name</td><td>ordinal_position</td><td>data_type</td><td>column_type</td></tr>";
foreach( $result as $item ) {
$data .= "<tr><td>". $item["column_name"] ."</td><td>". $item["ordinal_position"] ."</td><td>". $item["data_type"] ."</td><td>". $item["column_type"] ."</td></tr>";
}
$data .= "</table>";
return $data;
}
else {
return "Checked but no discrepancies found!";
}
}
?>
As of Node.js 14.3.0 the top-level await is supported.
Required flag: --experimental-top-level-await
.
Further details: https://v8.dev/features/top-level-await
You could use Synonyms part in the database.
Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply.
Cameron MacFarland nailed it.
I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.
Add it to the instance of the Click delegate:
ChildNode.Click += SubGraphButton_Click
which is inkeeping with the pattern .NET events follow (Observer).
Eclipse is erroring because if you try and create a project on a directory that exists, Eclipse doesn't know if it's an actual project or not - so it errors, saving you from losing work!
So you have two solutions:
Move the folder counter_src
somewhere else, then create the project (which will create the directory), then import the source files back into the newly created counter_src
.
Right-click on the project explorer and import an existing project, select C:\Users\Martin\Java\Counter\
as your root directory. If Eclipse sees a project, you will be able to import it.
As perhaps one of the older people here, and born late in the month, I find drop-down menus for birthdates to be frustrating. I typically have to scroll down on two drop-down menus, and that's awkward. I'd much rather type it in.
If you can have a control designed so that it can either accept drop-down menus or be typed into, and make it clear both work, that would be excellent.
Best way to copy all files from one folder to another using PHP
<?php
$src = "/home/www/example.com/source/folders/123456"; // source folder or file
$dest = "/home/www/example.com/test/123456"; // destination folder or file
shell_exec("cp -r $src $dest");
echo "<H2>Copy files completed!</H2>"; //output when done
?>
i would go around this by making a 2d dynamic array:
long long** a = new long long*[x];
for (unsigned i = 0; i < x; i++) a[i] = new long long[y];
more on this here https://stackoverflow.com/a/936702/3517001
I was beginning to go mad while searching for the real configuration, so here is the list of all configuration files on linux:
on windows:
Then in this file the prefix is configured:
prefix=/usr
The prefix is defaulted to /usr in linux, to ${APPDATA}\npm in windows
The node modules are under $prefix tree, and the path should contain $prefix/bin
There may be a problem :
/root/.npmrc
may be used!/home/youruser/.npmrc
.npm set -g prefix /usr
it sets the /etc/npmrc global, but doesn't override the localHere is all the informations that were missing to find what is configured where. Hope I have been exhaustive.
While it's true that json
is a built-in module, I also found that on an Ubuntu system with python-minimal
installed, you DO have python
but you can't do import json
. And then I understand that you would try to install the module using pip!
If you have python-minimal
you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json
module. The solution is to install an additional package, called libpython2.7-stdlib
, to install all 'default' python libraries.
sudo apt install libpython2.7-stdlib
And then you can do import json
in python and it would work!
Here is a cross platform solution to clearing docker container logs:
docker run --rm -v /var/lib/docker:/var/lib/docker alpine sh -c "echo '' > $(docker inspect --format='{{.LogPath}}' CONTAINER_NAME)"
Paste this into your terminal and change CONTAINER_NAME
to desired container name or id.
I usually do something along these lines:
work.dat1
for instance)work.2011-01-15T112357.dat
for instance)work.2011-01-15T112357.0001.dat
for instance. (I dislike GUIDs. I prefer order/predictability.)Here's a sample class:
static class DirectoryInfoHelpers
{
public static FileStream CreateFileWithUniqueName( this DirectoryInfo dir , string rootName )
{
FileStream fs = dir.TryCreateFile( rootName ) ; // try the simple name first
// if that didn't work, try mixing in the date/time
if ( fs == null )
{
string date = DateTime.Now.ToString( "yyyy-MM-ddTHHmmss" ) ;
string stem = Path.GetFileNameWithoutExtension(rootName) ;
string ext = Path.GetExtension(rootName) ?? ".dat" ;
ext = ext.Substring(1);
string fn = string.Format( "{0}.{1}.{2}" , stem , date , ext ) ;
fs = dir.TryCreateFile( fn ) ;
// if mixing in the date/time didn't work, try a sequential search
if ( fs == null )
{
int seq = 0 ;
do
{
fn = string.Format( "{0}.{1}.{2:0000}.{3}" , stem , date , ++seq , ext ) ;
fs = dir.TryCreateFile( fn ) ;
} while ( fs == null ) ;
}
}
return fs ;
}
private static FileStream TryCreateFile(this DirectoryInfo dir , string fileName )
{
FileStream fs = null ;
try
{
string fqn = Path.Combine( dir.FullName , fileName ) ;
fs = new FileStream( fqn , FileMode.CreateNew , FileAccess.ReadWrite , FileShare.None ) ;
}
catch ( Exception )
{
fs = null ;
}
return fs ;
}
}
You might want to tweak the algorithm (always use all the possible components to the file name for instance). Depends on the context -- If I was creating log files for instance, that I might want to rotate out of existence, you'd want them all to share the same pattern to the name.
The code isn't perfect (no checks on the data passed in for instance). And the algorithm's not perfect (if you fill up the hard drive or encounter permissions, actual I/O errors or other file system errors, for instance, this will hang, as it stands, in an infinite loop).
Seems like this is ought to be the approved answer...
Intl.NumberFormat('en-US').format(count)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
Hackbod's is one of the best answers on Stack Overflow. It throws light on a very obscure subject. It helped me a lot.
Another really helpful resource is this must-see video: Google I/O 2011: Memory management for Android Apps
UPDATE:
Process Stats, a service to discover how your app manages memory explained at the blog post Process Stats: Understanding How Your App Uses RAM by Dianne Hackborn:
Similar to brianegge's awk solution, here is the Perl equivalent:
ps | egrep 11383 | perl -lane 'print $F[3]'
-a
enables autosplit mode, which populates the @F
array with the column data.
Use -F,
if your data is comma-delimited, rather than space-delimited.
Field 3 is printed since Perl starts counting from 0 rather than 1
Oh okay read the question wrong, I guess it's about going backward in an array? if so, I have this:
array = ["ty", "rogers", "smith", "davis", "tony", "jack", "john", "jill", "harry", "tom", "jane", "hilary", "jackson", "andrew", "george", "rachel"]
counter = 0
for loop in range(len(array)):
if loop <= len(array):
counter = -1
reverseEngineering = loop + counter
print(array[reverseEngineering])
So I started experimenting with the different things that FileReader API had to offer and could create an IMG tag with a DATA URL.
Drawback: It doesn't work on mobile phones, but it works fine on Google Chrome.
$('input').change(function() {_x000D_
_x000D_
var fr = new FileReader;_x000D_
_x000D_
fr.onload = function() {_x000D_
var img = new Image;_x000D_
_x000D_
img.onload = function() { _x000D_
//I loaded the image and have complete control over all attributes, like width and src, which is the purpose of filereader._x000D_
$.ajax({url: img.src, async: false, success: function(result){_x000D_
$("#result").html("READING IMAGE, PLEASE WAIT...")_x000D_
$("#result").html("<img src='" + img.src + "' />");_x000D_
console.log("Finished reading Image");_x000D_
}});_x000D_
};_x000D_
_x000D_
img.src = fr.result;_x000D_
};_x000D_
_x000D_
fr.readAsDataURL(this.files[0]);_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" accept="image/*" capture="camera">_x000D_
<div id='result'>Please choose a file to view it. <br/>(Tested successfully on Chrome - 100% SUCCESS RATE)</div>
_x000D_
(see this on a jsfiddle at http://jsfiddle.net/eD2Ez/530/)
(see the original jsfiddle that i added upon to at http://jsfiddle.net/eD2Ez/)
You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy
:
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
Cast the operands to floats:
float ans = (float)a / (float)b;
Did you check NULLIF? http://msdn.microsoft.com/en-us/library/ms177562.aspx
Your code is indeed using the normal way to create and delete a dynamic object. Yes, it's perfectly normal (and indeed guaranteed by the language standard!) that delete
will call the object's destructor, just like new
has to invoke the constructor.
If you weren't instantiating Object1
directly but some subclass thereof, I'd remind you that any class intended to be inherited from must have a virtual destructor (so that the correct subclass's destructor can be invoked in cases analogous to this one) -- but if your sample code is indeed representative of your actual code, this cannot be your current problem -- must be something else, maybe in the destructor code you're not showing us, or some heap-corruption in the code you're not showing within that function or the ones it calls...?
BTW, if you're always going to delete the object just before you exit the function which instantiates it, there's no point in making that object dynamic -- just declare it as a local (storage class auto
, as is the default) variable of said function!
As of PHP 5.6 @$filePath
will not work in CURLOPT_POSTFIELDS
without CURLOPT_SAFE_UPLOAD
being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.
$fields = [
'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);
Instead of use set_userdata you should use set_flashdata.
According to CI user guide:
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: "record 2 deleted").
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
fork, exec, and wait should work, if you're not really looking for a Objective-C specific way. fork
creates a copy of the currently running program, exec
replaces the currently running program with a new one, and wait
waits for the subprocess to exit. For example (without any error checking):
#include <stdlib.h>
#include <unistd.h>
pid_t p = fork();
if (p == 0) {
/* fork returns 0 in the child process. */
execl("/other/program/to/run", "/other/program/to/run", "foo", NULL);
} else {
/* fork returns the child's PID in the parent. */
int status;
wait(&status);
/* The child has exited, and status contains the way it exited. */
}
/* The child has run and exited by the time execution gets to here. */
There's also system, which runs the command as if you typed it from the shell's command line. It's simpler, but you have less control over the situation.
I'm assuming you're working on a Mac application, so the links are to Apple's documentation for these functions, but they're all POSIX
, so you should be to use them on any POSIX-compliant system.
If you are using Sentry
check the logged in user with Sentry::getUser()->id
. The error you get is that the Auth::user()
returns NULL and it tries to get id from NULL hence the error trying to get a property from a non-object
.
you can put the css folder inside the assest folder(you name it any name) in the directory of your project as:
- ci_app
- application
- views
- assets
- css
- style.css
...
when you want to load that file in a page, you can use base_url()function as this way:
<head>
<link rel='stylesheet' href='<?php echo base_url();?>assets/css/style.css'>
</head>
and you are sure to add base_url of your project in the config.php file as this:
$config['base_url'] = 'http://localhost/ci_app';
You can stream download too which will consume significantly less resource. example:
$readableStream = fopen('test.zip', 'rb');
$writableStream = fopen('php://output', 'wb');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="test.zip"');
stream_copy_to_stream($readableStream, $writableStream);
ob_flush();
flush();
In the above example, I am downloading a test.zip (which was actually the android studio zip on my local machine).
php://output is a write-only stream (generally used by echo or print).
after that, you just need to set the required headers and call stream_copy_to_stream(source, destination).
stream_copy_to_stream() method acts as a pipe which takes the input from the source stream (read stream) and pipes it to the destination stream (write stream) and it also avoid the issue of allowed memory exhausted so you can actually download files that are bigger than your PHP memory_limit
.
You can try using simlinks, but in reverse.
React won't follow simlinks, but you can move something to the source directory, and create a simlink to it.
In the root of my project, I had a node server directory that had several schema files in it. I wanted to use them on the frontend, so I:
ln -s SRC_PATH_OF_SCHEMA_FILE
This gave react what it was looking for, and node was perfectly happy including files through simlinks.
try
java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main
If you are on windows, you should use ;
instead of :
signal
isn't the most reliable way as it differs in implementations. I would recommend using sigaction
. Tom's code would now look like this :
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void my_handler(int s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = my_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
pause();
return 0;
}
You mean that want to get status codes?
VolleyError
has a member variable type of NetworkResponse
and it is public.
You can access error.networkResponse.statusCode
for http error code.
I hope it is helpful for you.
Hans Passant was correct, I added a handler for AppDomain.CurrentDomain.UnhandledException as described here http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx I was able to find the exception that was occurring and corrected it.
Somewhere around r59 this gets easier (rotate around x):
bb.GraphicsEngine.prototype.calcRotation = function ( obj, rotationX)
{
var euler = new THREE.Euler( rotationX, 0, 0, 'XYZ' );
obj.position.applyEuler(euler);
}
This is not really an answer to the present question, however it might help others too.
At least I can tell there is a technical limit of 32767 values (=Short.MAX_VALUE) passable to the PostgreSQL backend, using Posgresql's JDBC driver 9.1.
This is a test of "delete from x where id in (... 100k values...)" with the postgresql jdbc driver:
Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 100000
at org.postgresql.core.PGStream.SendInteger2(PGStream.java:201)
The print
statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string:
a = str(tag.getArtist())
During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.
You can make your constructor private
or internal
if you want, just so long as it's parameterless.