In my case the issue didn't resolve by following any of the above methods. I had all the paths in my package config correct and the dll's were in place as referred, I was still getting run time error for System.Web.WebPages.Razor. I changed the localhost port number and this worked
I am not sure of why I had the issue and why changing the port number resolved it. Just posting this as I feel this might be useful for someone out there.
Briefly bitmask helps to manipulate position of multiple values. There is a good example here ;
Bitflags are a method of storing multiple values, which are not mutually exclusive, in one variable. You've probably seen them before. Each flag is a bit position which can be set on or off. You then have a bunch of bitmasks #defined for each bit position so you can easily manipulate it:
#define LOG_ERRORS 1 // 2^0, bit 0
#define LOG_WARNINGS 2 // 2^1, bit 1
#define LOG_NOTICES 4 // 2^2, bit 2
#define LOG_INCOMING 8 // 2^3, bit 3
#define LOG_OUTGOING 16 // 2^4, bit 4
#define LOG_LOOPBACK 32 // and so on...
// Only 6 flags/bits used, so a char is fine
unsigned char flags;
// initialising the flags
// note that assigning a value will clobber any other flags, so you
// should generally only use the = operator when initialising vars.
flags = LOG_ERRORS;
// sets to 1 i.e. bit 0
//initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3
// setting one flag on, leaving the rest untouched
// OR bitmask with the current value
flags |= LOG_INCOMING;
// testing for a flag
// AND with the bitmask before testing with ==
if ((flags & LOG_WARNINGS) == LOG_WARNINGS)
...
// testing for multiple flags
// as above, OR the bitmasks
if ((flags & (LOG_INCOMING | LOG_OUTGOING))
== (LOG_INCOMING | LOG_OUTGOING))
...
// removing a flag, leaving the rest untouched
// AND with the inverse (NOT) of the bitmask
flags &= ~LOG_OUTGOING;
// toggling a flag, leaving the rest untouched
flags ^= LOG_LOOPBACK;
**
WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and all others are unset. To test for a single flag you need to use & and == :
**
if (flags == LOG_WARNINGS) //DON'T DO THIS
...
if ((flags & LOG_WARNINGS) == LOG_WARNINGS) // The right way
...
if ((flags & (LOG_INCOMING | LOG_OUTGOING)) // Test for multiple flags set
== (LOG_INCOMING | LOG_OUTGOING))
...
You can also search C++ Triks
Using PuTTY's pscp.exe (which I have in an $env:path
directory):
pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*
This piece of code helps to convert back and forth
System.out.println("Date: "+ String.valueOf(new Date()));
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String stringdate = dt.format(new Date());
System.out.println("String.valueOf(date): "+stringdate);
try {
Date date = dt.parse(stringdate);
System.out.println("parse date: "+ String.valueOf(date));
} catch (ParseException e) {
e.printStackTrace();
}
This gets part way there. There is no ActualFontSize property but there is an ActualHeight and that would relate to the FontSize. Right now this only sizes for the original render. I could not figure out how to register the Converter as resize event. Actually maybe need to register the FontSize as a resize event. Please don't mark me down for an incomplete answer. I could not put code sample in a comment.
<Window.Resources>
<local:WidthConverter x:Key="widthConverter"/>
</Window.Resources>
<Grid>
<Grid>
<StackPanel VerticalAlignment="Center" Orientation="Vertical" >
<Viewbox Margin="100,0,100,0">
<TextBlock x:Name="headerText" Text="Lorem ipsum dolor" Foreground="Black"/>
</Viewbox>
<TextBlock Margin="150,0,150,0" FontSize="{Binding ElementName=headerText, Path=ActualHeight, Converter={StaticResource widthConverter}}" x:Name="subHeaderText" Text="Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, " TextWrapping="Wrap" Foreground="Gray" />
</StackPanel>
</Grid>
</Grid>
Converter
[ValueConversion(typeof(double), typeof(double))]
public class WidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)value*.7;
return width; // columnsCount;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Sounds like they want the ability to return only allowed fields, which means the number of fields returned also has to be dynamic. This will work with 2 variables. Anything more than that will be getting confusing.
IF (selectField1 = true AND selectField2 = true)
BEGIN
SELECT Field1, Field2
FROM Table
END
ELSE IF (selectField1 = true)
BEGIN
SELECT Field1
FROM Table
END
ELSE IF (selectField2 = true)
BEGIN
SELECT Field2
FROM Table
END
Dynamic SQL will help with multiples. This examples is assuming atleast 1 column is true.
DECLARE @sql varchar(MAX)
SET @sql = 'SELECT '
IF (selectField1 = true)
BEGIN
SET @sql = @sql + 'Field1, '
END
IF (selectField2 = true)
BEGIN
SET @sql = @sql + 'Field2, '
END
...
-- DROP ', '
@sql = SUBSTRING(@sql, 1, LEN(@sql)-2)
SET @sql = @sql + ' FROM Table'
EXEC(@sql)
Technically, there are two issues with the code posted by BGM:
the adding of the handlers in the WaitForPageLoad method is potentially too late. The navigation is initiated before the handlers are added which means that in very rare cases where the browser already has the page it may complete before the handlers are added in which case you will miss the event and sit forever waiting.
The solution is to add the handlers before the navigation starts and remove them after the navigation completed
This means the WaitForPageLoad method needs to be split into two methods. One is called before initiating the navigation. It should set the handlers. The second part does the ReadyState monitoring and cleans up when 'Ready'.
good programming practices is to add a timeout so that a lost (or crashed, or looping) browser doesn't make your code wait forever for the document completed even
You invoke the function with 2 parameters (@GenId and @Description):
EXEC etl.etl_M_Update_Promo @GenID, @Description
However you have declared the function to take 1 argument:
ALTER PROCEDURE [etl].[etl_M_Update_Promo]
@GenId bigint = 0
SQL Server is telling you that [etl_M_Update_Promo]
only takes 1 parameter (@GenId
)
You can alter the procedure to take two parameters by specifying @Description
.
ALTER PROCEDURE [etl].[etl_M_Update_Promo]
@GenId bigint = 0,
@Description NVARCHAR(50)
AS
.... Rest of your code.
Try the following
function sortCopy(arr) {
return arr.slice(0).sort();
}
The slice(0)
expression creates a copy of the array starting at element 0.
In your strings.xml file you can use any Unicode sign you want.
For example, the Unicode number for percent sign is 0025:
<string name="percent_sign">%</string>
You can see a comprehensive list of Unicode signs here
sbt
works in a fairly standard way comparing to the way other JVM-based projects are usually configured.
sbt is in fact two "subsystems" - the launcher and the core. It's usually xsbt.boot.Boot
that gets executed before the core starts up with the features we all know (and some even like).
It's therefore a matter of how you execute sbt that says how you could set up a proxy for HTTP, HTTPS and FTP network traffic.
The following is the entire list of the available properties that can be set for any Java application, sbt including, that instruct the Java API to route communication through a proxy:
Replace http
above with https
and ftp
to get the list of the properties for the services.
Some sbt
scripts use JAVA_OPTS
to set up the proxy settings with -Dhttp.proxyHost
and -Dhttp.proxyPort
amongst the others (listed above). See Java Networking and Proxies.
Some scripts come with their own way of setting up proxy configuration using the SBT_OPTS
property, .sbtopts
or (only on Windows) %SBT_HOME%\conf\sbtconfig.txt
. You can use them to specifically set sbt to use proxies while the other JVM-based applications are not affected at all.
From the sbt
command line tool:
# jvm options and output control
JAVA_OPTS environment variable, if unset uses "$java_opts"
SBT_OPTS environment variable, if unset uses "$default_sbt_opts"
.sbtopts if this file exists in the current directory, it is
prepended to the runner args
/etc/sbt/sbtopts if this file exists, it is prepended to the runner args
-Dkey=val pass -Dkey=val directly to the java runtime
-J-X pass option -X directly to the java runtime
(-J is stripped)
-S-X add -X to sbt's scalacOptions (-S is stripped)
And here comes an excerpt from sbt.bat
:
@REM Envioronment:
@REM JAVA_HOME - location of a JDK home dir (mandatory)
@REM SBT_OPTS - JVM options (optional)
@REM Configuration:
@REM sbtconfig.txt found in the SBT_HOME.
Be careful with sbtconfig.txt
that just works on Windows only. When you use cygwin
the file is not consulted and you will have to resort to using the other approaches.
I'm using sbt with the following script:
$JAVA_HOME/bin/java $SBT_OPTS -jar /Users/jacek/.ivy2/local/org.scala-sbt/sbt-launch/$SBT_LAUNCHER_VERSION-SNAPSHOT/jars/sbt-launch.jar "$@"
The point of the script is to use the latest version of sbt built from the sources (that's why I'm using /Users/jacek/.ivy2/local/org.scala-sbt/sbt-launch/$SBT_LAUNCHER_VERSION-SNAPSHOT/jars/sbt-launch.jar
) with $SBT_OPTS
property as a means of passing JVM properties to the JVM sbt uses.
The script above lets me to set proxy on command line on MacOS X as follows:
SBT_OPTS="-Dhttp.proxyHost=proxyhost -Dhttp.proxyPort=9999" sbt
As you can see, there are many approaches to set proxy for sbt that all pretty much boil down to set a proxy for the JVM sbt uses.
You can use +=
to concatenate your string, seems like no one answered that, which will be readable, and also neat... something like this
var hello = 'hello' +
'world' +
'blah';
can be also written as
var hello = 'hello';
hello += ' world';
hello += ' blah';
console.log(hello);
__del__
is a finalizer. It is called when an object is garbage collected which happens at some point after all references to the object have been deleted.
In a simple case this could be right after you say del x
or, if x
is a local variable, after the function ends. In particular, unless there are circular references, CPython (the standard Python implementation) will garbage collect immediately.
However, this is an implementation detail of CPython. The only required property of Python garbage collection is that it happens after all references have been deleted, so this might not necessary happen right after and might not happen at all.
Even more, variables can live for a long time for many reasons, e.g. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of cycle of references — CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.
Since you have no guarantee it's executed, one should never put the code that you need to be run into __del__()
— instead, this code belongs to finally
clause of the try
block or to a context manager in a with
statement. However, there are valid use cases for __del__
: e.g. if an object X
references Y
and also keeps a copy of Y
reference in a global cache
(cache['X -> Y'] = Y
) then it would be polite for X.__del__
to also delete the cache entry.
If you know that the destructor provides (in violation of the above guideline) a required cleanup, you might want to call it directly, since there is nothing special about it as a method: x.__del__()
. Obviously, you should you do so only if you know that it doesn't mind to be called twice. Or, as a last resort, you can redefine this method using
type(x).__del__ = my_safe_cleanup_method
you can use the query options {raw: true}
to return the raw result. Your query should like follows:
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw: true,
})
also if you have associations with include
that gets flattened. So, we can use another parameter nest:true
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw: true,
nest: true,
})
The sample below just does what you need programatically. I have used a fixed size of (140,398).
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(140, 398);
layoutParams.setMargins(24, 0, 24, 0);
layout.addView(button,layoutParams);
As mentioned in a comment above, you can have expressions within the template strings/literals. Example:
const one = 1;_x000D_
const two = 2;_x000D_
const result = `One add two is ${one + two}`;_x000D_
console.log(result); // output: One add two is 3
_x000D_
Another way to look at it is to consider git rebase master
as:
Rebase the current branch on top of
master
Here , 'master
' is the upstream branch, and that explain why, during a rebase, ours
and theirs
are reversed.
You can easily build a website as per the requirements. PHP will be there to handle the website development part. All the hosting and normal website development will work just as it is. However, for the streaming part, you will have to choose a good streaming service. Whether it is Red5 or Adobe, you can choose from plenty of services.
Choose a service that provides a dedicated storage to get something done right. If you do not know how to configure the server properly, you can just choose a streaming service. Good services often give a CDN that helps broadcast the stream efficiently. Simply launch your website in PHP and embed the YouTube player in the said web page to get it working.
you can just use post
to post your json.
values := map[string]string{"username": username, "password": password}
jsonValue, _ := json.Marshal(values)
resp, err := http.Post(authAuthenticatorUrl, "application/json", bytes.NewBuffer(jsonValue))
Actually every object in javascript resolves to true if it has "a real value" as W3Cschools puts it. That means everything except ""
, NaN
, undefined
, null
or 0
.
Testing a number against a boolean with the ==
operator indeed is a tad weird, since the boolean gets converted into numerical 1 before comparing, which defies a little bit the logic behind the definition.
This gets even more confusing when you do something like this:
var fred = !!3; // will set fred to true _x000D_
var joe = !!0; // will set joe to false_x000D_
alert("fred = "+ fred + ", joe = "+ joe);
_x000D_
not everything in javascript makes a lot of sense ;)
Another option you can choose:
select price = table1.price , other_price = table2.price from .....
Reference:
In case you are curious about the performance or otherwise of aliasing a column using “=” versus “as”.
Since you want to append elements to existing list, you can use var List[Int] and then keep on adding elements to the same list. Note -> You have to make sure that you insert an element into existing list as follows:-
var l: List[int] = List() // creates an empty list
l = 3 :: l // adds 3 to the head of the list
l = 4 :: l // makes int 4 as the head of the list
// Now when you will print l, you will see two elements in the list ( 4, 3)
This picture will remove everyone's confusion hopefully which is collected from there.
with open('test.txt', 'r') as inf, open('test1.txt', 'w') as outf:
for line in inf:
line = line.strip()
if line:
try:
outf.write(str(int(line, 16)))
outf.write('\n')
except ValueError:
print("Could not parse '{0}'".format(line))
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
IE 6+ .......... compatible ? Firefox 2+ ..... compatible ? Safari 3.2+ .... compatible ? Chrome 3+ ...... compatible ? Opera 10+ ...... compatible ?
http://requirejs.org/docs/download.html
Add this to your project: https://requirejs.org/docs/release/2.3.5/minified/require.js
and take a look at this http://requirejs.org/docs/api.html
I realise that posting links are not the best way to do things, but I highly recommend you read the following documentation from Google themselves. This is the official android doc on how to control your system ui (things like actionbar, nav bar etc). Unfortunately the info is too much to post directly, but after reading this you will understand exactly how to show and hide features no matter what version you are developing for, its so simple!
Incase the link ever changes, it can be found under the official android documentation under training -> getting started -> Best practices for user interface -> managing the system ui
Now a days, the easiest way I found to have a more updated version of Python is to install it via conda into a conda environment.
Install conda(you may need a virtualenv for this)
pip install conda
I'm adding this answer here because no manual download is needed. conda
will do that for you.
Now create an environment for the Python version you want. In this example I will use 3.5.2
, because it it the latest version at this time of writing (Aug 2016).
conda create -n py35 python=3.5.2
Will create a environment for conda to install packages
To activate this environment(I'm assuming linux otherwise check the conda docs):
source activate py35
Now install what you need either via pip or conda in the environemnt(conda has better binary package support).
conda install <package_name>
There are 2 simple ways:
Option 1
sp_help 'schema.table_name'
Option 2
SELECT * FROM INFORMATION_SCHEMA.columns c WHERE c.table_name = 'table_name'
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
The API changed again. It can be now found in:
tf.config.experimental.set_memory_growth(
device,
enable
)
Aliases:
References:
See also: Tensorflow - Use a GPU: https://www.tensorflow.org/guide/gpu
for Tensorflow 2.0 Alpha see: this answer
Connect with your mongodb instance from local system
It ll let you know all connected clients and their details
db.currentOp(true)
I'll explain the main use cases of implicits below, but for more detail see the relevant chapter of Programming in Scala.
Implicit parameters
The final parameter list on a method can be marked implicit
, which means the values will be taken from the context in which they are called. If there is no implicit value of the right type in scope, it will not compile. Since the implicit value must resolve to a single value and to avoid clashes, it's a good idea to make the type specific to its purpose, e.g. don't require your methods to find an implicit Int
!
example:
// probably in a library
class Prefixer(val prefix: String)
def addPrefix(s: String)(implicit p: Prefixer) = p.prefix + s
// then probably in your application
implicit val myImplicitPrefixer = new Prefixer("***")
addPrefix("abc") // returns "***abc"
Implicit conversions
When the compiler finds an expression of the wrong type for the context, it will look for an implicit Function
value of a type that will allow it to typecheck. So if an A
is required and it finds a B
, it will look for an implicit value of type B => A
in scope (it also checks some other places like in the B
and A
companion objects, if they exist). Since def
s can be "eta-expanded" into Function
objects, an implicit def xyz(arg: B): A
will do as well.
So the difference between your methods is that the one marked implicit
will be inserted for you by the compiler when a Double
is found but an Int
is required.
implicit def doubleToInt(d: Double) = d.toInt
val x: Int = 42.0
will work the same as
def doubleToInt(d: Double) = d.toInt
val x: Int = doubleToInt(42.0)
In the second we've inserted the conversion manually; in the first the compiler did the same automatically. The conversion is required because of the type annotation on the left hand side.
Regarding your first snippet from Play:
Actions are explained on this page from the Play documentation (see also API docs). You are using
apply(block: (Request[AnyContent]) ? Result): Action[AnyContent]
on the Action
object (which is the companion to the trait of the same name).
So we need to supply a Function as the argument, which can be written as a literal in the form
request => ...
In a function literal, the part before the =>
is a value declaration, and can be marked implicit
if you want, just like in any other val
declaration. Here, request
doesn't have to be marked implicit
for this to type check, but by doing so it will be available as an implicit value for any methods that might need it within the function (and of course, it can be used explicitly as well). In this particular case, this has been done because the bindFromRequest
method on the Form class requires an implicit Request
argument.
The cause of errors such as "Invalid application of sizeof to incomplete type with a struct ... " is always lack of an include statement. Try to find the right library to include.
Using the Call Stack Window
To open the Call Stack window in Visual Studio, from the Debug menu, choose Windows>Call Stack. To set the local context to a particular row in the stack trace display, double click the first column of the row.
http://msdn.microsoft.com/en-us/library/windows/hardware/hh439516(v=vs.85).aspx
Without code this is difficult to help you but here's some practical advice for you:
I suspect that your "image wall" has some sort of container with an id or class to give it styles.
eg:
<body>
<div id="maincontainer">
<div id="header"></div>
<div id="content">
<div id="imagewall">
<img src"img.jpg">
<!-- code continues -->
Styling a size on all images for your image wall, while not affecting other images, like you logo, etc. is easy if your code is set up similar to the above.
#imagewall img {
width: 100px;
height: 100px; }
But if your images are not perfectly square they will be skewed using this method.
$new_website = substr($str, ($pos = strrpos($str, '//')) !== false ? $pos + 2 : 0);
This would remove everything before the '//'.
EDIT
This one is tested. Using strrpos()
instead or strpos()
.
var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);
// This is because your method .getElementById has the letter 's': .getElement**s**ById
Interestingly, I found that if you pass in an empty string (as opposed to a null string, or a list of properties) for the third attribute of window.open, it would open in a new tab for Chrome, Firefox, and IE. If absent, the behavior was different.
So, this is my new call:
window.open(url, windowName, '');
Just this
passwd <<EOF
oldpassword
newpassword
newpassword
EOF
Actual output from ubuntu machine (sorry no AIX available to me):
user@host:~$ passwd <<EOF
oldpassword
newpassword
newpassword
EOF
Changing password for user.
(current) UNIX password: Enter new UNIX password: Retype new UNIX password:
passwd: password updated successfully
user@host:~$
The link you are referring to seems to work with strings generated at runtime. The strings from strings.xml are not created at runtime. You can get them via
String mystring = getResources().getString(R.string.mystring);
getResources()
is a method of the Context
class. If you are inside a Activity
or a Service
(which extend Context) you can use it like in this snippet.
Also note that the whole language dependency can be taken care of by the android framework.
Simply create different folders for each language. If english is your default language, just put the english strings into res/values/strings.xml
. Then create a new folder values-ru
and put the russian strings with identical names into res/values-ru/strings.xml
. From this point on android selects the correct one depending on the device locale for you, either when you call getString()
or when referencing strings in XML via @string/mystring
.
The ones from res/values/strings.xml
are the fallback ones, if you don't have a folder covering the users locale, this one will be used as default values.
See Localization and Providing Resources for more information.
Be carefull that the page does not contain any empty component which has "required" attribute as "true" before your selectOneMenu component running.
If you use a component such as
<p:inputText label="Nm:" id="id_name" value="#{ myHelper.name}" required="true"/>
then,
<p:selectOneMenu .....></p:selectOneMenu>
and forget to fill the required component, ajax listener of selectoneMenu cannot be executed.
My fix was suprisingly simple and another one of those obvious when you realise what you've done. I was manually building the configuration using .NET Core/Standard in the following fashion:
var configurationBuilder = new ConfigurationBuilder();
var root = configurationBuilder.Build();
and had forgotten to include the appsettings.json file that had my configuration settings in it
configurationBuilder.AddJsonFile("appsettings.json", false);
Once added, all started working once more.
Specifying a VOLUME
line in a Dockerfile configures a bit of metadata on your image, but how that metadata is used is important.
First, what did these two lines do:
WORKDIR /usr/src/app
VOLUME . /usr/src/app
The WORKDIR
line there creates the directory if it doesn't exist, and updates some image metadata to specify all relative paths, along with the current directory for commands like RUN
will be in that location. The VOLUME
line there specifies two volumes, one is the relative path .
, and the other is /usr/src/app
, both just happen to be the same directory. Most often the VOLUME
line only contains a single directory, but it can contain multiple as you've done, or it can be a json formatted array.
You cannot specify a volume source in the Dockerfile: A common source of confusion when specifying volumes in a Dockerfile is trying to match the runtime syntax of a source and destination at image build time, this will not work. The Dockerfile can only specify the destination of the volume. It would be a trivial security exploit if someone could define the source of a volume since they could update a common image on the docker hub to mount the root directory into the container and then launch a background process inside the container as part of an entrypoint that adds logins to /etc/passwd, configures systemd to launch a bitcoin miner on next reboot, or searches the filesystem for credit cards, SSNs, and private keys to send off to a remote site.
What does the VOLUME line do? As mentioned, it sets some image metadata to say a directory inside the image is a volume. How is this metadata used? Every time you create a container from this image, docker will force that directory to be a volume. If you do not provide a volume in your run command, or compose file, the only option for docker is to create an anonymous volume. This is a local named volume with a long unique id for the name and no other indication for why it was created or what data it contains (anonymous volumes are were data goes to get lost). If you override the volume, pointing to a named or host volume, your data will go there instead.
VOLUME breaks things: You cannot disable a volume once defined in a Dockerfile. And more importantly, the RUN
command in docker is implemented with temporary containers. Those temporary containers will get a temporary anonymous volume. That anonymous volume will be initialized with the contents of your image. Any writes inside the container from your RUN
command will be made to that volume. When the RUN
command finishes, changes to the image are saved, and changes to the anonymous volume are discarded. Because of this, I strongly recommend against defining a VOLUME
inside the Dockerfile. It results in unexpected behavior for downstream users of your image that wish to extend the image with initial data in volume location.
How should you specify a volume? To specify where you want to include volumes with your image, provide a docker-compose.yml
. Users can modify that to adjust the volume location to their local environment, and it captures other runtime settings like publishing ports and networking.
Someone should document this! They have. Docker includes warnings on the VOLUME usage in their documentation on the Dockerfile along with advice to specify the source at runtime:
- Changing the volume from within the Dockerfile: If any build steps change the data within the volume after it has been declared, those changes will be discarded.
...
- The host directory is declared at container run-time: The host directory (the mountpoint) is, by its nature, host-dependent. This is to preserve image portability, since a given host directory can’t be guaranteed to be available on all hosts. For this reason, you can’t mount a host directory from within the Dockerfile. The
VOLUME
instruction does not support specifying ahost-dir
parameter. You must specify the mountpoint when you create or run the container.
There's at least 7 different ways to test if a number is odd or even. But, if you read through these benchmarks, you'll find that as TGH mentioned above, the modulus operation is the fastest:
if (x % 2 == 0)
//even number
else
//odd number
Here are a few other methods (from the website) :
//bitwise operation
if ((x & 1) == 0)
//even number
else
//odd number
//bit shifting
if (((x >> 1) << 1) == x)
//even number
else
//odd number
//using native library
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
//even number
else
//odd number
I don't have much experience working with php but from a logic standpoint this is what I would do.
Below is some pseudocode illustrating this technique:
for (int i = 0; i < MySQLResults.count; i++){
$objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name);
// Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
$objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
$objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
}
If you git and GitHub user:
generate-package
more simply, than npm init
.
else
and/or you don't like package.json
template, that generate-package or npm init
generate:
you can generate your own template via scaffolding apps as generate, sails or yeoman.
This answer is relevant for March 2018. In the future, the data from this answer may be obsolete.
Author of this answer personally used generate-package at March 2018.
You need use git and GitHub for using generate-package.
For example, I create blank folder sasha-npm-init-vs-generate-package
.
Command:
D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package>gen package
[16:58:52] starting generate
[16:59:01] v running tasks: [ 'package' ]
[16:59:04] starting package
? Project description? generate-package demo
? Author's name? Sasha Chernykh
? Author's URL? https://vk.com/hair_in_the_wind
[17:00:19] finished package v 1m
package.json
:
{
"name": "sasha-npm-init-vs-generate-package",
"description": "generate-package demo",
"version": "0.1.0",
"homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package",
"author": "Sasha Chernykh (https://vk.com/hair_in_the_wind)",
"repository": "Kristinita/sasha-npm-init-vs-generate-package",
"bugs": {
"url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
},
"license": "MIT",
"engines": {
"node": ">=4"
},
"scripts": {
"test": "mocha"
},
"keywords": [
"generate",
"init",
"npm",
"package",
"sasha",
"vs"
]
}
D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (sasha-npm-init-vs-generate-package)
version: (1.0.0) 0.1.0
description: npm init demo
entry point: (index.js)
test command: mocha
git repository: https://github.com/Kristinita/sasha-npm-init-vs-generate-package
keywords: generate, package, npm, package, sasha, vs
author: Sasha Chernykh
license: (ISC) MIT
About to write to D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package\package.json:
{
"name": "sasha-npm-init-vs-generate-package",
"version": "0.1.0",
"description": "npm init demo",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Kristinita/sasha-npm-init-vs-generate-package.git"
},
"keywords": [
"generate",
"package",
"npm",
"package",
"sasha",
"vs"
],
"author": "Sasha Chernykh",
"license": "MIT",
"bugs": {
"url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
},
"homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package#readme"
}
Is this ok? (yes) y
{
"name": "sasha-npm-init-vs-generate-package",
"version": "0.1.0",
"description": "npm init demo",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Kristinita/sasha-npm-init-vs-generate-package.git"
},
"keywords": [
"generate",
"package",
"npm",
"package",
"sasha",
"vs"
],
"author": "Sasha Chernykh",
"license": "MIT",
"bugs": {
"url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
},
"homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package#readme"
}
I think, that generate-package
more simply, that npm init
.
That create your own package.json
template, see generate and yeoman examples.
Problem is when you already have an outline. Chrome still changes something and it's a real pain. I cannot find what to change :
.search input {
outline: .5em solid black;
width:41%;
background-color:white;
border:none;
font-size:1.4em;
padding: 0 0.5em 0 0.5em;
border-radius:3px;
margin:0;
height:2em;
}
.search input:focus, .search input:hover {
outline: .5em solid black !important;
box-shadow:none;
border-color:transparent;;
}
.search button {
border:none;
outline: .5em solid black;
color:white;
font-size:1.4em;
padding: 0 0.9em 0 0.9em;
border-radius: 3px;
margin:0;
height:2em;
background: -webkit-gradient(linear, left top, left bottom, from(#4EB4F8), to(#4198DE));
background: -webkit-linear-gradient(#4EB4F8, #4198DE);
background: -moz-linear-gradient(top, #4EB4F8, #4198DE);
background: -ms-linear-gradient(#4EB4F8, #4198DE);
background: -o-linear-gradient(#4EB4F8, #4198DE);
background: linear-gradient(#4EB4F8, #4198DE);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#4EB4F8', endColorstr='#4198DE');
zoom: 1;
}
It's possible, use the structure below:
<li><a><span></span></a></li>
<li><a><span></span></a></li>
etc...
Where the <li>
contains an <a>
anchor tag that contains a span as shown above. Then insert the following css:
position: relative;
<a>
tag a height
, width
<span>
width
& height
to 100%, so that both <a>
and <span>
have same dimensions<a>
and <span>
get position: relative;
.<a>
tag will have the 'OFF' background-position
, and the <span>
will have the 'ON' background-poisiton
.<span>
:hover
state use opacity 1 for <span>
-webkit
or -moz
transition on the <span>
elementYou'll have the ability to use the transition effect while still defaulting to the old background-position
swap. Don't forget to insert IE alpha filter.
I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle
file as following:
rootProject.name='YourNewName'
This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.
Try below code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:bottomLeftRadius="30dp"
android:bottomRightRadius="30dp"
android:topLeftRadius="30dp"
android:topRightRadius="30dp" />
<solid android:color="#1271BB" />
<stroke
android:width="5dp"
android:color="#1271BB" />
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" /></shape>
Adding to John and Tim's answer.
Unless you are coding for Win98, there are only two of the 6+ string types you should be using in your application
LPWSTR
LPCWSTR
The rest are meant to support ANSI platforms or dual compilations. Those are not as relevant today as they used to be.
Firefox Screenshots is a new tool that ships with Firefox. It is not a developer tool, it is aimed at end-users of the browser.
To take a screenshot, click on the page actions menu in the address bar, and click "take a screenshot". If you then click "Save full page", it will save the full page, scrolling for you.
(source: mozilla.net)
I thought I would add to this question as it is the top google search result.
As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.
As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating
// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
.Where(t =>
t.ClrType.GetProperties()
.Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
// get the keys in the appropriate order
var orderedKeys = entity.ClrType
.GetProperties()
.Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
.OrderBy(p =>
p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
.NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
.TypedValue.Value ?? 0)
.Select(x => x.Name)
.ToArray();
// apply the keys to the model builder
modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}
I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone
One example is when you write a parser function and pass it a source pointer to read from, if the function is supposed to push that pointer forward behind the last character which has been correctly recognized by the parser. Using a reference to a pointer makes it clear then that the function will move the original pointer to update its position.
In general, you use references to pointers if you want to pass a pointer to a function and let it move that original pointer to some other position instead of just moving a copy of it without affecting the original.
You might want to check out this tutorial: http://www.webdesignerwall.com/tutorials/css-decorative-gallery/
In it the writer uses an empty span element to add an overlaying image. You can use jQuery to inject said span elements, if you'd like to keep your code as clean as possible. An example is also given in the aforementioned article.
Hope this helps!
-Dave
This is my xml customTextView Object here you can use simply TextView to replace on Tag.
<com.wedoapps.crickethisabkitab.utils.view.montserrat.CustomTextView
android:id="@+id/lblRateUsPlayStore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/_10sdp"
android:layout_marginBottom="@dimen/_10sdp"
android:layout_marginStart="@dimen/_5sdp"
android:layout_marginEnd="@dimen/_5sdp"
android:text="@string/please_rate_us_5_star_on_play_store"
android:textAllCaps="false"
android:textColor="@color/green"
android:textSize="@dimen/_25ssp"
android:textStyle="bold"
android:visibility="visible"
android:linksClickable="true"
android:autoLink="web|phone"/>
And here is My Java File code. i have set my html text on server just replace your text on textview object. i have put this code is marquee tag with clickable if any links on this textview to open mobile or webBrowser.
CustomTextView lblRateUsPlayStore = findViewById(R.id.lblRateUsPlayStore);
lblRateUsPlayStore.setMovementMethod(LinkMovementMethod.getInstance());
lblRateUsPlayStore.setText( Html.fromHtml(documentSnapshot.getString("DisplayText")));
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(lblRateUsPlayStore, 12, 20, 2, 1);
lblRateUsPlayStore.setEllipsize(TextUtils.TruncateAt.MARQUEE);
// Set marquee repeat limit (unlimited)
lblRateUsPlayStore.setMarqueeRepeatLimit(-1);
lblRateUsPlayStore.setHorizontallyScrolling(true);
lblRateUsPlayStore.setSelected(true);
lblRateUsPlayStore.setLinksClickable(true);
lblRateUsPlayStore.setFocusableInTouchMode(true);
lblRateUsPlayStore.setFocusable(true);
I struggled with this as well, but I managed to find a workaround.
When you run into the error above, just cherry-pick the merge commit and then continue the rebase:
git cherry-pick -m 1 1234deadbeef1234deadbeef
git rebase --continue
My problem was in the config file of the domain:
the public folder of my project was created in /home/vagrant/Code/demo/public
the config file of the domain (for me /etc/nginx/sites-available/demo.app) had configured: "/home/vagrant/Code/Laravel/public" instead of "/home/vagrant/Code/demo/public".
Now it is working perfect.
In my case i did following code for compare 2 dates may it will help you ...
var date1 = "2010-10-20";_x000D_
var date2 = "2010-10-20";_x000D_
var time1 = moment(date1).format('YYYY-MM-DD');_x000D_
var time2 = moment(date2).format('YYYY-MM-DD');_x000D_
if(time2 > time1){_x000D_
console.log('date2 is Greter than date1');_x000D_
}else if(time2 > time1){_x000D_
console.log('date2 is Less than date1');_x000D_
}else{_x000D_
console.log('Both date are same');_x000D_
}
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
I use this script in my extension "Grab Any Media" and work fine ( like youtube case )
var oldHref = document.location.href;
window.onload = function() {
var
bodyList = document.querySelector("body")
,observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (oldHref != document.location.href) {
oldHref = document.location.href;
/* Changed ! your code here */
}
});
});
var config = {
childList: true,
subtree: true
};
observer.observe(bodyList, config);
};
Though static keyword not supported in interface in Typescript
but we can achieve it by creating a function interface
that has static member.
In my following code I have created a function interface Factory
that has two static members serialNumber
and printSerial.
// factory is a function interface
interface Factory<T> {
(name: string, age: number): T;
//staic property
serialNumber: number;
//static method
printSrial: () => void;
}
class Dog {
constructor(public name: string, public age: number) { }
}
const dogFactory: Factory<Dog> = (name, age) => {
return new Dog(name, age);
}
// initialising static members
dogFactory.serialNumber = 1234;
dogFactory.printSrial = () => console.log(dogFactory.serialNumber);
//instance of Dog that DogFactory creates
const myDog = dogFactory("spike", 3);
//static property that returns 1234
console.log(dogFactory.serialNumber)
//static method that prints the serial 1234
dogFactory.printSrial();
$json = @"
{
"Stuffs":
[
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
}
"@
$x = $json | ConvertFrom-Json
$x.Stuffs[0] # access to Darts
$x.Stuffs[1] # access to Clean Toilet
$darts = $x.Stuffs | where { $_.Name -eq "Darts" } #Darts
You can call the function from code behind like this :
MyForm.aspx.cs
protected void MyButton_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
}
MyForm.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Test() {
alert("hi");
$("#ButtonRow").show();
}
function AnotherFunction()
{
alert("This is another function");
}
</script>
</head>
<body>
<form id="form2" runat="server">
<table>
<tr><td>
<asp:RadioButtonList ID="SearchCategory" runat="server" onchange="Test()" RepeatDirection="Horizontal" BorderStyle="Solid">
<asp:ListItem>Merchant</asp:ListItem>
<asp:ListItem>Store</asp:ListItem>
<asp:ListItem>Terminal</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr id="ButtonRow"style="display:none">
<td>
<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
</td>
</tr>
</table>
</form>
If you set the editable div style to "display:inline-block; white-space: pre-wrap" you don't get new child divs when you enter a new line, you just get LF character (i.e. 
);.
function showCursPos(){
selection = document.getSelection();
childOffset = selection.focusOffset;
const range = document.createRange();
eDiv = document.getElementById("eDiv");
range.setStart(eDiv, 0);
range.setEnd(selection.focusNode, childOffset);
var sHtml = range.toString();
p = sHtml.length;
sHtml=sHtml.replace(/(\r)/gm, "\\r");
sHtml=sHtml.replace(/(\n)/gm, "\\n");
document.getElementById("caretPosHtml").value=p;
document.getElementById("exHtml").value=sHtml;
}
_x000D_
click/type in div below:
<br>
<div contenteditable name="eDiv" id="eDiv"
onkeyup="showCursPos()" onclick="showCursPos()"
style="width: 10em; border: 1px solid; display:inline-block; white-space: pre-wrap; "
>123 456 789</div>
<p>
html caret position:<br> <input type="text" id="caretPosHtml">
<p>
html from start of div:<br> <input type="text" id="exHtml">
_x000D_
What I noticed was when you press "enter" in the editable div, it creates a new node, so the focusOffset resets to zero. This is why I've had to add a range variable, and extend it from the child nodes' focusOffset back to the start of eDiv (and thus capturing all text in-between).
In general, fixing corrupt objects can be pretty difficult. However, in this case, we're confident that the problem is an aborted transfer, meaning that the object is in a remote repository, so we should be able to safely remove our copy and let git get it from the remote, correctly this time.
The temporary object file, with zero size, can obviously just be removed. It's not going to do us any good. The corrupt object which refers to it, d4a0e75...
, is our real problem. It can be found in .git/objects/d4/a0e75...
. As I said above, it's going to be safe to remove, but just in case, back it up first.
At this point, a fresh git pull
should succeed.
...assuming it was going to succeed in the first place. In this case, it appears that some local modifications prevented the attempted merge, so a stash
, pull
, stash pop
was in order. This could happen with any merge, though, and didn't have anything to do with the corrupted object. (Unless there was some index cleanup necessary, and the stash did that in the process... but I don't believe so.)
Note the potential for an out-of-range index with "i+3". You could do something like:
with open("file.txt", "r") as f:
searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
if "searchphrase" in line:
k=min(i+3,j)
for l in searchlines[i:k]: print l,
print
Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.
This can be accomplished by Unmarshaling into a map[string]json.RawMessage
.
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
To further parse sendMsg
, you could then do something like:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)
For say
, you can do the same thing and unmarshal into a string:
var str string
err = json.Unmarshal(objmap["say"], &str)
EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:
type sendMsg struct {
User string
Msg string
}
import org.junit.Assert
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
class FeatureTest {
companion object {
private lateinit var heavyFeature: HeavyFeature
@BeforeClass
@JvmStatic
fun beforeHeavy() {
heavyFeature = HeavyFeature()
}
}
private lateinit var feature: Feature
@Before
fun before() {
feature = Feature()
}
@Test
fun testCool() {
Assert.assertTrue(heavyFeature.cool())
Assert.assertTrue(feature.cool())
}
@Test
fun testWow() {
Assert.assertTrue(heavyFeature.wow())
Assert.assertTrue(feature.wow())
}
}
Same as
import org.junit.Assert
import org.junit.Test
class FeatureTest {
companion object {
private val heavyFeature = HeavyFeature()
}
private val feature = Feature()
@Test
fun testCool() {
Assert.assertTrue(heavyFeature.cool())
Assert.assertTrue(feature.cool())
}
@Test
fun testWow() {
Assert.assertTrue(heavyFeature.wow())
Assert.assertTrue(feature.wow())
}
}
Swift 4+
button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
Well, even in Java 8, long
and int
are still signed, only some methods treat them as if they were unsigned. If you want to write unsigned long
literal like that, you can do
static long values = Long.parseUnsignedLong("18446744073709551615");
public static void main(String[] args) {
System.out.println(values); // -1
System.out.println(Long.toUnsignedString(values)); // 18446744073709551615
}
I would put decimal.MaxValue.ToString()
since this is the effective ceiling for the decmial type it is equivalent to not having an upper bound.
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
For extremely secure systems we encrypt the database password in a configuration file (which itself is secured by the system administrator). On application/server startup the application then prompts the system administrator for the decryption key. The database password is then read from the config file, decrypted, and stored in memory for future use. Still not 100% secure since it is stored in memory decrypted, but you have to call it 'secure enough' at some point!
When I asked this question, my real question was, "is there a difference between the two? Doesn't the runtime have to keep information about the array size, and so will it not be able to tell which one we mean?" This question does not appear in "related questions", so just to help out those like me, here is the answer to that: "why do we even need the delete[] operator?"
I also need the container name or Id which a script requires to attach to the container. took some tweaking but this works perfectly well for me...
export svr=$(docker ps --format "table {{.ID}}"| sed 's/CONTAINER ID//g' | sed '/^[[:space:]]*$/d')
docker exec -it $svr bash
The sed command is needed to get rid of the fact that the words CONTAINER ID gets printed too ... but I just need the actual id stored in a var.
If you are using TypeScript
and don't want to account for "values those are false
" then this is the solution for you:
First: import { isNullOrUndefined } from 'util';
Then: isNullOrUndefined(this.yourVariableName)
Please Note: As mentioned below this is now deprecated, use value === undefined || value === null
instead. ref.
In java syntax:
rdd.collect().forEach(line -> System.out.println(line));
I am not sure whether the database backup file, you trying to restore, is coming from the same environment as you trying to restore it onto.
Remember that destination path of .mdf and .ldf files lives with the backup file itself.
If this is not a case, that means the backup file is coming from a different environment from your current hosting one, make sure that .mdf and .ldf file path is the same (exists) as on your machine, relocate these otherwise. (Mostly a case of restoring db in Docker image)
The way how to do it: In Databases -> Restore database -> [Files] option -> (Check "Relocate all files to folder" - mostly default path is populated on your hosting environment already)
The date solution is much better than others, I had to increment the time on 50 like that this is a Tweeter example:
//on click or your event handler..
var twMessage = "Your Message to share";
var now = new Date().valueOf();
setTimeout(function () {
if (new Date().valueOf() - now > 100) return;
var twitterUrl = "https://twitter.com/share?text="+twMessage;
window.open(twitterUrl, '_blank');
}, 50);
window.location = "twitter://post?message="+twMessage;
the only problem on Mobile IOS Safari is when you don't have the app installed on device, and so Safari show an alert that autodismiss when the new url is opened, anyway is a good solution for now!
A very simple solution is put the below code in your .htaccess
. I had the same issue and it solve my problem.
<IfModule mod_alias.c>
RedirectMatch 403 favicon.ico
</IfModule>
Reference: http://perishablepress.com/block-favicon-url-404-requests/
I didn't verify this myself, but you can look at this JavaScript implementation of Java's String.hashCode() method. Seems reasonably short.
With this prototype you can simply call
.hashCode()
on any string, e.g."some string".hashCode()
, and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.
String.prototype.hashCode = function() {
var hash = 0;
if (this.length == 0) {
return hash;
}
for (var i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
To change the size of (almost) all text elements, in one place, and synchronously, rel()
is quite efficient:
g+theme(text = element_text(size=rel(3.5))
You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)),
strip.text.x = element_text(size=rel(3.5)),
strip.text.y = element_text(size=rel(3.5)))
Use subprocess.Popen:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)
Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.
If you use the gson.JsonObject you can have something like that:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)
With files we know the size in advance, so just read it all at once!
String result;
File file = ...;
long length = file.length();
if (length < 1 || length > Integer.MAX_VALUE) {
result = "";
Log.w(TAG, "File is empty or huge: " + file);
} else {
try (FileReader in = new FileReader(file)) {
char[] content = new char[(int)length];
int numRead = in.read(content);
if (numRead != length) {
Log.e(TAG, "Incomplete read of " + file + ". Read chars " + numRead + " of " + length);
}
result = new String(content, 0, numRead);
}
catch (Exception ex) {
Log.e(TAG, "Failure reading " + this.file, ex);
result = "";
}
}
The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
SELECT text
FROM all_source
where name = 'FGETALGOGROUPKEY'
order by line
alternatively:
select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY')
from dual;
The problem may be that ssh is trying to connect to all the different IPs that www.google.com
resolves to. For example on my machine:
# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out
If I run it with a specific IP, it returns much faster.
EDIT: I've timed it (with time
) and the results are:
In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.
MyClass.php
namespace com\company\lib;
class MyClass {
}
index.php
namespace com\company\lib;
//Works fine
$i = new MyClass();
$cname = 'MyClass';
//Errors
//$i = new $cname;
//Works fine
$cname = "com\\company\\lib\\".$cname;
$i = new $cname;
You can use unset
:
unset($array['key-here']);
Example:
$array = array("key1" => "value1", "key2" => "value2");
print_r($array);
unset($array['key1']);
print_r($array);
unset($array['key2']);
print_r($array);
Output:
Array
(
[key1] => value1
[key2] => value2
)
Array
(
[key2] => value2
)
Array
(
)
Since Docker 17.05 COPY
is used with the --from
flag in multi-stage builds to copy artifacts from previous build stages to the current build stage.
from the documentation
Optionally COPY accepts a flag
--from=<name|index>
that can be used to set the source location to a previous build stage (created with FROM .. AS ) that will be used instead of a build context sent by the user.
I had this error when i was using the azure storage as a static website, the js files that are copied had the content type as text/plain; charset=utf-8
and i changed the content type to application/javascript
It started working.
A superfast XML Method, if you want to use a stored procedure and pass the comma separated list of Department IDs :
Declare @XMLList xml
SET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml)
SELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))
All credit goes to Guru Brad Schulz's Blog
I solve it just by changing 'http://webname...'
to "http://webname..."
Notice the quote. It should be double ("
) instead of single ('
).
<select id="myDropDown">
<option>html5</option>
<option>javascript</option>
<option>jquery</option>
<option>css</option>
<option>sencha</option>
</select>
By jQuery:
var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
//close dropdown
myDropDown.attr('size',0);
By javascript:
var myDropDown=document.getElementById("myDropDown");
var length = myDropDown.options.length;
//open dropdown
myDropDown.size = length;
//close dropdown
myDropDown.size = 0;
Copied from: Open close select
I have several projects running on my box. If you have already installed more than one version, this bash script should help you easily switch. At the moment I have php5, php5.6, and php7.0 which I often swtich back and forth depending on the project I am working on. Here is my code.
Feel free to copy. Make sure you understand how the code works. This is for the webhostin. my local box my mods are stored at /etc/apache2/mods-enabled/
#!/bin/bash
# This file is for switching php versions.
# To run this file you must use bash, not sh
#
# OS: Ubuntu 14.04 but should work on any linux
# Example: bash phpswitch.sh 7.0
# Written by Daniel Pflieger
# growlingflea at g mail dot com
NEWVERSION=$1 #this is the git directory target
#get the active php enabled mod by getting the array of files and store
#it to a variable
VAR=$(ls /etc/apache2/mods-enabled/php*)
#parse the returned variables and get the version of php that is active.
IFS=' ' read -r -a array <<< "$VAR"
array[0]=${array[0]#*php}
array[0]=${array[0]%.conf}
#confirm that the newversion veriable isn't empty.. if it is tell user
#current version and exit
if [ "$NEWVERSION" = "" ]; then
echo current version is ${array[0]}. To change version please use argument
exit 1
fi
OLDVERSION=${array[0]}
#confirm to the user this is what they want to do
echo "Update php" ${OLDVERSION} to ${NEWVERSION}
#give the user the opportunity to use CTRL-C to exit ot just hit return
read x
#call a2dismod function: this deactivate the current php version
sudo a2dismod php${OLDVERSION}
#call the a2enmod version. This enables the new mode
sudo a2enmod php${NEWVERSION}
echo "Restart service??"
read x
#restart apache
sudo service apache2 restart
The above code not worked for me. I found new solution :
var pdf = new jsPDF();
var img = new Image;
img.onload = function() {
pdf.addImage(this, 10, 10);
pdf.save("test.pdf");
};
img.crossOrigin = "";
img.src = "assets/images/logo.png";
Note :- Certainly in python-3x you need to use Range function It works to generate numbers on demand, standard method to use Range function to make a list of consecutive numbers is
x=list(range(10))
#"list"_will_make_all_numbers_generated_by_range_in_a_list
#number_in_range_(10)_is_an_option_you_can_change_as_you_want
print (x)
#Output_is_ [0,1,2,3,4,5,6,7,8,9]
Also if you want to make an function to generate a list of consecutive numbers by using Range function watch this code !
def consecutive_numbers(n) :
list=[i for i in range(n)]
return (list)
print(consecutive_numbers(10))
Good Luck!
The closest approach I can think of is NULLIF:
SELECT
ISNULL(NULLIF(O.ShipName, C.CompanyName), 1),
O.ShipName,
C.CompanyName,
O.OrderId
FROM [Northwind].[dbo].[Orders] O
INNER JOIN [Northwind].[dbo].[Customers] C
ON C.CustomerId = O.CustomerId
GO
NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.
So, above query will return 1 for records in which that columns are equal, the first expression otherwise.
For chinese Rails developers:
DateTime.strptime('2012-12-09 00:01:36', '%Y-%m-%d %H:%M:%S')
=> Sun, 09 Dec 2012 00:01:36 +0000
Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use
string s = Char.ConvertFromUtf32(56);
which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.
Use \Q
to autoescape any potentially problematic characters in your variable.
if($text_to_search =~ m/\Q$search_string/) print "wee";
Also take note that the object instantiated via using
is read-only within the using block. Refer to the official C# reference here.
var defaultsettings = {
ajaxsettings: {
...
},
uisettings: {
...
}
};
For an in-place sort, use
foo = [(list of tuples)]
foo.sort(key=lambda x:x[0]) #To sort by first element of the tuple
You need to use the as.Date formats correctly.
Eg.
x = '2012/07/25'
xd = as.Date(x,'%Y/%m/%d')
xd # Prints "2012-07-25"
R date formats are similary to *nix ones.
Doing a typeof(xd) shows it as a double ie. days since 1970.
I would use:
val, idx = min((val, idx) for (idx, val) in enumerate(my_list))
Then val
will be the minimum value and idx
will be its index.
You can use dict.pop
:
mydict.pop("key", None)
Note that if the second argument, i.e. None
is not given, KeyError
is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.
The Dev Tools in Edge finally added support for managing and browsing cookies.
Note: Even if you are testing and supporting IE targets, you mine as well do the heavy lifting of your browser compatibility testing by leveraging the new tooling in Edge, and defer checking in IE 11 (etc) for the last leg.
The benefit, of course, to the debugger tab is you don't have to hunt and peck for individual cookies across multiple different and historical requests.
Honestly, I hate all the solutions I've seen so far, and I'll tell you why: They just don't seem to ever align it right...so here's what I usually do:
I know what pixel values each div and their respective margins hold...so I do the following.
I'll create a wrapper div that has an absolute position and a left value of 50%...so this div now starts in the middle of the screen, and then I subtract half of all the content of the div's width...and I get BEAUTIFULLY scaling content...and I think this works across all browsers, too. Try it for yourself (this example assumes all content on your site is wrapped in a div tag that uses this wrapper class and all content in it is 200px in width):
.wrapper {
position: absolute;
left: 50%;
margin-left: -100px;
}
EDIT: I forgot to add...you may also want to set width: 0px; on this wrapper div for some browsers to not show the scrollbars, and then you may use absolute positioning for all inner divs.
This also works AMAZING for vertically aligning your content as well using top: 50% and margin-top. Cheers!
The problem is most likely because you config custom UITableViewCell
in storyboard but you do not use storyboard to instantiate your UITableViewController
which uses this UITableViewCell
. For example, in MainStoryboard, you have a UITableViewController
subclass called MyTableViewController
and have a custom dynamic UITableViewCell
called MyTableViewCell
with identifier id "MyCell".
If you create your custom UITableViewController
like this:
MyTableViewController *myTableViewController = [[MyTableViewController alloc] init];
It will not automatically register your custom tableviewcell for you. You have to manually register it.
But if you use storyboard to instantiate MyTableViewController
, like this:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
MyTableViewController *myTableViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyTableViewController"];
Nice thing happens! UITableViewController
will automatically register your custom tableview cell that you define in storyboard for you.
In your delegate method "cellForRowAtIndexPath", you can create you table view cell like this :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//Configure your cell here ...
return cell;
}
dequeueReusableCellWithIdentifier will automatically create new cell for you if there is not reusable cell available in the recycling queue.
Then you are done!
Disabling a html button
document.getElementById("Button").disabled = true;
Enabling a html button
document.getElementById("Button").disabled = false;
All versions of jQuery prior to 1.6
Disabling a html button
$('#Button').attr('disabled','disabled');
Enabling a html button
$('#Button').removeAttr('disabled');
All versions of jQuery after 1.6
Disabling a html button
$('#Button').prop('disabled', true);
Enabling a html button
$('#Button').prop('disabled', false);
P.S. Updated the code based on jquery 1.6.1 changes. As a suggestion, always use the latest jquery files and the prop()
method.
Simple Steps:
-Open Eclipse.
From my answer here, thought this might be useful:
I tried many steps to get this issue corrected. There are so many sources for possible solutions to this issue that is is hard to filter out the sense from the nonsense. I finally found a good solution here:
Step 1: Identify the Database Version
$ mysql --version
You'll see some output like this with MySQL:
$ mysql Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using EditLine wrapper
Or output like this for MariaDB:
mysql Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1
Make note of which database and which version you're running, as you'll use them later. Next, you need to stop the database so you can access it manually.
Step 2: Stopping the Database Server
To change the root password, you have to shut down the database server beforehand.
You can do that for MySQL with:
$ sudo systemctl stop mysql
And for MariaDB with:
$ sudo systemctl stop mariadb
Step 3: Restarting the Database Server Without Permission Checking
If you run MySQL and MariaDB without loading information about user privileges, it will allow you to access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.
To do this, you need to stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip networking as well to prevent other clients from connecting.
Start the database without loading the grant tables or enabling networking:
$ sudo mysqld_safe --skip-grant-tables --skip-networking &
The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.
Now you can connect to the database as the root user, which should not ask for a password.
$ mysql -u root
You'll immediately see a database shell prompt instead.
MySQL Prompt
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
MariaDB Prompt
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
Now that you have root access, you can change the root password.
Step 4: Changing the Root Password
mysql> FLUSH PRIVILEGES;
Now we can actually change the root password.
For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command:
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
Make sure to replace new_password
with your new password of choice.
Note: If the ALTER USER
command doesn't work, it's usually indicative of a bigger problem. However, you can try UPDATE ... SET
to reset the root password instead.
[IMPORTANT] This is the specific line that fixed my particular issue:
mysql> UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';
Remember to reload the grant tables after this.
In either case, you should see confirmation that the command has been successfully executed.
Query OK, 0 rows affected (0.00 sec)
The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.
Step 5: Restart the Database Server Normally
The tutorial goes into some further steps to restart the database, but the only piece I used was this:
For MySQL, use: $ sudo systemctl start mysql
For MariaDB, use:
$ sudo systemctl start mariadb
Now you can confirm that the new password has been applied correctly by running:
$ mysql -u root -p
The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.
Conclusion
You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.
Note: with Git 2.14.x/2.15 (Q3 2017), the git rebase
message in case of conflicts will be clearer.
See commit 5fdacc1 (16 Jul 2017) by William Duclot (williamdclt
).
(Merged by Junio C Hamano -- gitster
-- in commit 076eeec, 11 Aug 2017)
rebase
: make resolve message clearer for inexperienced users
Before:
When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort"
After:
Resolve all conflicts manually,
mark them as resolved with git add/rm <conflicted_files>
then run "git rebase --continue".
You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".')
The git UI can be improved by addressing the error messages to those they help: inexperienced and casual git users.
To this intent, it is helpful to make sure the terms used in those messages can be understood by this segment of users, and that they guide them to resolve the problem.In particular, failure to apply a patch during a git rebase is a common problem that can be very destabilizing for the inexperienced user.
It is important to lead them toward the resolution of the conflict (which is a 3-steps process, thus complex) and reassure them that they can escape a situation they can't handle with "--abort
".
This commit answer those two points by detailing the resolution process and by avoiding cryptic git linguo.
The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS
In my case the accepted answer did not work. I was calling the API from an MVC application which had no async actions.
This is how I managed to make it work:
private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static T RunSync<T>(Func<Task<T>> func)
{
CultureInfo cultureUi = CultureInfo.CurrentUICulture;
CultureInfo culture = CultureInfo.CurrentCulture;
return _myTaskFactory.StartNew<Task<T>>(delegate
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return func();
}).Unwrap<T>().GetAwaiter().GetResult();
}
Then I called it like this:
Helper.RunSync(new Func<Task<ReturnTypeGoesHere>>(async () => await AsyncCallGoesHere(myparameter)));
try this for comparision
if "%INPUT%"=="y"...
The extra [ ] on the outside of your second syntax are unnecessary, and possibly confusing. You may use them, but if you must you need to have whitespace between them.
Alternatively:
while [ $stats -gt 300 ] || [ $stats -eq 0 ]
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
Try this:
$.datepicker.parseDate("yy-mm-dd", minValue);
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
Try This Code $scope.DSRListGrid.data = data; this one for source data
for (var prop in data[0]) {
if (data[0].hasOwnProperty(prop)) {
$scope.ListColumns.push(
{
"name": prop,
"field": prop,
"width": 150,
"headerCellClass": 'font-12'
}
);
}
}
console.log($scope.ListColumns);
Step 1: Get HttpURLConnection object
URL url = new URL(urlToConnect);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
Step 2: Add headers to the HttpURLConnection using setRequestProperty method.
Map<String, String> headers = new HashMap<>();
headers.put("X-CSRF-Token", "fetch");
headers.put("content-type", "application/json");
for (String headerKey : headers.keySet()) {
httpUrlConnection.setRequestProperty(headerKey, headers.get(headerKey));
}
Reference link
I know that I am late to party but performed test before actually implement the solution.
I did perform test against inbuilt MD5 class and also md5sum.exe. In my case inbuilt class took 13 second where md5sum.exe too around 16-18 seconds in every run.
DateTime current = DateTime.Now;
string file = @"C:\text.iso";//It's 2.5 Gb file
string output;
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(file))
{
byte[] checksum = md5.ComputeHash(stream);
output = BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower();
Console.WriteLine("Total seconds : " + (DateTime.Now - current).TotalSeconds.ToString() + " " + output);
}
}
Eclipse IDE for Java Developers 'Servers' doesn't exist. Therefore download correct Eclipse IDE. It is Eclipse IDE for Enterprise Java Developers(Eclipse IDE for Java EE Developers). This way is easy.
You can Use This code.
var checkbox = document.getElementById("dlCheckAll4Delete");
checkbox.addEventListener("click", function (event) {
let checkboxes = document.querySelectorAll(".dlMultiDelete");
checkboxes.forEach(function (ele) {
ele.checked = !!checkbox.checked;
});
});
You can find an overview of a lot of design patterns in Wikipedia. It also mentions which patterns are mentioned by GoF. I'll sum them up here and try to assign as many pattern implementations as possible, found in both the Java SE and Java EE APIs.
javax.xml.parsers.DocumentBuilderFactory#newInstance()
javax.xml.transform.TransformerFactory#newInstance()
javax.xml.xpath.XPathFactory#newInstance()
java.lang.StringBuilder#append()
(unsynchronized)java.lang.StringBuffer#append()
(synchronized)java.nio.ByteBuffer#put()
(also on CharBuffer
, ShortBuffer
, IntBuffer
, LongBuffer
, FloatBuffer
and DoubleBuffer
)javax.swing.GroupLayout.Group#addComponent()
java.lang.Appendable
java.util.stream.Stream.Builder
java.util.Calendar#getInstance()
java.util.ResourceBundle#getBundle()
java.text.NumberFormat#getInstance()
java.nio.charset.Charset#forName()
java.net.URLStreamHandlerFactory#createURLStreamHandler(String)
(Returns singleton object per protocol)java.util.EnumSet#of()
javax.xml.bind.JAXBContext#createMarshaller()
and other similar methodsjava.lang.Object#clone()
(the class has to implement java.lang.Cloneable
)java.util.Arrays#asList()
java.util.Collections#list()
java.util.Collections#enumeration()
java.io.InputStreamReader(InputStream)
(returns a Reader
)java.io.OutputStreamWriter(OutputStream)
(returns a Writer
)javax.xml.bind.annotation.adapters.XmlAdapter#marshal()
and #unmarshal()
new LinkedHashMap(LinkedHashSet<K>, List<V>)
which returns an unmodifiable linked map which doesn't clone the items, but uses them. The java.util.Collections#newSetFromMap()
and singletonXXX()
methods however comes close.java.awt.Container#add(Component)
(practically all over Swing thus)javax.faces.component.UIComponent#getChildren()
(practically all over JSF UI thus)java.io.InputStream
, OutputStream
, Reader
and Writer
have a constructor taking an instance of same type.java.util.Collections
, the checkedXXX()
, synchronizedXXX()
and unmodifiableXXX()
methods.javax.servlet.http.HttpServletRequestWrapper
and HttpServletResponseWrapper
javax.swing.JScrollPane
javax.faces.context.FacesContext
, it internally uses among others the abstract/interface types LifeCycle
, ViewHandler
, NavigationHandler
and many more without that the enduser has to worry about it (which are however overrideable by injection).javax.faces.context.ExternalContext
, which internally uses ServletContext
, HttpSession
, HttpServletRequest
, HttpServletResponse
, etc.java.lang.Integer#valueOf(int)
(also on Boolean
, Byte
, Character
, Short
, Long
and BigDecimal
)java.lang.reflect.Proxy
java.rmi.*
javax.ejb.EJB
(explanation here)javax.inject.Inject
(explanation here)javax.persistence.PersistenceContext
java.lang.Runnable
javax.swing.Action
java.util.Pattern
java.text.Normalizer
java.text.Format
javax.el.ELResolver
java.util.Iterator
(thus among others also java.util.Scanner
!).java.util.Enumeration
java.util.Timer
(all scheduleXXX()
methods)java.util.concurrent.Executor#execute()
java.util.concurrent.ExecutorService
(the invokeXXX()
and submit()
methods)java.util.concurrent.ScheduledExecutorService
(all scheduleXXX()
methods)java.lang.reflect.Method#invoke()
java.util.Date
(the setter methods do that, Date
is internally represented by a long
value)java.io.Serializable
javax.faces.component.StateHolder
java.util.Observer
/java.util.Observable
(rarely used in real world though)java.util.EventListener
(practically all over Swing thus)javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionAttributeListener
javax.faces.event.PhaseListener
javax.faces.lifecycle.LifeCycle#execute()
(controlled by FacesServlet
, the behaviour is dependent on current phase (state) of JSF lifecycle)java.util.Comparator#compare()
, executed by among others Collections#sort()
.javax.servlet.http.HttpServlet
, the service()
and all doXXX()
methods take HttpServletRequest
and HttpServletResponse
and the implementor has to process them (and not to get hold of them as instance variables!).javax.servlet.Filter#doFilter()
java.io.InputStream
, java.io.OutputStream
, java.io.Reader
and java.io.Writer
.java.util.AbstractList
, java.util.AbstractSet
and java.util.AbstractMap
.javax.servlet.http.HttpServlet
, all the doXXX()
methods by default sends a HTTP 405 "Method Not Allowed" error to the response. You're free to implement none or any of them.This solved my problem when I had to deal with HTML page with embedded JavaScript
WebElement empSalary = driver.findElement(By.xpath(PayComponentAmount));
Actions mouse2 = new Actions(driver);
mouse2.clickAndHold(empSalary).sendKeys(Keys.chord(Keys.CONTROL, "a"), "1234").build().perform();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].onchange()", empSalary);
I think this is a better approach. Simple and straight forward.
public function sizeFilter( $bytes )
{
$label = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
for( $i = 0; $bytes >= 1024 && $i < ( count( $label ) -1 ); $bytes /= 1024, $i++ );
return( round( $bytes, 2 ) . " " . $label[$i] );
}
Use dev.new()
. (See this related question.)
plot(1:10)
dev.new(width=5, height=4)
plot(1:20)
To be more specific which units are used:
dev.new(width=5, height=4, unit="in")
plot(1:20)
dev.new(width = 550, height = 330, unit = "px")
plot(1:15)
edit additional argument for Rstudio (May 2020), (thanks user Soren Havelund Welling)
For Rstudio, add dev.new(width=5,height=4,noRStudioGD = TRUE)
There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like:
sum( 2 %<% x %<% 5 )
sum( 2 %<=% x %<=% 5 )
which gives the same results as:
sum( 2 < x & x < 5 )
sum( 2 <= x & x <= 5 )
Which is better is probably more a matter of personal preference.
No; instances of class File
represent a path in a filesystem. Therefore, you can use that function only with a file. But perhaps there is an overload that takes an InputStream
instead?
This works for me:
First you need to create method, which will be returns your headers you want to add to request:
private Map<String, String> getCustomHeaders()
{
Map<String, String> headers = new HashMap<>();
headers.put("YOURHEADER", "VALUE");
return headers;
}
Second you need to create WebViewClient:
private WebViewClient getWebViewClient()
{
return new WebViewClient()
{
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
view.loadUrl(request.getUrl().toString(), getCustomHeaders());
return true;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url, getCustomHeaders());
return true;
}
};
}
Add WebViewClient to your WebView:
webView.setWebViewClient(getWebViewClient());
Hope this helps.
I had to run my commands in the one and same terminal, not seperately.
nohup sudo Xvfb :10 -ac
export DISPLAY=:10
java -jar vendor/se/selenium-server-standalone/bin/selenium-server-standalone.jar -Dwebdriver.chrome.bin="/usr/bin/google-chrome" -Dwebdriver.chrome.driver="vendor/bin/chromedriver"
It's VERY important to include:
SET NOCOUNT ON;
into SP, In First line,
if you do INSERT
in SP, the END SELECT
can't return values.
THEN, in vb60 you can:
SET RS = CN.EXECUTE(SQL)
OR:
RS.OPEN CN, RS, SQL
To add and simplify Günter Zöchbauer's the example incase using (if...else) to set something else than background image :
<p [ngStyle]="value == 10 && { 'font-weight': 'bold' }">
If you are not using SSMS then here is the syntax:
ALTER TABLE <table_name>
ADD <constraint_name> FOREIGN KEY
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)
Hint
DataTable table = new DataTable();
table.Columns.Add("Column#1", typeof(int));
table.Columns.Add("Column#2", typeof(string));
table.Rows.Add(5, "Cell1-1");
table.Rows.Add(130, "Cell2-2");
EDIT: Added more
string cellValue = table.Rows[0].GetCellValueByName<string>("Column#2");
public static class DataRowExtensions
{
public static T GetCellValueByName<T>(this DataRow row, string columnName)
{
int index = row.Table.Columns.IndexOf(columnName);
return (index < 0 || index > row.ItemArray.Count())
? default(T)
: (T) row[index];
}
}
Use str_pad function. It is very easy to use. One example is below:
<?php
$input = "Alien";
echo str_pad($input, 10); // produces "Alien "
?>
The syntax problem is shadowing method and variable names. In the current version sort_word_list()
is a method, and sorted_word_list
is a variable, whereas num_words
is both. Also, list.sort()
modifies the list and replaces it with a sorted version; the sorted(list)
function actually returns a new list.
But I suspect this indicates a design problem. What's the point of calls like
test.parser()
test.sort_word_list()
test.num_words()
which don't do anything? You should probably just have the methods figure out whether the appropriate counting and/or sorting has been done, and, if appropriate, do the count or sort and otherwise just return something.
E.G.,
def sort_word_list(self):
if self.sorted_word_list is not None:
self.sorted_word_list = sorted(self.word_list)
return self.sorted_word_list
(Alternately, you could use properties.)
In addition to what @ckal suggested, it is critical to give each renamed Configuration.cs its own namespace. If you do not, EF will attempt to apply migrations to the wrong context.
Here are the specific steps that work well for me.
If Migrations are messed up and you want to create a new "baseline":
Creating the initial migration:
In Package Manager Console:
Enable-Migrations -EnableAutomaticMigrations -ContextTypeName
NamespaceOfContext.ContextA -ProjectName ProjectContextIsInIfNotMainOne
-StartupProjectName NameOfMainProject -ConnectionStringName ContextA
In Solution Explorer: Rename Migrations.Configuration.cs to Migrations.ConfigurationA.cs. This should automatically rename the constructor if using Visual Studio. Make sure it does. Edit ConfigurationA.cs: Change the namespace to NamespaceOfContext.Migrations.MigrationsA
Enable-Migrations -EnableAutomaticMigrations -ContextTypeName
NamespaceOfContext.ContextB -ProjectName ProjectContextIsInIfNotMainOne
-StartupProjectName NameOfMainProject -ConnectionStringName ContextB
In Solution Explorer: Rename Migrations.Configuration.cs to Migrations.ConfigurationB.cs. Again, make sure the constructor is also renamed appropriately. Edit ConfigurationB.cs: Change the namespace to NamespaceOfContext.Migrations.MigrationsB
add-migration InitialBSchema -IgnoreChanges -ConfigurationTypeName
ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne
-StartupProjectName NameOfMainProject -ConnectionStringName ContextB
Update-Database -ConfigurationTypeName ConfigurationB -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextB
add-migration InitialSurveySchema -IgnoreChanges -ConfigurationTypeName
ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName
NameOfMainProject -ConnectionStringName ContextA
Update-Database -ConfigurationTypeName ConfigurationA -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextA
Steps to create migration scripts in Package Manager Console:
Run command
Add-Migration MYMIGRATION -ConfigurationTypeName ConfigurationA -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextA
or -
Add-Migration MYMIGRATION -ConfigurationTypeName ConfigurationB -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextB
It is OK to re-run this command until changes are applied to the DB.
Either run the scripts against the desired local database, or run Update-Database without -Script to apply locally:
Update-Database -ConfigurationTypeName ConfigurationA -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextA
or -
Update-Database -ConfigurationTypeName ConfigurationB -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextB
I use if (this.variable)
to test if it is defined. A simple if (variable)
, recommended in a previous answer, fails for me.
It turns out that it works only when a variable is a field of some object, obj.someField
to check if it is defined in the dictionary. But we can use this
or window
as the dictionary object since any variable is a field in the current window, as I understand it. Therefore here is a test:
if (this.abc)
alert("defined");
else
alert("undefined");
abc = "abc";
if (this.abc)
alert("defined");
else
alert("undefined");
_x000D_
It first detects that variable abc
is undefined and it is defined after initialization.
Let's say you have a Login
action which provides the user with a login screen, then receives the user name and password back after the user submits the form:
public ActionResult Login() {
return View();
}
public ActionResult Login(string userName, string password) {
// do login stuff
return View();
}
MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.
Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.
[HttpGet]
public ActionResult Login() {
return View();
}
[HttpPost]
public ActionResult Login(string userName, string password) {
// do login stuff
return View();
}
You can also combine the request method attributes if your action serves requests from multiple verbs:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
.
For a thread you have the myThread.IsAlive
property. It is false if the thread method returned or the thread was aborted.
There are two reasons to pass an argument by reference: (1) for performance (in which case you want to pass by const reference) and (2) because you need the ability to change the value of the argument inside the function.
I highly doubt that passing an unsigned long on modern architectures is slowing you down too much. So I'm assuming that you're intending to change the value of State
inside the method. The compiler is complaining because the constant 0
cannot be changed, as it's an rvalue ("non-lvalue" in the error message) and unchangeable (const
in the error message).
Simply put, you want a method that can change the argument passed, but by default you want to pass an argument that can't change.
To put it another way, non-const
references have to refer to actual variables. The default value in the function signature (0
) is not a real variable. You're running into the same problem as:
struct Foo {
virtual ULONG Write(ULONG& State, bool sequence = true);
};
Foo f;
ULONG s = 5;
f.Write(s); // perfectly OK, because s is a real variable
f.Write(0); // compiler error, 0 is not a real variable
// if the value of 0 were changed in the function,
// I would have no way to refer to the new value
If you don't actually intend to change State
inside the method you can simply change it to a const ULONG&
. But you're not going to get a big performance benefit from that, so I would recommend changing it to a non-reference ULONG
. I notice that you are already returning a ULONG
, and I have a sneaky suspicion that its value is the value of State
after any needed modifications. In which case I would simply declare the method as so:
// returns value of State
virtual ULONG Write(ULONG State = 0, bool sequence = true);
Of course, I'm not quite sure what you're writing or to where. But that's another question for another time.
using row major example:
A(i,j) = a[i + j*ld]; // where ld is the leading dimension
// (commonly same as array dimension in i)
// matrix like notation using preprocessor hack, allows to hide indexing
#define A(i,j) A[(i) + (j)*ld]
double *A = ...;
size_t ld = ...;
A(i,j) = ...;
... = A(j,i);
Number(new Date(2010, 6, 26))
Works the same way as things above. If you need seconds don't forget to / 1000
I'm using Visual Studio 2013 Professional with Update 4 but didn't find resolution with any of the other suggestions, however, I did manage to resolve the issue for my Team project.
Here's what I did to cause the problem -
Here's what I did to solve the problem -
If this is the case for you then just be extra sure that you're deleting the phantom file rather than the actual one you want to keep in the project.
The above one with JQuery is the easiest and mostly used way. However you can use pure javascript but try to define this script in the head so that it is read at the beginning. What you are looking for is window.onload
event.
Below is a simple script that I created to run a counter. The counter then stops after 10 iterations
window.onload=function()
{
var counter = 0;
var interval1 = setInterval(function()
{
document.getElementById("div1").textContent=counter;
counter++;
if(counter==10)
{
clearInterval(interval1);
}
},1000);
}
No you can't - IP addresses get reallocated and reassigned from time to time, so the mapping of IP to location will also change over time.
If you want to find out the location that an IP address currently maps to you can either download a geolocation database, such as GeoLite from MaxMind, or use an API like http://ipinfo.io (my own service) which will also give you additional details:
$ curl ipinfo.io/8.8.8.8
{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"loc": "37.385999999999996,-122.0838",
"org": "AS15169 Google Inc.",
"city": "Mountain View",
"region": "California",
"country": "US",
"phone": 650
}
Since other solutions are old and either poorly-working or not working at all, I've modified NestedScrollView
, which is stable, modern and it has all you expect from a scroll view. Except for horizontal scrolling.
Here's the repo: https://github.com/ultimate-deej/TwoWayNestedScrollView
I've made no changes, no "improvements" to the original NestedScrollView
expect for what was absolutely necessary.
The code is based on androidx.core:core:1.3.0
, which is the latest stable version at the time of writing.
All of the following works:
NestedScrollView
)Too hard? Your TA is... well, the phrase would probably get me banned. Anyways, check to see if numb
is negative. If it is then multiply numa
by -1
and do numb = abs(numb)
. Then do the loop.
The main mistake: You have "divitis" in the whole document.
Why this?
<header>
<div id="logo"></div>
<div id="language"></div>
</header>
Instead of:
<header role="banner">
<!-- Not the best -->
<h1 id="logo"></h1> <!-- or <figure> and <figcaption>, or <h1> and <p>... -->
<h2 id="language"></h2>
<!-- Better, if the IDs have not semantic sense -->
<h1></h1>
<h2></h2>
</header>
To stylize this header, use CSS hierarchy: body > section > header > h1, body > section > header > h2
More, ...line 63: why header wraps h2?? If you do not include any more element inside header, just use a single h2.
Keep in mind, your structure is not to stylize document, but construct a document self-explained.
Apply this to the rest of document; Good luck ;)
I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)
However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:
public class MainActivity extends Activity {
private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
final TextView textIp = (TextView) findViewById(R.id.Ip);
final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.BSSID = CHIPKIT_BSSID;
wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
myWifiManager.setWifiEnabled(true);
int netID = myWifiManager.addNetwork(wifiConfiguration);
myWifiManager.enableNetwork(netID, true);
textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n'
+ myWifiManager.getWifiState() + "\n\n");
btnDoSomething.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clearTextViews(textWifiManager, textIp);
}
});
btnNewScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getNewScan(myWifiManager, textWifiManager, textIp);
}
});
}
private void clearTextViews(TextView...tv) {
for(int i = 0; i<tv.length; i++){
tv[i].setText("");
}
}
public void getNewScan(WifiManager wm, TextView...textViews) {
wm.startScan();
List<ScanResult> scanResult = wm.getScanResults();
String scan = "";
for (int i = 0; i < scanResult.size(); i++) {
scan += (scanResult.get(i).toString() + "\n\n");
}
textViews[0].setText(scan);
textViews[1].setText(wm.toString());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...
and my manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Hope that helps!
I believe best practice these days is H/5 * * * *
, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.
void main()
{
int a,b,c,d,e,max;
max=a;
if(b/max)
max=b;
if(c/max)
max=c;
if(d/max)
max=d;
if(e/max)
max=e;
cout<<"Maximum is"<<max;
}
Apart from the accepted answer, other problems can cause the exception too. For me it was that the certificate was not trusted (i.e., self-signed cert and not in the trust store).
If the certificate file does not exists, or could not be loaded (e.g., typo in path) can---in certain circumstances---cause the same exception.
You can use a structure like the following:
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
Here are some more tests
True if string is not empty:
[ -n "$var" ]
[[ -n $var ]]
test -n "$var"
[ "$var" ]
[[ $var ]]
(( ${#var} ))
let ${#var}
test "$var"
True if string is empty:
[ -z "$var" ]
[[ -z $var ]]
test -z "$var"
! [ "$var" ]
! [[ $var ]]
! (( ${#var} ))
! let ${#var}
! test "$var"
IMHO, there is not much difference in case of web application if you look at it from the angle of responsibility assignment. However, keep the clarity in the layer. Keep anything purely for the presentation purpose in the presentation layer, like the control and code specific to the web controls. Just keep your entities in the business layer and all features (like add, edit, delete) etc in the business layer. However rendering them onto the browser to be handled in the presentation layer. For .Net, the ASP.NET MVC pattern is very good in terms of keeping the layers separated. Look into the MVC pattern.
Old question I know, but this is now possible using the css property table-layout: fixed
on the table tag. Answer below from this question CSS percentage width and text-overflow in a table cell
This is easily done by using table-layout: fixed
, but a little tricky because not many people know about this CSS property.
table {
width: 100%;
table-layout: fixed;
}
See it in action at the updated fiddle here: http://jsfiddle.net/Fm5bM/4/
I know this question has been answered. But my requirement was slightly different. Instead of value I wanted to filter by text. So i modified the answer by @William Herry like this.
var array = ['Administration', 'Finance', 'HR', 'IT', 'Marketing', 'Materials', 'Reception', 'Support'];
if (somecondition) {
$(array).each(function () {
$("div#deprtmnts option:contains(" + this + ")").unwrap();
});
}
else{
$(array).each(function () {
$("div#deprtmnts option:contains(" + this + ")").wrap('<span/>');
});
}
This way you can use value also by replacing contains like this
$("div#ovrcateg option[value=" + this + "]").wrap('<span/>');
SharpCompress is in my opinion one of the smartest compression libraries out there. It supports LZMA (7-zip), is easy to use and under active development.
As it has LZMA streaming support already, at the time of writing it unfortunately only supports 7-zip archive reading. BUT archive writing is on their todo list (see readme). For future readers: Check to get the current status here: https://github.com/adamhathcock/sharpcompress/blob/master/FORMATS.md
You cannot put tr inside td. You can see the allowed content from MDN web docs documentation about td
. The relevant information is in the permitted content section.
Another way to achieve this is by using colspan
and rowspan
. Check this fiddle.
HTML:
<table width="100%">
<tr>
<td>Name 1</td>
<td>Name 2</td>
<td colspan="2">Name 3</td>
<td>Name 4</td>
</tr>
<tr>
<td rowspan="3">ITEM 1</td>
<td rowspan="3">ITEM 2</td>
<td>name1</td>
<td>price1</td>
<td rowspan="3">ITEM 4</td>
</tr>
<tr>
<td>name2</td>
<td>price2</td>
</tr>
<tr>
<td>name3</td>
<td>price3/td>
</tr>
</table>
And some CSS:
table {
border-collapse: collapse
}
td {
border: 1px solid #000000
}
Am adding few things related to jenkins configuration files storage.
As per my understanding all config file stores in the machine or OS that you have installed jenkins.
The jobs you are going to create in jenkins will be stored in jenkins server and you can find the config.xml etc., here.
After jenkins installation you will find jenkins workspace in server.
*cd>jenkins/jobs/`
cd>jenkins/jobs/$ls
job1 job2 job3 config.xml ....*
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/baselineImage"
android:includeFontPadding="false" />
<ImageView
android:id="@+id/baselineImage"
android:layout_width="1dp"
android:layout_height="1dp"
android:baselineAlignBottom="true"
android:layout_alignParentBottom="true" />
<!-- This view will be exactly 10dp below the baseline of textView -->
<View
android:id="@+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="@+id/baselineImage" />
</RelativeLayout>
With an extra ImageView we can set the TextView to be baseline aligned with the ImageView and set the android:baselineAlignBottom
on the ImageView to true, which will make the baseline of ImageView to bottom. Other views can align itself using the bottom of the ImageView which itself is the same as the TextView's baseline.
This however only fixes the padding bottom not the top.
For this particular question, the standard suggestion of java.text.SimpleDateFormat
works, but has the unfortunate side effect that SimpleDateFormat
is not thread-safe and can be the source of particularly nasty problems since it'll corrupt your output in multi-threaded scenarios, and you won't get any exceptions!
I would strongly recommend looking at Joda for anything like this. Why ? It's a much richer and more intuitive time/date library for Java than the current library (and the basis of the up-and-coming new standard Java date/time library, so you'll be learning a soon-to-be-standard API).
You need to use df.shift
here.
df.shift(i)
shifts the entire dataframe by i
units down.
So, for i = 1
:
Input:
x1 x2
0 206 214
1 226 234
2 245 253
3 265 272
4 283 291
Output:
x1 x2
0 Nan Nan
1 206 214
2 226 234
3 245 253
4 265 272
So, run this script to get the expected output:
import pandas as pd
df = pd.DataFrame({'x1': ['206', '226', '245',' 265', '283'],
'x2': ['214', '234', '253', '272', '291']})
print(df)
df['x2'] = df['x2'].shift(1)
print(df)
I found this today. It really helped me. http://www.propra.nl/playground/css_filters/
All you need is to add this to your css style.:
div {-webkit-filter: brightness(57%)}
Use crosstab()
from the tablefunc module.
SELECT * FROM crosstab(
$$SELECT user_id, user_name, rn, email_address
FROM (
SELECT u.user_id, u.user_name, e.email_address
, row_number() OVER (PARTITION BY u.user_id
ORDER BY e.creation_date DESC NULLS LAST) AS rn
FROM usr u
LEFT JOIN email_tbl e USING (user_id)
) sub
WHERE rn < 4
ORDER BY user_id
$$
, 'VALUES (1),(2),(3)'
) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);
I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:
Detailed explanation and instructions here:
And in particular, for "extra columns":
The special difficulties here are:
The lack of key names.
-> We substitute with row_number()
in a subquery.
The varying number of emails.
-> We limit to a max. of three in the outer SELECT
and use crosstab()
with two parameters, providing a list of possible keys.
Pay attention to NULLS LAST
in the ORDER BY
.
This might work for you:
sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
For Kotlin:
Create two extensions, one for EditText and one for TextView
EditText:
fun EditText.clear() { text.clear() }
TextView:
fun TextView.clear() { text = "" }
and use it like
myEditText.clear()
myTextView.clear()
$product=Mage::getModel('catalog/product')->load($product_id);
above code not working for me. its throw exception;
This is working for me for get product details.
$obj = Mage::getModel('catalog/product');
$_product = $obj->load($product_id);
So use for for product type.
$productType = $_product->getTypeId();
As other answers mentioned, Docker's default local bridge
network only supports 30 different networks (each one of them uniquely identifiable by their name). If you are not using them, then docker network prune
will do the trick.
However, you might be interested in establishing more than 30 containers, each with their own network. Were you interested in doing so then you would need to define an overlay
network. This is a bit more tricky but extremely well documented here.
EDIT (May 2020): Link has become unavailable, going through the docs there's not an exact replacement, but I would recommend starting from here.
According to the site I'll post below, it's all how you set up your server. One example they show is this:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
and their route function:
function route(handle, pathname, response) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
This is one way. http://www.nodebeginner.org/
From another site, they create a page and then load it. This might be more of what you're looking for.
fs.readFile('www/404.html', function(error2, data) {
response.writeHead(404, {'content-type': 'text/html'});
response.end(data);
});
As of version 2.4, you can create a text index on the field(s) to search and use the $text operator for querying.
First, create the index:
db.users.createIndex( { "username": "text" } )
Then, to search:
db.users.find( { $text: { $search: "son" } } )
Benchmarks (~150K documents):
Notes:
db.collection.createIndex( { "$**": "text" } )
.For unit test:
spyOn(component.form, 'valid').and.returnValue(true);
Since Java 9, it is possible to use Map.of(...)
, like so:
Map<String, Integer> immutableMap = Map.of("One", 1,
"Two", 2,
"Three", 3);
This map is immutable. If you want the map to be mutable, you have to add:
Map<String, Integer> hashMap = new HashMap<>(immutableMap);
If you can't use Java 9, you're stuck with writing a similar helper method yourself or using a third-party library (like Guava) to add that functionality for you.
Aside from @see
, a more general way of refering to another class and possibly method of that class is {@link somepackage.SomeClass#someMethod(paramTypes)}
. This has the benefit of being usable in the middle of a javadoc description.
From the javadoc documentation (description of the @link tag):
This tag is very simliar to @see – both require the same references and accept exactly the same syntax for package.class#member and label. The main difference is that {@link} generates an in-line link rather than placing the link in the "See Also" section. Also, the {@link} tag begins and ends with curly braces to separate it from the rest of the in-line text.
All of the answers so far ignore a dangerous problem with ===. It has been noted in passing, but not stressed, that integer and double are different types, so the following code:
$n = 1000;
$d = $n + 0.0e0;
echo '<br/>'. ( ($n == $d)?'equal' :'not equal' );
echo '<br/>'. ( ($n === $d)?'equal' :'not equal' );
gives:
equal
not equal
Note that this is NOT a case of a "rounding error". The two numbers are exactly equal down to the last bit, but they have different types.
This is a nasty problem because a program using === can run happily for years if all of the numbers are small enough (where "small enough" depends on the hardware and OS you are running on). However, if by chance, an integer happens to be large enough to be converted to a double, its type is changed "forever" even though a subsequent operation, or many operations, might bring it back to a small integer in value. And, it gets worse. It can spread - double-ness infection can be passed along to anything it touches, one calculation at a time.
In the real world, this is likely to be a problem in programs that handle dates beyond the year 2038, for example. At this time, UNIX timestamps (number of seconds since 1970-01-01 00:00:00 UTC) will require more than 32-bits, so their representation will "magically" switch to double on some systems. Therefore, if you calculate the difference between two times you might end up with a couple of seconds, but as a double, rather than the integer result that occurs in the year 2017.
I think this is much worse than conversions between strings and numbers because it is subtle. I find it easy to keep track of what is a string and what is a number, but keeping track of the number of bits in a number is beyond me.
So, in the above answers there are some nice tables, but no distinction between 1 (as an integer) and 1 (subtle double) and 1.0 (obvious double). Also, advice that you should always use === and never == is not great because === will sometimes fail where == works properly. Also, JavaScript is not equivalent in this regard because it has only one number type (internally it may have different bit-wise representations, but it does not cause problems for ===).
My advice - use neither. You need to write your own comparison function to really fix this mess.
C# 7 adds support for local functions
Here is the previous example using a local function
void Method()
{
string localFunction(string source)
{
// add your functionality here
return source ;
};
// call the inline function
localFunction("prefix");
}
I needed the best x results of points per team.
Ranking does not solves this problem when there are results with equal points.
So I need a recordnumber
I made a VBA function in Access to create a recordnumber
that resets on ID change.
You have to query this query with where recordnumber <= x
to get the points per team.
NB Access changes the record-number
That is not what I thought that would happen.
Solved this by using a temporary table and saving the recordnumbers
and keys or an extra field in the table.
SELECT ID, Points, RecordNumberOffId([ID}) AS Recordnumber
FROM Team ORDER BY ID ASC, Points DESC;
It uses 3 module level variables to remember between calls
Dim PreviousID As Long
Dim PreviousRecordNumber As Long
Dim TimeLastID As Date
Public Function RecordNumberOffID(ID As Long) As Long
'ID is sortgroup identity
'Reset if last call longer dan nn seconds in the past
If Time() - TimeLastID > 0.0003 Then '0,000277778 = 1 second
PreviousID = 0
PreviousRecordNumber = 0
End If
If ID <> PreviousID Then
PreviousRecordNumber = 0
PreviousID = ID
End If
PreviousRecordNumber = PreviousRecordNumber + 1
RecordNumberOffID = PreviousRecordNumber
TimeLastID = Time()
End Function
HTML provide only input type="time"
If you are using bootstrap then you can use timepicker.
You can get code from this URL http://jdewit.github.io/bootstrap-timepicker
May be it will help you
It can also be done with isinstance
as per Alex Hall's answer :
>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True
isinstance
is also intuitive but there is the complication that it requires the line
NoneType = type(None)
which isn't needed for types like int
and float
.
I tried all of these solutions and none worked completely for me. This is what I came up with
$(document).ready(function () {
var clicknum = 0;
$('.dropdown').click(
function() {
clicknum++;
if (clicknum == 2) {
clicknum = 0;
$(this).css('position', '');
$(this).css('width', '');
}
}).blur(
function() {
$(this).css('position', '');
$(this).css('width', '');
clicknum = 0;
}).focus(
function() {
$(this).css('position', 'relative');
$(this).css('width', 'auto');
}).mousedown(
function() {
$(this).css('position', 'relative');
$(this).css('width', 'auto');
});
})(jQuery);
Be sure to add a dropdown class to each dropdown in your html
The trick here is using the specialized click function (I found it here Fire event each time a DropDownList item is selected with jQuery). Many of the other solutions on here use the event handler change, which works well but won't trigger if the user selects the same option as was previously selected.
Like many of the other solutions, focus and mousedown is for when the user puts the dropdown in focus, blur is for when they click away.
You may also want to stick some kind of browser detection in this so it only effects ie. It doesn't look bad in other browsers though
While installing Netbeans itself, you will get an option which servers needs to be installed and integrated with Netbeans. First screen itself will show.
Another option is to reinstall Netbeans by closing all the open projects.
Sometimes all the solutions with Workbooks.open is not working no matter how many parameters are set. For me, the fastest solution was to change the List separator in Region & language settings. Region window / Additional settings... / List separator.
If csv is not opening in proper way You probly have set ',' as a list separator. Just change it to ';' and everything is solved. Just the easiest way when "everything is against You" :P
Try this .{3,} this will match any characher except new line (\n)
that’s just wrong: is not a wrapper. The element denotes a semantic section of your content to help construct a document outline. It should contain a heading. If you’re looking for a page wrapper element (for any flavour of HTML or XHTML), consider applying styles directly to the element as described by Kroc Camen. If you still need an additional element for styling, use a . As Dr Mike explains, div isn’t dead, and if there’s nothing else more appropriate, it’s probably where you really want to apply your CSS.
you can check this : http://html5doctor.com/avoiding-common-html5-mistakes/
You are looking for serialize(). Here is an example:
$array = array('foo', 'bar');
//Array to String
$string = serialize($array);
//String to array
$array = unserialize($string);
try using:
RAISERROR('your message here!!!',0,1) WITH NOWAIT
you could also try switching to "Results to Text" it is just a few icons to the right of "Execute" on the default tool bar.
With both of the above in place, and you still you do not see the messages, make sure you are running the same server/database/owner version of the procedure that you are editing. Make sure you are hitting the RAISERROR command, make it the first command inside the procedure.
If all else fails, you could create a table:
create table temp_log (RowID int identity(1,1) primary key not null
, MessageValue varchar(255))
then:
INSERT INTO temp_log VALUES ('Your message here')
then after running the procedure (provided no rollbacks) just select
the table.
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
(Update) V5.1 & Hooks (Requires React >= 16.8)
You can use useHistory
, useLocation
and useRouteMatch
in your component to get match
, history
and location
.
const Child = () => {
const location = useLocation();
const history = useHistory();
const match = useRouteMatch("write-the-url-you-want-to-match-here");
return (
<div>{location.pathname}</div>
)
}
export default Child
(Update) V4 & V5
You can use withRouter
HOC in order to inject match
, history
and location
in your component props.
class Child extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
(Update) V3
You can use withRouter
HOC in order to inject router
, params
, location
, routes
in your component props.
class Child extends React.Component {
render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
Original answer
If you don't want to use the props, you can use the context as described in React Router documentation
First, you have to set up your childContextTypes
and getChildContext
class App extends React.Component{
getChildContext() {
return {
location: this.props.location
}
}
render() {
return <Child/>;
}
}
App.childContextTypes = {
location: React.PropTypes.object
}
Then, you will be able to access to the location object in your child components using the context like this
class Child extends React.Component{
render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}
The easiest way to do this is:
You can use private as well and you can call private methods with reflection. If you're using Visual Studio Team Suite it has some nice functionality that will generate a proxy to call your private methods for you. Here's a code project article that demonstrates how you can do the work yourself to unit test private and protected methods:
http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx
In terms of which access modifier you should use, my general rule of thumb is start with private and escalate as needed. That way you will expose as little of the internal details of your class as are truly needed and it helps keep the implementation details hidden, as they should be.
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
You may also need to specify the proxy server/port, in some environments the system settings for proxy are not enough for npm to work.
npm config set proxy "http://your-proxy.com:80"