I would prefer to have the framework do the logging for you by hooking in a logging stream which logs as the framework processes that underlying stream. The following isn't as clean as I would like it, since you can't decide between request and response in the ChainStream method. The following is how I handle it. With thanks to Jon Hanna for the overriding a stream idea
public class LoggerSoapExtension : SoapExtension
{
private static readonly string LOG_DIRECTORY = ConfigurationManager.AppSettings["LOG_DIRECTORY"];
private LogStream _logger;
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override object GetInitializer(Type serviceType)
{
return null;
}
public override void Initialize(object initializer)
{
}
public override System.IO.Stream ChainStream(System.IO.Stream stream)
{
_logger = new LogStream(stream);
return _logger;
}
public override void ProcessMessage(SoapMessage message)
{
if (LOG_DIRECTORY != null)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
_logger.Type = "request";
break;
case SoapMessageStage.AfterSerialize:
break;
case SoapMessageStage.BeforeDeserialize:
_logger.Type = "response";
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
}
internal class LogStream : Stream
{
private Stream _source;
private Stream _log;
private bool _logSetup;
private string _type;
public LogStream(Stream source)
{
_source = source;
}
internal string Type
{
set { _type = value; }
}
private Stream Logger
{
get
{
if (!_logSetup)
{
if (LOG_DIRECTORY != null)
{
try
{
DateTime now = DateTime.Now;
string folder = LOG_DIRECTORY + now.ToString("yyyyMMdd");
string subfolder = folder + "\\" + now.ToString("HH");
string client = System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request != null && System.Web.HttpContext.Current.Request.UserHostAddress != null ? System.Web.HttpContext.Current.Request.UserHostAddress : string.Empty;
string ticks = now.ToString("yyyyMMdd'T'HHmmss.fffffff");
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
if (!Directory.Exists(subfolder))
Directory.CreateDirectory(subfolder);
_log = new FileStream(new System.Text.StringBuilder(subfolder).Append('\\').Append(client).Append('_').Append(ticks).Append('_').Append(_type).Append(".xml").ToString(), FileMode.Create);
}
catch
{
_log = null;
}
}
_logSetup = true;
}
return _log;
}
}
public override bool CanRead
{
get
{
return _source.CanRead;
}
}
public override bool CanSeek
{
get
{
return _source.CanSeek;
}
}
public override bool CanWrite
{
get
{
return _source.CanWrite;
}
}
public override long Length
{
get
{
return _source.Length;
}
}
public override long Position
{
get
{
return _source.Position;
}
set
{
_source.Position = value;
}
}
public override void Flush()
{
_source.Flush();
if (Logger != null)
Logger.Flush();
}
public override long Seek(long offset, SeekOrigin origin)
{
return _source.Seek(offset, origin);
}
public override void SetLength(long value)
{
_source.SetLength(value);
}
public override int Read(byte[] buffer, int offset, int count)
{
count = _source.Read(buffer, offset, count);
if (Logger != null)
Logger.Write(buffer, offset, count);
return count;
}
public override void Write(byte[] buffer, int offset, int count)
{
_source.Write(buffer, offset, count);
if (Logger != null)
Logger.Write(buffer, offset, count);
}
public override int ReadByte()
{
int ret = _source.ReadByte();
if (ret != -1 && Logger != null)
Logger.WriteByte((byte)ret);
return ret;
}
public override void Close()
{
_source.Close();
if (Logger != null)
Logger.Close();
base.Close();
}
public override int ReadTimeout
{
get { return _source.ReadTimeout; }
set { _source.ReadTimeout = value; }
}
public override int WriteTimeout
{
get { return _source.WriteTimeout; }
set { _source.WriteTimeout = value; }
}
}
}
[AttributeUsage(AttributeTargets.Method)]
public class LoggerSoapExtensionAttribute : SoapExtensionAttribute
{
private int priority = 1;
public override int Priority
{
get
{
return priority;
}
set
{
priority = value;
}
}
public override System.Type ExtensionType
{
get
{
return typeof(LoggerSoapExtension);
}
}
}
Use crontab to add job
0 0 9 ? * MON,WED,FRI *
The above expression will run the job at 9 am on every mon, wed and friday. You can validate this in : http://www.cronmaker.com/
List<String> stringList = getMyListOfStrings();
StringJoiner sj = new StringJoiner(" ");
stringList.stream().forEach(e -> sj.add(e));
String spaceSeparated = sj.toString()
You pass to the new StringJoiner
the char sequence you want to be used as separator. If you want to do a CSV: new StringJoiner(", ");
Another much simpler possibility is that one of your property names is wrong (probably one you just changed in the class). This is what it was for me in RazorPages .NET Core 3.
Try ps -ef
. man ps
will give you all the options.
-A Display information about other users' processes, including those without controlling terminals.
-e Identical to -A.
-f Display the uid, pid, parent pid, recent CPU usage, process start time, controlling tty, elapsed CPU usage, and the associated command. If the -u option is also used, display
the user name rather then the numeric uid. When -o or -O is used to add to the display following -f, the command field is not truncated as severely as it is in other formats.
I am using React Bootstrap, which is based on Bootstrap 4. The approach is to use Sass, simliar to Nelson Rothermel's answer above.
The idea is to override Bootstraps Sass variable for font family in your custom Sass file. If you are using Google Fonts, then make sure you import it at the top of your custom Sass file.
For example, my custom Sass file is called custom.sass
with the following content:
@import url('https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap');
$font-family-sans-serif: "Dancing Script", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji" !default;
I simply added the font I want to the front of the default values, which can be found in ..\node_modules\boostrap\dist\scss\_variables.scss
.
How the custom.scss
file is used is shown here, which is obtained from here, which is obtained from here...
Because the React app is created by the Create-React-App utility, there's no need to go through all the crufts like Gulp; I just saved the files and React will compile the Sass for me automagically behind the scene.
First and foremost, you should consider calling MimeTypeMap#getMimeTypeFromExtension()
, like this:
// url = file path or whatever suitable URL you want.
public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
Use this one, I've written this to my app,
<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#882C383E"/>
<corners
android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
</shape>
Microsoft has an article about this issue. It goes through it all step by step.
In short it involves starting up the instance of sqlserver with -m
like all the other answers suggest. However Microsoft provides slightly more detailed instructions.
From the Start page, start SQL Server Management Studio. On the View menu, select Registered Servers. (If your server is not already registered, right-click Local Server Groups, point to Tasks, and then click Register Local Servers.)
In the Registered Servers area, right-click your server, and then click SQL Server Configuration Manager. This should ask for permission to run as administrator, and then open the Configuration Manager program.
Close Management Studio.
In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, find your instance of SQL Server. (The default instance of SQL Server includes (MSSQLSERVER) after the computer name. Named instances appear in upper case with the same name that they have in Registered Servers.) Right-click the instance of SQL Server, and then click Properties.
On the Startup Parameters tab, in the Specify a startup parameter box, type -m and then click Add. (That's a dash then lower case letter m.)
Note
For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Be careful not to change any of the existing parameters. At the very end, add a new parameter ;-m and then click OK. (That's a semi-colon then a dash then lower case letter m.)
Click OK, and after the message to restart, right-click your server name, and then click Restart.
After SQL Server has restarted your server will be in single-user mode. Make sure that that SQL Server Agent is not running. If started, it will take your only connection.
On the Windows 8 start screen, right-click the icon for Management Studio. At the bottom of the screen, select Run as administrator. (This will pass your administrator credentials to SSMS.)
Note
For earlier versions of Windows, the Run as administrator option appears as a sub-menu.
In some configurations, SSMS will attempt to make several connections. Multiple connections will fail because SQL Server is in single-user mode. You can select one of the following actions to perform. Do one of the following.
a) Connect with Object Explorer using Windows Authentication (which includes your Administrator credentials). Expand Security, expand Logins, and double-click your own login. On the Server Roles page, select sysadmin, and then click OK.
b) Instead of connecting with Object Explorer, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). (You can only connect this way if you did not connect with Object Explorer.) Execute code such as the following to add a new Windows Authentication login that is a member of the sysadmin fixed server role. The following example adds a domain user named CONTOSO\PatK.
CREATE LOGIN [CONTOSO\PatK] FROM WINDOWS; ALTER SERVER ROLE sysadmin ADD MEMBER [CONTOSO\PatK];
c) If your SQL Server is running in mixed authentication mode, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Execute code such as the following to create a new SQL Server Authentication login that is a member of the sysadmin fixed server role.
CREATE LOGIN TempLogin WITH PASSWORD = '************'; ALTER SERVER ROLE sysadmin ADD MEMBER TempLogin;
Warning:
Replace ************ with a strong password.
d) If your SQL Server is running in mixed authentication mode and you want to reset the password of the sa account, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Change the password of the sa account with the following syntax.
ALTER LOGIN sa WITH PASSWORD = '************'; Warning
Replace ************ with a strong password.
The following steps now change SQL Server back to multi-user mode. Close SSMS.
In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, right-click the instance of SQL Server, and then click Properties.
On the Startup Parameters tab, in the Existing parameters box, select -m and then click Remove.
Note
For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Remove the ;-m which you added earlier, and then click OK.
Right-click your server name, and then click Restart.
Now you should be able to connect normally with one of the accounts which is now a member of the sysadmin fixed server role.
You could do this:
echo "<script>alert('Successfully Updated'); window.location = './edit.php';</script>";
Be careful, the solution proposed with $a = array_combine($a, $a);
will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384)
to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}
Here I am checking session values(two values filled in text box on previous page)
protected void Page_Load(object sender, EventArgs e)
{
if (Session["sessUnit_code"] == null || Session["sessgrcSerial"] == null)
{
Response.Write("<Script Language = 'JavaScript'> alert('Go to GRC Tab and fill Unit Code and GRC Serial number first')</script>");
}
else
{
lblUnit.Text = Session["sessUnit_code"].ToString();
LblGrcSr.Text = Session["sessgrcSerial"].ToString();
}
}
You can prevent tables from expanding beyond their parent div by using table-layout:fixed
.
The CSS below will make your tables expand to the width of the div surrounding it.
table
{
table-layout:fixed;
width:100%;
}
I found this trick here.
extrac Guid values from database functions:
#region GUID
public static Guid GGuid(SqlDataReader reader, string field)
{
try
{
return reader[field] == DBNull.Value ? Guid.Empty : (Guid)reader[field];
}
catch { return Guid.Empty; }
}
public static Guid GGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
return reader[ordinal] == DBNull.Value ? Guid.Empty : (Guid)reader[ordinal];
}
catch { return Guid.Empty; }
}
public static Guid? NGuid(SqlDataReader reader, string field)
{
try
{
if (reader[field] == DBNull.Value) return (Guid?)null; else return (Guid)reader[field];
}
catch { return (Guid?)null; }
}
public static Guid? NGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
if (reader[ordinal] == DBNull.Value) return (Guid?)null; else return (Guid)reader[ordinal];
}
catch { return (Guid?)null; }
}
#endregion
If you know max index accessing the max value is immediate. So all you need is max index.
int max=0;
for(int i = 1; i < arr.Length; i++)
if (arr[i] > arr[max]) max = i;
For the disabled buttons you can use the :disabled
pseudo-element. It works for all the elements.
For browsers/devices supporting CSS2 only, you can use the [disabled]
selector.
As with the image, don't put an image in the button. Use CSS background-image
with background-position
and background-repeat
. That way, the image dragging will not occur.
Selection problem: here is a link to the specific question:
Example for the disabled selector:
button {_x000D_
border: 1px solid #0066cc;_x000D_
background-color: #0099cc;_x000D_
color: #ffffff;_x000D_
padding: 5px 10px;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
border: 1px solid #0099cc;_x000D_
background-color: #00aacc;_x000D_
color: #ffffff;_x000D_
padding: 5px 10px;_x000D_
}_x000D_
_x000D_
button:disabled,_x000D_
button[disabled]{_x000D_
border: 1px solid #999999;_x000D_
background-color: #cccccc;_x000D_
color: #666666;_x000D_
}_x000D_
_x000D_
div {_x000D_
padding: 5px 10px;_x000D_
}
_x000D_
<div>_x000D_
<button> This is a working button </button>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<button disabled> This is a disabled button </button>_x000D_
</div>
_x000D_
I think the most natural way for achieving this is to define a function.
def read(filename):
f = open(filename, 'r')
output = f.read()
f.close()
return output
Then you can do the following:
output = read('pagehead.section.htm')
You can use round function. Here some example
numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53, 8.13, 3.97, 10.08])
IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.
>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']
Use DateTime::createFromFormat
$date = date_create_from_format('d/m/Y:H:i:s', $s);
$date->getTimestamp();
Ok, this is actually four different question. I'll address them one by one:
are both equals for the compiler? (speed, perf...)
Yes. The pointer dereferenciation and decay from type int (*)[100][280]
to int (*)[280]
is always a noop to your CPU. I wouldn't put it past a bad compiler to generate bogus code anyways, but a good optimizing compiler should compile both examples to the exact same code.
is one of these solutions eating more memory than the other?
As a corollary to my first answer, no.
what is the more frequently used by developers?
Definitely the variant without the extra (*pointer)
dereferenciation. For C programmers it is second nature to assume that any pointer may actually be a pointer to the first element of an array.
what is the best way, the 1st or the 2nd?
That depends on what you optimize for:
Idiomatic code uses variant 1. The declaration is missing the outer dimension, but all uses are exactly as a C programmer expects them to be.
If you want to make it explicit that you are pointing to an array, you can use variant 2. However, many seasoned C programmers will think that there's a third dimension hidden behind the innermost *
. Having no array dimension there will feel weird to most programmers.
I think best option is like same:
foreach ($lists as $key=>$value) {
echo $key+1;
}
it is easy and normally
Instead of setBackgroundColor
, retrieve the background drawable and set its color:
v.setBackgroundResource(R.drawable.tags_rounded_corners);
GradientDrawable drawable = (GradientDrawable) v.getBackground();
if (i % 2 == 0) {
drawable.setColor(Color.RED);
} else {
drawable.setColor(Color.BLUE);
}
Also, you can define the padding within your tags_rounded_corners.xml
:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="4dp" />
<padding
android:top="2dp"
android:left="2dp"
android:bottom="2dp"
android:right="2dp" />
</shape>
Using Studio 3T for MongoDB, if I use .find({}, { _id: 0, roll: true })
it still return an array of objects with an empty _id
property.
Using JavaScript map
helped me to only retrieve the desired roll
property as an array of string:
var rolls = db.student
.find({ roll: { $gt: 70 } }) // query where role > 70
.map(x => x.roll); // return an array of role
Not possible, I believe ie has a content changed event but it is certainly not x-browser
Should I say not possible without some nasty interval chugging away in the background!
If your query is something like this SELECT Count(*) FROM tranbook
, then do this rs.next(); System.out.println(rs.getInt("Count(*)"));
The var
keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var
keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var
keyword has a type. For instance, you'll find that the following code outputs "String".
var myString = "";
Console.Write(myString.GetType().Name);
Furthermore, the code above is equivalent to:
String myString = "";
Console.Write(myString.GetType().Name);
The var
keyword is simply C#'s way of saying "I can figure out the type for myString
from the context, so don't worry about specifying the type."
var myVariable = (MyType)null
or MyType myVariable = null
should work because you are giving the C# compiler context to figure out what type myVariable
should will be.
For more information:
I'm not aware of any way to do it using the standard library. But I do know and use this class that deals with html entities.
"HTMLEntities is an Open Source Java class that contains a collection of static methods (htmlentities, unhtmlentities, ...) to convert special and extended characters into HTML entitities and vice versa."
http://www.tecnick.com/public/code/cp_dpage.php?aiocp_dp=htmlentities
As Craig said, no.
But, regarding your comment as to why:
It might be easier to use 1 <form>
with the inputs and the "Update" button, and use copy hidden inputs with the "Submit Order" button in a another <form>
.
Use the native element.submit()
to circumvent the preventDefault in the jQuery handler, and note that your return statement only returns from the each loop, it does not return from the event handler
$('form').submit(function(e){
e.preventDefault();
var valid = true;
$('[name="atendeename[]"]', this).each(function(index, el){
if ( $(el).val() ) {
var entree = $(el).next('input');
if ( ! entree.val()) {
entree.focus();
valid = false;
}
}
});
if (valid) this.submit();
});
Maybe VT-X is not enabled in your BIOS.
See Intel HAXM documentation here: http://software.intel.com/en-us/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows
Intel VT-x not enabled
In some cases, Intel VT-x may be disabled in the system BIOS and must be enabled within the BIOS setup utility. To access the BIOS setup utility, a key must be pressed during the computer’s boot sequence. This key is dependent on which BIOS is used but it is typically the F2, Delete, or Esc key. Within the BIOS setup utility, Intel VT may be identified by the terms "VT", "Virtualization Technology", or "VT-d." Make sure to enable all of the Virtualization features.
FOR MAC USERS if you are working with open cv
import cv2
cv2.imwrite('path_to_folder/image.jpg',image)
PROBLEM: tag a file, at the top of the file, with the base name of the parent directory.
I.e., for
/mnt/Vancouver/Programming/file1
tag the top of file1
with Programming
.
SOLUTION 1 -- non-empty files:
bn=${PWD##*/} ## bn: basename
sed -i '1s/^/'"$bn"'\n/' <file>
1s
places the text at line 1 of the file.
SOLUTION 2 -- empty or non-empty files:
The sed
command, above, fails on empty files. Here is a solution, based on https://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in-bash/246841#246841
printf "${PWD##*/}\n" | cat - <file> > temp && mv -f temp <file>
Note that the -
in the cat command is required (reads standard input: see man cat
for more information). Here, I believe, it's needed to take the output of the printf statement (to STDIN), and cat that and the file to temp ... See also the explanation at the bottom of http://www.linfo.org/cat.html.
I also added -f
to the mv
command, to avoid being asked for confirmations when overwriting files.
To recurse over a directory:
for file in *; do printf "${PWD##*/}\n" | cat - $file > temp && mv -f temp $file; done
Note also that this will break over paths with spaces; there are solutions, elsewhere (e.g. file globbing, or find . -type f ...
-type solutions) for those.
ADDENDUM: Re: my last comment, this script will allow you to recurse over directories with spaces in the paths:
#!/bin/bash
## https://stackoverflow.com/questions/4638874/how-to-loop-through-a-directory-recursively-to-delete-files-with-certain-extensi
## To allow spaces in filenames,
## at the top of the script include: IFS=$'\n'; set -f
## at the end of the script include: unset IFS; set +f
IFS=$'\n'; set -f
# ----------------------------------------------------------------------------
# SET PATHS:
IN="/mnt/Vancouver/Programming/data/claws-test/corpus test/"
# https://superuser.com/questions/716001/how-can-i-get-files-with-numeric-names-using-ls-command
# FILES=$(find $IN -type f -regex ".*/[0-9]*") ## recursive; numeric filenames only
FILES=$(find $IN -type f -regex ".*/[0-9 ]*") ## recursive; numeric filenames only (may include spaces)
# echo '$FILES:' ## single-quoted, (literally) prints: $FILES:
# echo "$FILES" ## double-quoted, prints path/, filename (one per line)
# ----------------------------------------------------------------------------
# MAIN LOOP:
for f in $FILES
do
# Tag top of file with basename of current dir:
printf "[top] Tag: ${PWD##*/}\n\n" | cat - $f > temp && mv -f temp $f
# Tag bottom of file with basename of current dir:
printf "\n[bottom] Tag: ${PWD##*/}\n" >> $f
done
unset IFS; set +f
Alright so after trying every solution out there to solve this exact issues on a wordpress blog, I might have done something either really stupid or genius... With no idea why there's an increase in Mysql connections, I used the php script below in my header to kill all sleeping processes..
So every visitor to my site helps in killing the sleeping processes..
<?php
$result = mysql_query("SHOW processlist");
while ($myrow = mysql_fetch_assoc($result)) {
if ($myrow['Command'] == "Sleep") {
mysql_query("KILL {$myrow['Id']}");}
}
?>
Using custom exception class you can return different HTTP status code and dto object.
@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
if(userDto.getId() != null) {
throw new UserNotFoundException("A new user cannot already have an ID");
}
return ResponseEntity.ok(userService.saveUser(userDto));
}
Exception class
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user not found")
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
type Services
at search, then start Services
then start all VM services
A note for anyone looking to do this but also have the column headers, this is the solution that I used an a batch file:
sqlcmd -S servername -U username -P password -d database -Q "set nocount on; set ansi_warnings off; sql query here;" -o output.tmp -s "," -W
type output.tmp | findstr /V \-\,\- > output.csv
del output.tmp
This outputs the initial results (including the ----,---- separators between the headers and data) into a temp file, then removes that line by filtering it out through findstr. Note that it's not perfect since it's filtering out -,-
—it won't work if there's only one column in the output, and it will also filter out legitimate lines that contain that string.
Try this, pick or create one column and make that value required so that it's always populated such as title. A field that doesn't hold the name of the folder. Then in your filter put the filter you wanted that will select only the files you want. Then add an or to your filter, select your "required" field then set it equal to and leave the filter blank. Since all folders will have a blank in this required field your folders will show up with your files.
You're probably after Set wbOOR = ThisWorkbook
Just to clarify
ThisWorkbook
will always refer to the workbook the code resides in
ActiveWorkbook
will refer to the workbook that is active
Be careful how you use this when dealing with multiple workbooks. It really depends on what you want to achieve as to which is the best option.
Removing and adding DOM element is slower than modification of existing one.
If your option sets have same length, you may do something like this:
$('#my-select option')
.each(function(index) {
$(this).text('someNewText').val('someNewValue');
});
In case your new option set has different length, you may delete/add empty options you really need, using some technique described above.
var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
alert("yes, i have that property");
}
Or
var myProp = 'prop';
if(myProp in myObj){
alert("yes, i have that property");
}
Or
if('prop' in myObj){
alert("yes, i have that property");
}
Note that hasOwnProperty
doesn't check for inherited properties, whereas in
does. For example 'constructor' in myObj
is true, but myObj.hasOwnProperty('constructor')
is not.
Assuming such a query would return a single row, you could use either
select @EmpId = Id from dbo.Employee
Or
set @EmpId = (select Id from dbo.Employee)
You can divide seconds by 60 to get the minutes
import time
seconds = time.time()
minutes = seconds / 60
print(minutes)
When you divide it by 60 again, you will get the hours
Depending on how you render your view, you may also need:
@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}
I had to COPY
and untar java package in my docker image.
When I compared the docker image size created using ADD it was 180MB bigger than the one created using COPY, tar -xzf *.tar.gz and rm *.tar.gz
This means that although ADD removes the tar file, it is still kept somewhere. And its making the image bigger!!
NL derived from EBCDIC NL = x'15' which would logically compare to CRLF x'odoa ascii... this becomes evident when physcally moving data from mainframes to midrange. Coloquially (as only arcane folks use ebcdic) NL has been equated with either CR or LF or CRLF
When you add a string, do it differently depending on whether the key exists already or not. To add the string value
for the key key
:
List<string> list;
if (dictionary.ContainsKey(key)) {
list = dictionary[key];
} else {
list = new List<string>();
dictionary.Add(ley, list);
}
list.Add(value);
#This valid till 4 digit number
numbers={1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine',
10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen',
17:'seventeen', 18:'eighteen', 19:'nineteen', 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty',
60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety', 100:'hundred', 1000:'thousand'}
def my_fun(num):
list = []
num_len = len(str(num)) - 1
while num_len > 0 and num > 0:
while num_len > 0 and num > 0:
if num in numbers and num < 1000:
list.append(numbers[num])
num_len = 0
elif num < 100:
list.extend([numbers[num - num%10], numbers[num%10]])
num_len = 0
else:
quotent = num//10**num_len # 4567//1000= 4
num = num % 10**num_len #4567%1000 =567
if quotent != 0 :
list.append(numbers[quotent])
list.append(numbers[10**num_len])
else:
list.append(numbers[num])
num_len -= 1
return ' '.join(list)
What is the difference between creating cookies on the server and on the client?
What you are referring to are the 2 ways in which cookies can be directed to be set on the client, which are:
By server:
The Set-cookie
response header from the server directs the client to set a cookie on that particular domain. The implementation to actually create and store the cookie lies in the browser. For subsequent requests to the same domain, the browser automatically sets the Cookie
request header for each request, thereby letting the server have some state to an otherwise stateless HTTP protocol. The Domain
and Path
cookie attributes are used by the browser to determine which cookies are to be sent to a server.
The server only receives name=value
pairs, and nothing more.
By Client:
One can create a cookie on the browser using document.cookie = cookiename=cookievalue
. However, if the server does not intend to respond to any random cookie a user creates, then such a cookie serves no purpose.
Are these called server side cookies and client side cookies?
Cookies always belong to the client. There is no such thing as server side cookie.
Is there a way to create cookies that can only be read on the server or on the client?
Since reading cookie values are upto the server and client, it depends if either one needs to read the cookie at all.
On the client side, by setting the HttpOnly
attribute of the cookie, it is possible to prevent scripts ( mostly Javscript ) from reading your cookies , thereby acting as a defence mechanism against Cookie theft through XSS, but sends the cookie to the intended server only.
Therefore, in most of the cases since cookies are used to bring 'state' ( memory of past user events ), creating cookies on client side does not add much value, unless one is aware of the cookies the server uses / responds to.
References: Wikipedia
I used the defaultValue parameter, below is the code how I achieved a default value as well as update the default value when an option is selected from the drop-down.
<Select
name="form-dept-select"
options={depts}
defaultValue={{ label: "Select Dept", value: 0 }}
onChange={e => {
this.setState({
department: e.label,
deptId: e.value
});
}}
/>
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
For me the C:\Program Files (x86)\Notepad++\plugins
does not work.
I have to put plugins into the following directory: C:\Users\<username>\AppData\Local\Notepad++\plugins
UPDATE
There is a feature from NPP-v7.6.4 to open plugin folder:
Plugins -> Open Plugins Folder...
use [value]="1" instead of value="1"
<input name="options" ng-control="options" type="radio" [value]="1" [(ngModel)]="model.options" ><br/>
<input name="options" ng-control="options" type="radio" [value]="2" [(ngModel)]="model.options" ><br/>
Edit:
As suggested by thllbrg "For angular 2.1+ use [(ngModel)]
instead of [(ng-model)]
"
There are two times when you can update a record through a view:
Generally, you should not rely on being able to perform an insert to a view unless you have specifically written an INSTEAD OF trigger for it. Be aware, there are also INSTEAD OF UPDATE triggers that can be written as well to help perform updates.
this will been called before he start loading the page
(and get the same parameters as onFinished()
)
@Override
public void onPageCommitVisible(WebView view, String url) {
super.onPageCommitVisible(view, url);
}
A node is the base class for both elements and attributes (and basically all other XML representations too).
Uri myUri = Uri.parse("http://www.google.com");
Here's the doc http://developer.android.com/reference/android/net/Uri.html#parse%28java.lang.String%29
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the activity. After researching the problem on Stack Overflow, I adopted the following solution:
volatile boolean running;
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
running=true;
...
}
public void onDestroy() {
super.onDestroy();
running=false;
...
}
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.
This answer is for comparing two solutions, not a suggested solution.
Instead of creating another list as other answers suggested, you can used a for
loop using the dictionary Count
for the loop stop condition and Keys.ElementAt(i)
to get the key.
for (int i = 0; i < dictionary.Count; i++)
{
dictionary[dictionary.Keys.ElementAt(i)] = 0;
}
At firs I thought this would be more efficient because we do not need to create a key list. After running a test I found that the for
loop solution is much less efficient. The reason is because ElementAt
is O(n) on the dictionary.Keys
property, it searches from the beginning of the collection until it gets to the nth item.
Test:
int iterations = 10;
int dictionarySize = 10000;
Stopwatch sw = new Stopwatch();
Console.WriteLine("Creating dictionary...");
Dictionary<string, int> dictionary = new Dictionary<string, int>(dictionarySize);
for (int i = 0; i < dictionarySize; i++)
{
dictionary.Add(i.ToString(), i);
}
Console.WriteLine("Done");
Console.WriteLine("Starting tests...");
// for loop test
sw.Restart();
for (int i = 0; i < iterations; i++)
{
for (int j = 0; j < dictionary.Count; j++)
{
dictionary[dictionary.Keys.ElementAt(j)] = 3;
}
}
sw.Stop();
Console.WriteLine($"for loop Test: {sw.ElapsedMilliseconds} ms");
// foreach loop test
sw.Restart();
for (int i = 0; i < iterations; i++)
{
foreach (string key in dictionary.Keys.ToList())
{
dictionary[key] = 3;
}
}
sw.Stop();
Console.WriteLine($"foreach loop Test: {sw.ElapsedMilliseconds} ms");
Console.WriteLine("Done");
Results:
Creating dictionary...
Done
Starting tests...
for loop Test: 2367 ms
foreach loop Test: 3 ms
Done
Global title: In newer releases of matplotlib one can use Figure.suptitle() method of Figure
:
import matplotlib.pyplot as plt
fig = plt.gcf()
fig.suptitle("Title centered above all subplots", fontsize=14)
Alternatively (based on @Steven C. Howell's comment below (thank you!)), use the matplotlib.pyplot.suptitle() function:
import matplotlib.pyplot as plt
# plot stuff
# ...
plt.suptitle("Title centered above all subplots", fontsize=14)
Please make sure you have typed correct spelling of using script section in view
the correct is
@section scripts{ //your script here}
if you typed @section script{ //your script here}
this is wrong.
Let's start from keeping in mind that data is stored as bytes; Unicode is a character set where characters are mapped to code points (unique integers), and we need something to translate these code points data into bytes. That's where UTF-8 comes in so called encoding – simple!
using 'm_' or '_' in the front of a variable makes it easier to spot member variables in methods throughout an object.
As a side benefit typing 'm_' or '_' will make intellsense pop them up first ;)
To get exact name of control, use:
string controlName = Page.FindControl(Page.Request.Params["__EVENTTARGET"]).ID;
I think your problem is your version numbers. Try making 8.1 --> 8.01, and so forth. That should put the points in the right order.
Alternatively, you could plot using X
, where X is the column number you want, instead of using 1:X
. That will plot those values on the y axis and integers on the x axis. Try:
plot "ls.dat" using 2 title 'Removed' with lines, \
"ls.dat" using 3 title 'Added' with lines, \
"ls.dat" using 4 title 'Modified' with lines
I had the same problem and I resolved it like this:
numpy.full((2,2), True, dtype=bool)
You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.
public static String convertDate(String dateInMilliseconds,String dateFormat) {
return DateFormat.format(dateFormat, Long.parseLong(dateInMilliseconds)).toString();
}
Call this function
convertDate("82233213123","dd/MM/yyyy hh:mm:ss");
Try this snippet:
span {
display: inline-block;
width: 100px;
background: blue;
font-size: 30px;
color: white;
text-align: center;
margin-right: -3px;
}
Working demo: http://jsfiddle.net/dGHFV/2784/
The way i resolved was, i have written a function in controller and accessed it via ajax on jquery click event
First of all i want to thank @Stefano Altieri for giving me an idea of how to implement the above scenario,you are absolutely right we cannot access current session value from clientside when the session expires.
Also i would like to say that proper reading of question will help us to answer the question carefully.
If you need a basic border around you just need to use bootstrap wells.
For example the code below:
<div class="well">Basic Well</div>
Assuming you are on Windows (this bug is caused by the crappy bat files escaping), It is a bug introduced in the latest versions (7.0.56
and 8.0.14
) to workaround another bug. Try to remove the "
around the JAVA_OPTS
declaration in catalina.bat
. It fixed it for me with Tomcat 7.0.56
yesterday.
In 7.0.56
in bin/catalina.bat:179
and 184
:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"
..
:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"
to
:noJuliConfig
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%
..
:noJuliManager
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%
For your asterisk, it might only be a configuration of yours somewhere that appends it to the host declaration.
I saw this on Tomcat's bugtracker yesterday but I can't find the link again. Edit Found it! https://issues.apache.org/bugzilla/show_bug.cgi?id=56895
I hope it fixes your problem.
Members must be resolvable at compile time to be called directly from C#. Otherwise you must use reflection or dynamic objects.
Reflection
namespace ConsoleApplication1
{
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
foreach(Type type in DLL.GetExportedTypes())
{
var c = Activator.CreateInstance(type);
type.InvokeMember("Output", BindingFlags.InvokeMethod, null, c, new object[] {@"Hello"});
}
Console.ReadLine();
}
}
}
Dynamic (.NET 4.0)
namespace ConsoleApplication1
{
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
foreach(Type type in DLL.GetExportedTypes())
{
dynamic c = Activator.CreateInstance(type);
c.Output(@"Hello");
}
Console.ReadLine();
}
}
}
I want to put the correct answer in here, just in case others are having this problem like I was. If you hate the ViewBag, fine don't use it, but the real problem with the code in the question is that the same name is being used for both the model property and the selectlist as was pointed out by @RickAndMSFT
Simply changing the name of the DropDownList control should resolve the issue, like so:
@Html.DropDownList("NewsCategoriesSelection", (SelectList)ViewBag.NewsCategoriesID)
It doesn't really have anything to do with using the ViewBag or not using the ViewBag as you can have a name collision with the control regardless.
You can find the instructions here. Basically you just add
[global]
http-proxy-host = ip.add.re.ss
http-proxy-port = 3128
http-proxy-compression = no
to your ~/.subversion/servers
file.
If you encounter this problem when you add an app
from scratch. It is probably because that you miss some settings
. Three steps is needed when adding an app
.
Suppose you have a project named mysite
and you want to add an app
named your_app_name
. Put your template file under mysite/your_app_name/templates/your_app_name
as following.
+-- mysite
¦ +-- settings.py
¦ +-- urls.py
¦ +-- wsgi.py
+-- your_app_name
¦ +-- admin.py
¦ +-- apps.py
¦ +-- models.py
¦ +-- templates
¦ ¦ +-- your_app_name
¦ ¦ +-- my_index.html
¦ +-- urls.py
¦ +-- views.py
app
to INSTALLED_APPS
.Modify settings.py
INSTALLED_APPS = [
...
'your_app_name',
...
]
app
directory to DIRS
in TEMPLATES
.Modify settings.py
.
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'your_app_name', 'templates', 'your_app_name'),
...
]
}
]
With java8 now, you can use
Integer offset = ZonedDateTime.now().getOffset().getTotalSeconds();
to get the current system time offset from UTC. Then you can convert it to any format you want. Found it useful for my case. Example : https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html
Here's an awesome/really crappy way of extending multiple classes. I'm utilizing a couple functions that Babel put into my transpiled code. The function creates a new class that inherits class1, and class1 inherits class2, and so on. It has its issues, but a fun idea.
var _typeof = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? function (obj) {
return typeof obj
} : function (obj) {
return obj && typeof Symbol === 'function' && obj.constructor === Symbol ? 'symbol' : typeof obj
}
function _inherits (subClass, superClass) {
if (typeof superClass !== 'function' && superClass !== null) {
throw new TypeError('Super expression must either be null or a function, not ' + (
typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)))
}
subClass.prototype = Object.create(
superClass && superClass.prototype,
{
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
})
if (superClass) {
Object.setPrototypeOf
? Object.setPrototypeOf(subClass, superClass)
: subClass.__proto__ = superClass.__proto__ // eslint-disable-line no-proto
}
}
function _m (...classes) {
let NewSuperClass = function () {}
let c1 = NewSuperClass
for (let c of classes) {
_inherits(c1, c)
c1 = c
}
return NewSuperClass
}
import React from 'react'
/**
* Adds `this.log()` to your component.
* Log message will be prefixed with the name of the component and the time of the message.
*/
export default class LoggingComponent extends React.Component {
log (...msgs) {
if (__DEBUG__) {
console.log(`[${(new Date()).toLocaleTimeString()}] [${this.constructor.name}]`, ...msgs)
}
}
}
export class MyBaseComponent extends _m(LoggingComponent, StupidComponent) {}
Op De Cirkel is mostly right. His suggestion will work in most cases:
myString.replaceAll("\\p{C}", "?");
But if myString
might contain non-BMP codepoints then it's more complicated. \p{C}
contains the surrogate codepoints of \p{Cs}
. The replacement method above will corrupt non-BMP codepoints by sometimes replacing only half of the surrogate pair. It's possible this is a Java bug rather than intended behavior.
Using the other constituent categories is an option:
myString.replaceAll("[\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", "?");
However, solitary surrogate characters not part of a pair (each surrogate character has an assigned codepoint) will not be removed. A non-regex approach is the only way I know to properly handle \p{C}
:
StringBuilder newString = new StringBuilder(myString.length());
for (int offset = 0; offset < myString.length();)
{
int codePoint = myString.codePointAt(offset);
offset += Character.charCount(codePoint);
// Replace invisible control characters and unused code points
switch (Character.getType(codePoint))
{
case Character.CONTROL: // \p{Cc}
case Character.FORMAT: // \p{Cf}
case Character.PRIVATE_USE: // \p{Co}
case Character.SURROGATE: // \p{Cs}
case Character.UNASSIGNED: // \p{Cn}
newString.append('?');
break;
default:
newString.append(Character.toChars(codePoint));
break;
}
}
To answer the original question: yes, you can access the index value of a row in apply()
. It is available under the key name
and requires that you specify axis=1
(because the lambda processes the columns of a row and not the rows of a column).
Working example (pandas 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40
I am Using this
String timeStamp = new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp);
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
The data itself is one or more lucene indices, since you can have multiple shards. What you also need to backup is the cluster state, which contains all sorts of information regarding the cluster, the available indices, their mappings, the shards they are composed of etc.
It's all within the data
directory though, you can just copy it. Its structure is pretty intuitive. Right before copying it's better to disable automatic flush (in order to backup a consistent view of the index and avoiding writes on it while copying files), issue a manual flush, disable allocation as well. Remember to copy the directory from all nodes.
Also, next major version of elasticsearch is going to provide a new snapshot/restore api that will allow you to perform incremental snapshots and restore them too via api. Here is the related github issue: https://github.com/elasticsearch/elasticsearch/issues/3826.
Yes, it is sufficient. The way injection type attacks work, is by somehow getting an interpreter (The database) to evaluate something, that should have been data, as if it was code. This is only possible if you mix code and data in the same medium (Eg. when you construct a query as a string).
Parameterised queries work by sending the code and the data separately, so it would never be possible to find a hole in that.
You can still be vulnerable to other injection-type attacks though. For example, if you use the data in a HTML-page, you could be subject to XSS type attacks.
This is probably not a solution to your problem, but a suggestion just in case (I know I ran into a similar problem before but not with a .NET application).
If you are on a 64-bit machine, there are 2 regsvr32.exe
files;
One is in \Windows\System32
and the other one is in \Windows\SysWOW64
.
You cannot register 64-bit COM-objects with the 32-bit version, but you can do it vice versa. I'd try registering your DLL with both regsvr32.exe
files explicitly (i.e. typing "C:\Windows\System32\regsvr32.exe /i mydll.dll
" and then "C:\Windows\SysWOW64\regsvr32.exe /i mydll.dll
") and seeing if that helps...
After trying many different ways, re-installing IIS on my windows solved the problem.
There is another way, but...
DO NOT DO THIS IF YOU DO NOT WANT YOUR PASSWORD IN THE SCRIPT FILE (It isn't a good idea to store passwords in scripts, but some of us just like to know how.)
Ok, that was the warning, here's the code:
$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$cred
will have the credentials from John Doe with the password "ABCDEF".
Alternative means to get the password ready for use:
$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force
In short: No.
There is a hack, use vector as underlaid container, so queue::front
will return valid reference, convert it to pointer an iterate until <= queue::back
I test with below code and it is fine.
@echo off
set varEmpty=
if not "%varEmpty%"=="" (
echo varEmpty is not empty
) else (
echo varEmpty is empty
)
set varNotEmpty=hasValue
if not "%varNotEmpty%"=="" (
echo varNotEmpty is not empty
) else (
echo varNotEmpty is empty
)
You already have multiple answers to your question, but I would like to add another minor one here that might help to add something.
To view data structures in Perl you can use Data::Dumper
. To print a string you can use say
, which adds a newline character "\n"
after every call instead of adding it explicitly.
I usually use \s
which matches a whitespace character. If you add +
it matches one or more whitespace characters. You can read more about it here perlre
.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use feature 'say';
my $line = "file1.gz file2.gz file3.gz";
my @abc = split /\s+/, $line;
print Dumper \@abc;
say for @abc;
PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
If eclipse worries about an uncaught NameNotFoundException
, you can use:
PackageManager m = getPackageManager();
String s = getPackageName();
try {
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
} catch (PackageManager.NameNotFoundException e) {
Log.w("yourtag", "Error Package name not found ", e);
}
To blank it:
myObject["myVar"]=null;
To remove it:
delete myObject["myVar"]
as you can see in duplicate answers
Try,
var newList =
(
from x in empCollection
select new {Loc = x.empLoc, PL = x.empPL, Shift = x.empShift}
).Distinct();
This is for Nikola.
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
JSONObject j;
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
break;
}
}
}
}
return js1;
}
public static void main(String[] args) throws IOException, JSONException {
String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
JSONObject json = new JSONObject(text);
setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
System.out.println(json.toString(4));
}
If it's help bro,Do not forget to up for my reputation)))
According to mozilla:
A Map object can iterate its elements in insertion order - a for..of loop will return an array of [key, value] for each iteration.
and
Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this, Objects have been used as Maps historically; however, there are important differences between Objects and Maps that make using a Map better.
An Object has a prototype, so there are default keys in the map. However, this can be bypassed using map = Object.create(null). The keys of an Object are Strings, where they can be any value for a Map. You can get the size of a Map easily while you have to manually keep track of size for an Object.
Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.
Use objects when there is logic that operates on individual elements.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
The iterability-in-order is a feature that has long been wanted by developers, in part because it ensures the same performance in all browsers. So to me that's a big one.
The myMap.has(key)
method will be especially handy, and also the myMap.size
property.
function calculate() {_x000D_
// amount_x000D_
var salary = parseInt($('#salary').val());_x000D_
// percent _x000D_
var incentive_rate = parseInt($('#incentive_rate').val());_x000D_
var perc = "";_x000D_
if (isNaN(salary) || isNaN(incentive_rate)) {_x000D_
perc = " ";_x000D_
} else {_x000D_
perc = (incentive_rate/100) * salary;_x000D_
_x000D_
_x000D_
} $('#total_income').val(perc);_x000D_
}
_x000D_
Simple solution to resolve this problem is to set an empty value by default :
<input name='myInput' value={this.state.myInput || ''} onChange={this.handleChange} />
You need to add the new line character \n
:
console.log('line one \nline two')
would display:
line one
line two
Use RelativeLayout
, place your view in it, get RelativeLayout.LayoutParams
object from your view and set margins as you need. Then call requestLayout()
on your view. This is the only way I know.
In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:
so:
import sys
and when finished:
sys.exit()
Specifically saying overloading or overriding doesn't give the full picture. Polymorphism is simply the ability of an object to specialize its behavior based on its type.
I would disagree with some of the answers here in that overloading is a form of polymorphism (parametric polymorphism) in the case that a method with the same name can behave differently give different parameter types. A good example is operator overloading. You can define "+" to accept different types of parameters -- say strings or int's -- and based on those types, "+" will behave differently.
Polymorphism also includes inheritance and overriding methods, though they can be abstract or virtual in the base type. In terms of inheritance-based polymorphism, Java only supports single class inheritance limiting it polymorphic behavior to that of a single chain of base types. Java does support implementation of multiple interfaces which is yet another form of polymorphic behavior.
you can try to stop and start again with :
$ cd /path/apache-tomcat x.x.x/bin
then
$ sh shutdown.sh
when succesfully done the last step you must turn on your tomcat and catalina with command
$ sh startup.sh
I managed to resolve my problem with this way
I was recently shown this website for liquid layouts using CSS. http://matthewjamestaylor.com/blog/perfect-multi-column-liquid-layouts (Take a look at the demo pages in the links below).
The author now provides an example for fixed width layouts. Check out; http://matthewjamestaylor.com/blog/how-to-convert-a-liquid-layout-to-fixed-width.
This provides the following example(s), http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm (for two column layout like you are after I think)
http://matthewjamestaylor.com/blog/fixed-width-or-liquid-layout.htm (for three column layout).
Sorry for so many links to this guys site, but I think it is an AWESOME resource.
In SQL Management Studio you can:
Right click on the result set grid, select 'Save Result As...' and save in.
On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.
If you need to automate it, use bcp tool.
You can use <hr>
for a vertical line as well.
Set the width
to 1
and the size(height) as long as you want.
I used 500 in my example(demo):
With <hr width="1" size="500">
I don't like previous answers. The best solution is to use:
<android.support.v7.widget.AppCompatEditText
app:backgroundTint="@color/blue_gray_light" />
android:backgroundTint
for EditText
works only on API21+ . Because of it, we have to use the support library and AppCompatEditText
.
Note: we have to use app:backgroundTint
instead of android:backgroundTint
AndroidX version
<androidx.appcompat.widget.AppCompatEditText
app:backgroundTint="@color/blue_gray_light" />
You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:
lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)
Then you can get hold of the axes objects (an array of axes):
axes = lm.axes
After that you can tweak the axes properties
axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)
creates:
intersect_all <- function(a,b,...){
all_data <- c(a,b,...)
require(plyr)
count_data<- length(list(a,b,...))
freq_dist <- count(all_data)
intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
intersect_data
}
intersect_all(a,b,c)
UPDATE EDIT A simpler code
intersect_all <- function(a,b,...){
Reduce(intersect, list(a,b,...))
}
intersect_all(a,b,c)
If you use numpy.multiply
S = [22, 33, 45.6, 21.6, 51.8]
P = 2.45
multiply(S, P)
It gives you as a result
array([53.9 , 80.85, 111.72, 52.92, 126.91])
Set the required PATH in your cron
crontab -e
Edit: Press i
PATH=/usr/local/bin:/usr/local/:or_whatever
10 * * * * your_command
Save and exit :wq
This is a small adition to @Andrew Dunn's post above
Combining the 2 is possible to generate readable JS and matching output
var foo = "Bob\n\
is\n\
cool.\n\";
//catch volume update
var volEvents = "change,input";
var volEventsArr = volEvents.split(",");
for(var i = 0;i<volknob.length;i++) {
for(var k=0;k<volEventsArr.length;k++) {
volknob[i].addEventListener(volEventsArr[k], function() {
var cfa = document.getElementsByClassName('watch_televised');
for (var j = 0; j<cfa.length; j++) {
cfa[j].volume = this.value / 100;
}
});
}
}
Navigate to your play page:
https://play.google.com/store/apps/details?id=com.yourpackage
Using a standard HTTP GET. Now the following jQuery finds important info for you:
$("[itemprop='softwareVersion']").text()
$(".recent-change").each(function() { all += $(this).text() + "\n"; })
Now that you can extract these information manually, simply make a method in your app that executes this for you.
public static String[] getAppVersionInfo(String playUrl) {
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
props.setAllowHtmlInsideAttributes(true);
props.setAllowMultiWordAttributes(true);
props.setRecognizeUnicodeChars(true);
props.setOmitComments(true);
try {
URL url = new URL(playUrl);
URLConnection conn = url.openConnection();
TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
Object[] new_nodes = node.evaluateXPath("//*[@class='recent-change']");
Object[] version_nodes = node.evaluateXPath("//*[@itemprop='softwareVersion']");
String version = "", whatsNew = "";
for (Object new_node : new_nodes) {
TagNode info_node = (TagNode) new_node;
whatsNew += info_node.getAllChildren().get(0).toString().trim()
+ "\n";
}
if (version_nodes.length > 0) {
TagNode ver = (TagNode) version_nodes[0];
version = ver.getAllChildren().get(0).toString().trim();
}
return new String[]{version, whatsNew};
} catch (IOException | XPatherException e) {
e.printStackTrace();
return null;
}
}
Uses HtmlCleaner
SELECT c.ID
FROM clients c
WHERE EXISTS(SELECT c2.ID
FROM clients2 c2
WHERE c2.ID = c.ID);
Will return all ID's that are the SAME in both tables. To get the differences change EXISTS to NOT EXISTS.
It can work for all kind of layout.
android:windowSoftInputMode="adjustResize"
for example:
<activity android:name=".ActivityLogin"
android:screenOrientation="portrait"
android:theme="@style/AppThemeTransparent"
android:windowSoftInputMode="adjustResize"/>
android:fitsSystemWindows="true"
and
android:layout_alignParentBottom="true"
for example:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:fitsSystemWindows="true">
For Windows, I've created a build.cmd
file:
(replace the keystore path and alias)
For Cordova:
@echo off
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%
And for Ionic:
@echo off
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%
Save it in the ptoject's directory, you can double click or open it with cmd.
Use GSON library for that. Here is the sample code
List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");
String json = new Gson().toJson(foo );
Here is the maven dependency for Gson
<dependencies>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
Or you can directly download jar from here and put it in your class path
http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=
To send Json to client you can use spring or in simple servlet add this code
response.getWriter().write(json);
Couldn't you just reverse the string and replace only the first occurrence of the reversed search pattern? I'm thinking . . .
var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
if (str.endsWith(list[i])
{
var reversedHaystack = str.split('').reverse().join('');
var reversedNeedle = list[i].split('').reverse().join('');
reversedHaystack = reversedHaystack.replace(reversedNeedle, 'hsinif');
str = reversedHaystack.split('').reverse().join('');
}
}
See with the help of the following example if you can use literals and '$' sign in your case.
function doHomework(subject) {
alert(\`Starting my ${subject} homework.\`);
}
doHomework('maths');
Don't forget to take into consideration the global flag in your regexp :
var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi'); // => true
reg.test('abcdefghi'); // => false <=
This is because Regexp keeps track of the lastIndex when a new match is found.
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
I think this is the simple form
Button1.layer.cornerRadius = 10(Half of the length and width)
Button1.layer.borderWidth = 2
To create your cell styles see: http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors.
Custom colors
HSSF:
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("Default Palette");
//apply some colors from the standard palette,
// as in the previous examples.
//we'll use red text on a lime background
HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
HSSFFont font = wb.createFont();
font.setColor(HSSFColor.RED.index);
style.setFont(font);
cell.setCellStyle(style);
//save with the default palette
FileOutputStream out = new FileOutputStream("default_palette.xls");
wb.write(out);
out.close();
//now, let's replace RED and LIME in the palette
// with a more attractive combination
// (lovingly borrowed from freebsd.org)
cell.setCellValue("Modified Palette");
//creating a custom palette for the workbook
HSSFPalette palette = wb.getCustomPalette();
//replacing the standard red with freebsd.org red
palette.setColorAtIndex(HSSFColor.RED.index,
(byte) 153, //RGB red (0-255)
(byte) 0, //RGB green
(byte) 0 //RGB blue
);
//replacing lime with freebsd.org gold
palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);
//save with the modified palette
// note that wherever we have previously used RED or LIME, the
// new colors magically appear
out = new FileOutputStream("modified_palette.xls");
wb.write(out);
out.close();
XSSF:
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell( 0);
cell.setCellValue("custom XSSF colors");
XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
style1.setFillPattern(CellStyle.SOLID_FOREGROUND);
If you want to keep the changes and change the branch in a single line command
git stash && git checkout <branch_name> && git stash pop
I solve such queries using this pattern:
SELECT *
FROM t
WHERE t.field=(
SELECT MAX(t.field)
FROM t AS t0
WHERE t.group_column1=t0.group_column1
AND t.group_column2=t0.group_column2 ...)
That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:
WITH site_history AS (
SELECT sites.siteName, sites.siteIP, history.date
FROM sites
JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
SELECT MAX(date)
FROM site_history h0
WHERE h.siteName=h0.siteName)
ORDER BY siteName
It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date
field should be unique for each siteName
, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history
table has an unique index for (site, date)
, this query is also very fast, index range scan on the history
table scanning just the first item can be used.
Using Diamond(<>) operator for generic instance creation
Map<String, List<Trade>> trades = new TreeMap <> ();
Using strings in switch statements
String status= “something”;
switch(statue){
case1:
case2:
default:
}
Underscore in numeric literals
int val 12_15; long phoneNo = 01917_999_720L;
Using single catch statement for throwing multiple exception by using “|” operator
catch(IOException | NullPointerException ex){
ex.printStackTrace();
}
No need to close() resources because Java 7 provides try-with-resources statement
try(FileOutputStream fos = new FileOutputStream("movies.txt");
DataOutputStream dos = new DataOutputStream(fos)) {
dos.writeUTF("Java 7 Block Buster");
} catch(IOException e) {
// log the exception
}
binary literals with prefix “0b” or “0B”
<span class="txt">Some Text</span>
.txt:hover {
text-decoration: underline;
}
$rootbeer = (float) $InvoicedUnits;
Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.
I find the best (and least frustrating) path is to start with Allow from All
, then, when you know it will work that way, scale it back to the more secure Allow from 127.0.0.1
or Allow from ::1
(localhost).
As long as your firewall is configured properly, Allow from all
shouldn't cause any problems, but it is better to only allow from localhost if you don't need other computers to be able to access your site.
Don't forget to restart Apache whenever you make changes to httpd.conf. They will not take effect until the next start.
Hopefully this is enough to get you started, there is lots of documentation available online.
I tried to resolve with the suggested answer and still ran into some issues...
This was a solution to my problem:
ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}
# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]
Specifically targeting your problem:
RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]
Use git format-patch
to slice out the part of the commit you care about and git am
to apply it to another branch
git format-patch <sha> -- path/to/file
git checkout other-branch
git am *.patch
Interesting approach could be found here: How To Enlarge Your Columns With No Downtime by spaghettidba
If you try to enlarge this column with a straight “ALTER TABLE” command, you will have to wait for SQLServer to go through all the rows and write the new data type
ALTER TABLE tab_name ALTER COLUMN col_name new_larger_data_type;
To overcome this inconvenience, there is a magic column enlargement pill that your table can take, and it’s called Row Compression. (...) With Row Compression, your fixed size columns can use only the space needed by the smallest data type where the actual data fits.
When table is compressed at ROW
level, then ALTER TABLE ALTER COLUMN
is metadata only operation.
If anyone wants the true solution for centering BOTH images and text within a span using bootstrap row-fluid, here it is (how to implement this and explanation follows my example):
css
div.row-fluid [class*="span"] .center-in-span {
float: none;
margin: 0 auto;
text-align: center;
display: block;
width: auto;
height: auto;
}
html
<div class="row-fluid">
<div class="span12">
<img class="center-in-span" alt="MyExample" src="/path/to/example.jpg"/>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<p class="center-in-span">this is text</p>
</div>
</div>
USAGE: To use this css to center an image within a span, simply apply the .center-in-span class to the img element, as shown above.
To use this css to center text within a span, simply apply the .center-in-span class to the p element, as shown above.
EXPLANATION: This css works because we are overriding specific bootstrap styling. The notable differences from the other answers that were posted are that the width and height are set to auto, so you don't have to used a fixed with (good for a dynamic webpage). also, the combination of setting the margin to auto, text-align:center and display:block, takes care of both images and paragraphs.
Let me know if this is thorough enough for easy implementation.
Most answers are actually producing the CSV which I don't always have good experience with, when opening in Excel.
One way of doing it would be also with ACE OLEDB Provider (see also connection strings for Excel). Of course you'd have to have the provider installed and registered. You do have it, if you have Excel installed, but this is something you have to consider when deploying (e.g. on web server).
In below helper class code you'd have to call something like ExportHelper.CreateXlsFromDataTable(dataset.Tables[0], @"C:\tmp\export.xls");
public class ExportHelper
{
private const string ExcelOleDbConnectionStringTemplate = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\";";
/// <summary>
/// Creates the Excel file from items in DataTable and writes them to specified output file.
/// </summary>
public static void CreateXlsFromDataTable(DataTable dataTable, string fullFilePath)
{
string createTableWithHeaderScript = GenerateCreateTableCommand(dataTable);
using (var conn = new OleDbConnection(String.Format(ExcelOleDbConnectionStringTemplate, fullFilePath)))
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
OleDbCommand cmd = new OleDbCommand(createTableWithHeaderScript, conn);
cmd.ExecuteNonQuery();
foreach (DataRow dataExportRow in dataTable.Rows)
{
AddNewRow(conn, dataExportRow);
}
}
}
private static void AddNewRow(OleDbConnection conn, DataRow dataRow)
{
string insertCmd = GenerateInsertRowCommand(dataRow);
using (OleDbCommand cmd = new OleDbCommand(insertCmd, conn))
{
AddParametersWithValue(cmd, dataRow);
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Generates the insert row command.
/// </summary>
private static string GenerateInsertRowCommand(DataRow dataRow)
{
var stringBuilder = new StringBuilder();
var columns = dataRow.Table.Columns.Cast<DataColumn>().ToList();
var columnNamesCommaSeparated = string.Join(",", columns.Select(x => x.Caption));
var questionmarkCommaSeparated = string.Join(",", columns.Select(x => "?"));
stringBuilder.AppendFormat("INSERT INTO [{0}] (", dataRow.Table.TableName);
stringBuilder.Append(columnNamesCommaSeparated);
stringBuilder.Append(") VALUES(");
stringBuilder.Append(questionmarkCommaSeparated);
stringBuilder.Append(")");
return stringBuilder.ToString();
}
/// <summary>
/// Adds the parameters with value.
/// </summary>
private static void AddParametersWithValue(OleDbCommand cmd, DataRow dataRow)
{
var paramNumber = 1;
for (int i = 0; i <= dataRow.Table.Columns.Count - 1; i++)
{
if (!ReferenceEquals(dataRow.Table.Columns[i].DataType, typeof(int)) && !ReferenceEquals(dataRow.Table.Columns[i].DataType, typeof(decimal)))
{
cmd.Parameters.AddWithValue("@p" + paramNumber, dataRow[i].ToString().Replace("'", "''"));
}
else
{
object value = GetParameterValue(dataRow[i]);
OleDbParameter parameter = cmd.Parameters.AddWithValue("@p" + paramNumber, value);
if (value is decimal)
{
parameter.OleDbType = OleDbType.Currency;
}
}
paramNumber = paramNumber + 1;
}
}
/// <summary>
/// Gets the formatted value for the OleDbParameter.
/// </summary>
private static object GetParameterValue(object value)
{
if (value is string)
{
return value.ToString().Replace("'", "''");
}
return value;
}
private static string GenerateCreateTableCommand(DataTable tableDefination)
{
StringBuilder stringBuilder = new StringBuilder();
bool firstcol = true;
stringBuilder.AppendFormat("CREATE TABLE [{0}] (", tableDefination.TableName);
foreach (DataColumn tableColumn in tableDefination.Columns)
{
if (!firstcol)
{
stringBuilder.Append(", ");
}
firstcol = false;
string columnDataType = "CHAR(255)";
switch (tableColumn.DataType.Name)
{
case "String":
columnDataType = "CHAR(255)";
break;
case "Int32":
columnDataType = "INTEGER";
break;
case "Decimal":
// Use currency instead of decimal because of bug described at
// http://social.msdn.microsoft.com/Forums/vstudio/en-US/5d6248a5-ef00-4f46-be9d-853207656bcc/localization-trouble-with-oledbparameter-and-decimal?forum=csharpgeneral
columnDataType = "CURRENCY";
break;
}
stringBuilder.AppendFormat("{0} {1}", tableColumn.ColumnName, columnDataType);
}
stringBuilder.Append(")");
return stringBuilder.ToString();
}
}
add is a local variable not a global variable try this
var add;_x000D_
var input = document.getElementById("input");_x000D_
_x000D_
function start() {_x000D_
add = setInterval("input.value++", 1000);_x000D_
}_x000D_
start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="number" id="input" />_x000D_
<input type="button" onclick="clearInterval(add)" value="stop" />_x000D_
<input type="button" onclick="start()" value="start" />
_x000D_
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.
BernardSaucier has already given you an answer. My post is not an answer but an explanation as to why you shouldn't be using UsedRange
.
UsedRange
is highly unreliable as shown HERE
To find the last column which has data, use .Find
and then subtract from it.
With Sheets("Sheet1")
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastCol = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Else
lastCol = 1
End If
End With
If lastCol > 8 Then
'Debug.Print ActiveSheet.UsedRange.Columns.Count - 8
'The above becomes
Debug.Print lastCol - 8
End If
I did not manage to make the most popular answers work.
I attempted to come up with a solution of my own using plain old eval:
eval '$var =~ s/' . $find . '/' . $replace . '/gsu;';
Of course, this allows for code injection. But as far as I know, the only way to escape the regex query and inject code is to insert two forward slashes in $find or one in $replace, followed by a semi-colon, after which you can add add code. For example, if I set the variables this way:
my $find = 'foo';
my $replace = 'bar/; print "You\'ve just been hacked!\n"; #';
The evaluated code is this:
$var =~ s/foo/bar/; print "You've just been hacked!\n"; #/gsu;';
So what I do is make sure the strings don't contain any unescaped forward slashes.
First, I copy the strings into dummy strings.
my $findTest = $find;
my $replaceTest = $replace;
Then, I remove all escaped backslashes (backslash pairs) from the dummy strings. This allows me to find forward slashes that are not escaped, without falling into the trap of considering a forward slash escaped if it's preceded by an escaped backslash. For example: \/
contains an escaped forward slash, but \\/
contains a literal forward slash, because the backslash is escaped.
$findTest =~ s/\\\\//gmu;
$replaceTest =~ s/\\\\//gmu;
Now if any forward slash that is not preceded by a backslash remains in the strings, I throw a fatal error, as that would allow the user to insert arbitrary code.
if ($findTest =~ /(?<!\\)\// || $replaceTest =~ /(?<!\\)\//)
{
print "String must not contain unescaped slashes.\n";
exit 1;
}
Then I eval.
eval '$var =~ s/' . $find . '/' . $replace . '/gsu;';
I'm not an expert at preventing code injection, but I'm the only one using my script, so I'm content using this solution without fully knowing if it's vulnerable. But as far as I know, it may be, so if anyone knows if there is or isn't any way to inject code into this, please provide your insight in a comment.
It depends upon which platform you're on as to how it will be translated and whether it will be there at all: Wikipedia entry on newline
uint32_t
is standard, uint32
is not. That is, if you include <inttypes.h>
or <stdint.h>
, you will get a definition of uint32_t
. uint32
is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.
To install a new package and only that, you have two options:
Using the require
command, just run:
composer require new/package
Composer will guess the best version constraint to use, install the package, and add it to composer.lock
.
You can also specify an explicit version constraint by running:
composer require new/package ~2.5
–OR–
Using the update
command, add the new package manually to composer.json
, then run:
composer update new/package
If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag --with-dependencies
. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).
Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If php -m
doesn't list mcrypt then it's missing.
Important: Don't forget to specify new/package
when using composer update
! Omitting that argument will cause all dependencies, as well as composer.lock
, to be updated.
I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information
One other good reason to always typedef enums and structs results from this problem:
enum EnumDef
{
FIRST_ITEM,
SECOND_ITEM
};
struct StructDef
{
enum EnuumDef MyEnum;
unsigned int MyVar;
} MyStruct;
Notice the typo in EnumDef in the struct (EnuumDef)? This compiles without error (or warning) and is (depending on the literal interpretation of the C Standard) correct. The problem is that I just created an new (empty) enumeration definition within my struct. I am not (as intended) using the previous definition EnumDef.
With a typdef similar kind of typos would have resulted in a compiler errors for using an unknown type:
typedef
{
FIRST_ITEM,
SECOND_ITEM
} EnumDef;
typedef struct
{
EnuumDef MyEnum; /* compiler error (unknown type) */
unsigned int MyVar;
} StructDef;
StrructDef MyStruct; /* compiler error (unknown type) */
I would advocate ALWAYS typedef'ing structs and enumerations.
Not only to save some typing (no pun intended ;)), but because it is safer.
Use stream to write content to webrequest
string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
Following these instructions worked for me: http://www.mdoninger.de/2015/05/16/completion-for-custom-properties-in-spring-boot.html
That message about having to Re-run the Annotation Processor is a bit confusing as it appears it stays there all the time even if nothing has changed.
The key seems to be rebuilding the project after adding the required dependency, or after making any property changes. After doing that and going back to the YAML file, all my properties were now linked to the configuration classes.
You may need to click the 'Reimport All Maven Projects' button in the Maven pane as well to get the .yaml file view to recognise the links back to the corresponding Java class.
I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
color: #000; /*Sets the text hover color on navbar*/
}
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
a:hover, .navbar-default .navbar-nav > .active > a:focus {
color: white; /*BACKGROUND color for active*/
background-color: #030033;
}
.navbar-default {
background-color: #0f006f;
border-color: #030033;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #66CCFF; /*change color of links in drop down here*/
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: silver; /*Change rollover cell color here*/
}
.navbar-default .navbar-nav > li > a {
color: white; /*Change active text color here*/
}
Sub MultiProcessing_Principle()
Dim k As Long, j As Long
k = Environ("NUMBER_OF_PROCESSORS")
For j = 1 To k
Shellm "msaccess", "C:\Autoexec.mdb"
Next
DoCmd.Quit
End Sub
Private Sub Shellm(a As String, b As String) ' Shell modificirani
Const sn As String = """"
Const r As String = """ """
Shell sn & a & r & b & sn, vbMinimizedNoFocus
End Sub
$(window).scroll(function() {
$('.logo_container, .slogan').css({
"opacity" : ".1",
"transition" : "opacity .8s ease-in-out"
});
});
Check the fiddle: http://jsfiddle.net/2k3hfwo0/2/
Another way when working with incoming data (like from an ajax call):
var new_div = $(data).hide();
$('#old_div').append(new_div);
new_div.slideDown();
One of the reason may be improper date/time of your PC.
In Ubuntu PC to check the date and time using:
date
Example, One of the ways to update date and time is:
date -s "23 MAR 2017 17:06:00"
Do a quick 'record macro' to see the color number associated with the color you're looking for (yellow highlight is 65535). Then erase the code and put
Sub Name()
Selection.Interior.Color = 65535 '(your number may be different depending on the above)
End Sub
If you have a worksheet with many rows that all contain the formula, by far the easiest method is to copy a row that is without data (but it does contain formulas), and then "insert copied cells" below/above the row where you want to add. The formulas remain. In a pinch, it is OK to use a row with data. Just clear it or overwrite it after pasting.
When you don't want to change the link (e.g. foo.php?id=1&id=2&id=3
) you could probably do something like this (although there might be a better way...):
$id_arr = array();
foreach (explode("&", $_SERVER['QUERY_STRING']) as $tmp_arr_param) {
$split_param = explode("=", $tmp_arr_param);
if ($split_param[0] == "id") {
$id_arr[] = urldecode($split_param[1]);
}
}
print_r($id_arr);
#case_date= 03/31/2020
#Above is the value stored in case_date in format(mm/dd/yyyy )
demo=case_date.split("/")
new_case_date = demo[1]+"-"+demo[0]+"-"+demo[2]
#new format of date is (dd/mm/yyyy) test by printing it
print(new_case_date)
I had the same problem. The problem is remote had something preventing this.
I first created a local repository. I added a LICENSE
and README.md
file to my local and committed.
Then I wanted a remote repository so I created one on GitHub. Here I made a mistake of checking "Initialize this repository with a README", which created a README.md in remote too.
So now when I ran
git push --set-upstream origin master
I got:
error: failed to push some refs to 'https://github.com/lokeshub/myTODs.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes
(e.g. hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
Now to overcome this I did
git pull origin master
Which resulted in the below error:
From https://github.com/lokeshub/myTODs
branch master -> FETCH_HEAD
fatal: refusing to merge unrelated histories**
I tried:
git pull origin master --allow-unrelated-histories
Result:
From https://github.com/lokeshub/myTODs
* branch master -> FETCH_HEAD
Auto-merging README.md
CONFLICT (add/add): Merge conflict in README.md
Automatic merge failed;
fix conflicts and then commit the result.
Solution:
I removed the remote repository and created a new (I think only removing file README
could have worked) and after that the below worked:
git remote rm origin
git remote add origin https://github.com/lokeshub/myTODOs.git
git push --set-upstream origin master
for(var memberName in ad)
{
//Member Name: memberName
//Member Value: ad[memberName]
}
Member means Member property, member variable, whatever you want to call it >_>
The above code will return EVERYTHING, including toString... If you only want to see if the object's prototype has been extended:
var dummyObj = {};
for(var memberName in ad)
{
if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
//Member Name: memberName
//Member Value: ad[memberName]
}
Note A: We check to see if the dummy object's member has the same type as our testing object's member. If it is an extend, dummyobject's member type should be "undefined"
May be this is alltime multiple connection open issue, you are somewhere in your code opening connections and not closing them properly. use
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
}
Refer this article: http://msdn.microsoft.com/en-us/library/ms254507(v=vs.80).aspx, The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.
Use fallocate
if you don't want to wait for disk.
Example:
fallocate -l 100G BigFile
Usage:
Usage:
fallocate [options] <filename>
Preallocate space to, or deallocate space from a file.
Options:
-c, --collapse-range remove a range from the file
-d, --dig-holes detect zeroes and replace with holes
-i, --insert-range insert a hole at range, shifting existing data
-l, --length <num> length for range operations, in bytes
-n, --keep-size maintain the apparent size of the file
-o, --offset <num> offset for range operations, in bytes
-p, --punch-hole replace a range with a hole (implies -n)
-z, --zero-range zero and ensure allocation of a range
-x, --posix use posix_fallocate(3) instead of fallocate(2)
-v, --verbose verbose mode
-h, --help display this help
-V, --version display version
Do you want iteration? itertools.combinations. Common usage:
>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
If you just need to compute the formula, use math.factorial:
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
print nCr(4,2)
In Python 3, use the integer division //
instead of /
to avoid overflows:
return f(n) // f(r) // f(n-r)
6
Assuming "current version" is the working directory (uncommitted modifications) and "last version" is HEAD
(last committed modifications for the current branch), simply do
git diff HEAD
Credit for the following goes to user Cerran
.
And if you always skip the staging area with -a
when you commit, then you can simply use git diff
.
Summary
git diff
shows unstaged changes.git diff --cached
shows staged changes.git diff HEAD
shows all changes (both staged and unstaged).Source: git-diff(1) Manual Page – Cerran
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader. This typically means that the class is missing from the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. This is sometimes the case when working in more complex environments like an App Server (WebSphere is infamous for such classloader issues).
People often tend to confuse java.lang.NoClassDefFoundError
with java.lang.ClassNotFoundException
however there's an important distinction. For example an exception (an error really since java.lang.NoClassDefFoundError
is a subclass of java.lang.Error) like
java.lang.NoClassDefFoundError:
org/apache/activemq/ActiveMQConnectionFactory
does not mean that the ActiveMQConnectionFactory class is not in the CLASSPATH. Infact its quite the opposite. It means that the class ActiveMQConnectionFactory was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (ActiveMQConnectionFactory in this case) and look for code using static blocks or static members. If you don't have access the the source, then simply decompile it using JAD.
On examining the code, say you find a line of code like below, make sure that the class SomeClass in in your CLASSPATH.
private static SomeClass foo = new SomeClass();
Tip : To find out which jar a class belongs to, you can use the web site jarFinder . This allows you to specify a class name using wildcards and it searches for the class in its database of jars. jarhoo allows you to do the same thing but its no longer free to use.
If you would like to locate the which jar a class belongs to in a local path, you can use a utility like jarscan ( http://www.inetfeedback.com/jarscan/ ). You just specify the class you'd like to locate and the root directory path where you'd like it to start searching for the class in jars and zip files.
Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:
private DataTable LoadExcelData(string fileName)
{
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);
myCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
return dt;
}
You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.
ctrl != super on windows and linux machines.
If the F12 version of "Goto Definition" produces results of several files, the "ctrl + shift + click" version might not work well. I found that bug when viewing golang project with GoSublime package.
I have a simpler solution for you:
window.onload = window.onresize = (event) => {
//Your Code Here
}
I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.
I sometimes use "yield" like this:
def add_to_http
"http://#{yield}"
end
puts add_to_http { "www.example.com" }
puts add_to_http { "www.victim.com"}
Also, the ternary operator enables a form of "optional" parameter. Java does not allow optional parameters in method signatures but the ternary operator enables you to easily inline a default choice when null
is supplied for a parameter value.
For example:
public void myMethod(int par1, String optionalPar2) {
String par2 = ((optionalPar2 == null) ? getDefaultString() : optionalPar2)
.trim()
.toUpperCase(getDefaultLocale());
}
In the above example, passing null
as the String
parameter value gets you a default string value instead of a NullPointerException
. It's short and sweet and, I would say, very readable. Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
Moreover, this pattern enables you to make the String
parameter truly optional (if it is deemed useful to do so) by overloading the method as follows:
public void myMethod(int par1) {
return myMethod(par1, null);
}
For the syntax, it looks like this (leave out the column list to implicitly mean "all")
INSERT INTO this_table_archive
SELECT *
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00'
For avoiding primary key errors if you already have data in the archive table
INSERT INTO this_table_archive
SELECT t.*
FROM this_table t
LEFT JOIN this_table_archive a on a.id=t.id
WHERE t.entry_date < '2011-01-01 00:00:00'
AND a.id is null # does not yet exist in archive
To clear out all the parameters, without doing a page refresh, AND if you are using HTML5, then you can do this:
history.pushState({}, '', 'index.html' ); //replace 'index.html' with whatever your page name is
This will add an entry in the browser history. You could also consider replaceState
if you don't wan't to add a new entry and just want to replace the old entry.
Doing the following in a command prompt works for me, also adding to my User environment variables worked fine as well:
set PATH=%PATH%;C:\Program Files\7-Zip\
echo %PATH%
7z
You should see as output (or something similar - as this is on my laptop running Windows 7):
C:\Users\Phillip>set PATH=%PATH%;C:\Program Files\7-Zip\
C:\Users\Phillip>echo %PATH%
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Wi
ndows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\
WirelessCommon\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\To
ols\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Fil
es (x86)\QuickTime\QTSystem\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Notepad+
+;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\7-Zip\
C:\Users\Phillip>7z
7-Zip [64] 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18
Usage: 7z <command> [<switches>...] <archive_name> [<file_names>...]
[<@listfiles...>]
<Commands>
a: Add files to archive
b: Benchmark
d: Delete files from archive
e: Extract files from archive (without using directory names)
l: List contents of archive
t: Test integrity of archive
u: Update files to archive
x: eXtract files with full paths
<Switches>
-ai[r[-|0]]{@listfile|!wildcard}: Include archives
-ax[r[-|0]]{@listfile|!wildcard}: eXclude archives
-bd: Disable percentage indicator
-i[r[-|0]]{@listfile|!wildcard}: Include filenames
-m{Parameters}: set compression Method
-o{Directory}: set Output directory
-p{Password}: set Password
-r[-|0]: Recurse subdirectories
-scs{UTF-8 | WIN | DOS}: set charset for list files
-sfx[{name}]: Create SFX archive
-si[{name}]: read data from stdin
-slt: show technical information for l (List) command
-so: write data to stdout
-ssc[-]: set sensitive case mode
-ssw: compress shared files
-t{Type}: Set type of archive
-u[-][p#][q#][r#][x#][y#][z#][!newArchiveName]: Update options
-v{Size}[b|k|m|g]: Create volumes
-w[{path}]: assign Work directory. Empty path means a temporary directory
-x[r[-|0]]]{@listfile|!wildcard}: eXclude filenames
-y: assume Yes on all queries
You could try this:
#include <stdio.h>
int main()
{
int i,j;
int my_array[3][3] ={10, 23, 42, 1, 654, 0, 40652, 22, 0};
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d ", my_array[i][j]);
}
printf("\n");
}
return 0;
}
I made a deleteRabbitMqQs.sh, which accepts arguments to search the list of queues for, selecting only ones matching the pattern you want. If you offer no arguments, it will delete them all! It shows you the list of queues its about to delete, letting you quit before doing anything destructive.
for word in "$@"
do
args=true
newQueues=$(rabbitmqctl list_queues name | grep "$word")
queues="$queues
$newQueues"
done
if [ $# -eq 0 ]; then
queues=$(rabbitmqctl list_queues name | grep -v "\.\.\.")
fi
queues=$(echo "$queues" | sed '/^[[:space:]]*$/d')
if [ "x$queues" == "x" ]; then
echo "No queues to delete, giving up."
exit 0
fi
read -p "Deleting the following queues:
${queues}
[CTRL+C quit | ENTER proceed]
"
while read -r line; do
rabbitmqadmin delete queue name="$line"
done <<< "$queues"
If you want different matching against the arguments you pass in, you can alter the grep in line four. When deleting all queues, it won't delete ones with three consecutive spaces in them, because I figured that eventuality would be rarer than people who have rabbitmqctl printing its output out in different languages.
Enjoy!
In Python 3.x, you can use the end
argument to the print()
function to prevent a newline character from being printed:
print("Nope, that is not a two. That is a", end="")
In Python 2.x, you can use a trailing comma:
print "this should be",
print "on the same line"
You don't need this to simply print a variable, though:
print "Nope, that is not a two. That is a", x
Note that the trailing comma still results in a space being printed at the end of the line, i.e. it's equivalent to using end=" "
in Python 3. To suppress the space character as well, you can either use
from __future__ import print_function
to get access to the Python 3 print function or use sys.stdout.write()
.
Here I found a tweak for this, without any third party tool. This will make the following shortcut to work:
fn + right: to go to the end of the line.
fn + left: to go to the beginning of the line.
cmd + ,
).EDIT: Refer to the comment by @Maurice Gilden below for more insights.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace SamplePrograme
{
public class Program
{
public enum Suit : int
{
Spades = 0,
Hearts = 1,
Clubs = 2,
Diamonds = 3
}
public static void Main(string[] args)
{
//from string
Console.WriteLine((Suit) Enum.Parse(typeof(Suit), "Clubs"));
//from int
Console.WriteLine((Suit)1);
//From number you can also
Console.WriteLine((Suit)Enum.ToObject(typeof(Suit) ,1));
}
}
}
If you declare one variable/object per line not only does it solve this problem, but it makes the code clearer and prevents silly mistakes when declaring pointers.
To directly answer your question though, you have to initialize each variable to 0 explicitly. int a = 0, b = 0, c = 0;
.
You say:
To me if a source repository is available for public it should take less than 10 seconds to have that code in my filesystem.
And of course, if you want to use Git (which GitHub is all about), then what you do to get the code onto your system is called "cloning the repository".
It's a single Git invocation on the command line, and it will give you the code just as seen when you browse the repository on the web (when getting a ZIP archive, you will need to unpack it and so on, it's not always directly browsable). For the repository you mention, you would do:
$ git clone git://github.com/SpringSource/spring-data-graph-examples.git
The git:
-type URL is the one from the page you linked to. On my system just now, running the above command took 3.2 seconds. Of course, unlike ZIP, the time to clone a repository will increase when the repository's history grows. There are options for that, but let's keep this simple.
I'm just saying: You sound very frustrated when a large part of the problem is your reluctance to actually use Git.
This is a sample simplelogger.properties
which you can place on the classpath (uncomment the properties you wish to use):
# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info
# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=
# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false
# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true
# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true
# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false
Now, one can use Spark to do the same and its way faster than other approaches (such as Hadoop MR). Here is the code snippet.
def traverseDirectory(filePath:String,recursiveTraverse:Boolean,filePaths:ListBuffer[String]) {
val files = FileSystem.get( sparkContext.hadoopConfiguration ).listStatus(new Path(filePath))
files.foreach { fileStatus => {
if(!fileStatus.isDirectory() && fileStatus.getPath().getName().endsWith(".xml")) {
filePaths+=fileStatus.getPath().toString()
}
else if(fileStatus.isDirectory()) {
traverseDirectory(fileStatus.getPath().toString(), recursiveTraverse, filePaths)
}
}
}
}
The following steps worked for me:
str.strip()
returns a string with leading+trailing whitespace removed, .lstrip
and .rstrip
for only leading and trailing respectively.
grades.append(lists[i].rstrip('\n').split(','))
You can use the box-shadow property on a tr element as a subtitute for a border. As a plus, any border-radius property on the same element will also apply to the box shadow.
box-shadow: 0px 0px 0px 1px rgb(0, 0, 0);
Applies to Bootstrap 3 only.
Ignoring the letters (xs, sm, md, lg) for now, I'll start with just the numbers...
col-*-6
spans 6 of 12 columns (half the width), col-*-12
spans 12 of 12 columns (the entire width), etcSo, if you want two equal columns to span a div, write
<div class="col-xs-6">Column 1</div>
<div class="col-xs-6">Column 2</div>
Or, if you want three unequal columns to span that same width, you could write:
<div class="col-xs-2">Column 1</div>
<div class="col-xs-6">Column 2</div>
<div class="col-xs-4">Column 3</div>
You'll notice the # of columns always add up to 12. It can be less than twelve, but beware if more than 12, as your offending divs will bump down to the next row (not .row
, which is another story altogether).
You can also nest columns within columns, (best with a .row
wrapper around them) such as:
<div class="col-xs-6">
<div class="row">
<div class="col-xs-4">Column 1-a</div>
<div class="col-xs-8">Column 1-b</div>
</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-2">Column 2-a</div>
<div class="col-xs-10">Column 2-b</div>
</div>
</div>
Each set of nested divs also span up to 12 columns of their parent div. NOTE: Since each .col
class has 15px padding on either side, you should usually wrap nested columns in a .row
, which has -15px margins. This avoids duplicating the padding and keeps the content lined up between nested and non-nested col classes.
-- You didn't specifically ask about the xs, sm, md, lg
usage, but they go hand-in-hand so I can't help but touch on it...
In short, they are used to define at which screen size that class should apply:
Read the "Grid Options" chapter from the official Bootstrap documentation for more details.
You should usually classify a div using multiple column classes so it behaves differently depending on the screen size (this is the heart of what makes bootstrap responsive). eg: a div with classes col-xs-6
and col-sm-4
will span half the screen on the mobile phone (xs) and 1/3 of the screen on tablets(sm).
<div class="col-xs-6 col-sm-4">Column 1</div> <!-- 1/2 width on mobile, 1/3 screen on tablet) -->
<div class="col-xs-6 col-sm-8">Column 2</div> <!-- 1/2 width on mobile, 2/3 width on tablet -->
NOTE: as per comment below, grid classes for a given screen size apply to that screen size and larger unless another declaration overrides it (i.e. col-xs-6 col-md-4
spans 6 columns on xs
and sm
, and 4 columns on md
and lg
, even though sm
and lg
were never explicitly declared)
NOTE: if you don't define xs
, it will default to col-xs-12
(i.e. col-sm-6
is half the width on sm
, md
and lg
screens, but full-width on xs
screens).
NOTE: it's actually totally fine if your .row
includes more than 12 cols, as long as you are aware of how they will react. --This is a contentious issue, and not everyone agrees.
You need to use
<?php bloginfo('template_directory'); ?>
It returns the directory of the current WordPress theme.
Now for example, if your theme has some image named example.jpg
inside some folder name subfolder
folder in the images
folder.
themes
|-> your theme
|-> images
|->subfolder
|-> examples.jpg
You access it like this
<img class="article-image" src="<?php bloginfo('template_directory'); ?> /images/subfolder/example.jpg" border="0" alt="">
some sources prefere to use .env.development
and .env.production
but that's not obligatory.
it seems that if your environment variable does not start like that so you will have problems
to include your environment variable just put on your code process.env.REACT_APP_VARIABLE
You don't have to install any external dependency
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
The problem with changing it via JavaScript or CSS is that if you have a slower connection, the image will take a second to change to the hovered version. This will cause an undesirable flash as one disappears while the other downloads.
What I've done before is have two images. Then hide and show each depending on the hover state. This will allow for a clean switch between the two images.
<a href="/settings">
<img class="default" src="settings-default.svg"/>
<img class="hover" src="settings-hover.svg"/>
<span>Settings</span>
</a>
a img.hover {
display: none;
}
a img.default {
display: inherit;
}
a:hover img.hover {
display: inherit;
}
a:hover img.default {
display: none;
}
The obj
directory is for intermediate object files and other transient data files that are generated by the compiler or build system during a build. The bin
directory is the directory that final output binaries (and any dependencies or other deployable files) will be written to.
You can change the actual directories used for both purposes within the project settings, if you like.
I also suggest using contourf(Z)
. For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.
So in my case, I prefer to use jucestain's answer. The default shading faceted
of pcolor()
is more suitable.
However, pcolor()
does not use the last row and column of the plotted matrix. For this, I used the padarray()
function:
pcolor(padarray(Z,[1 1],0,'post'))
Sorry if that is not really related to the original post
Since you didn't refer to self
in the bar
method body, PyCharm is asking if you might have wanted to make bar
static. In other programming languages, like Java, there are obvious reasons for declaring a static method. In Python, the only real benefit to a static method (AFIK) is being able to call it without an instance of the class. However, if that's your only reason, you're probably better off going with a top-level function - as note here.
In short, I'm not one hundred percent sure why it's there. I'm guessing they'll probably remove it in an upcoming release.
Or use the XmlSerializer class.
XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));
If you iterate over a dictionary you get the keys, so assuming your dictionary is in a variable called data
and you have some function find_definition()
which gets the definition, you can do something like the following:
for word in data:
data[word] = find_definition(word)
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
You can give variable names as project files. For instance in you plugin configuration give only one tag as below:-
<projectFile>${projectName}</projectFile>
Then on command line you can pass the project name as parameter:-
mvn [your-command] -DprojectName=[name of project]
You can manually set xticks (and yticks) using pyplot.xticks:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()
You can never get 100% isolation. Because a pod may have some shared dependencies and if you attempt to update your single pod, then it would update the dependencies of other pods as well. If that is ok then:
tl;dr use:
pod update podName
Why? Read below.
pod update
will NOT respect the podfile.lock
. It will override it — pertaining to that single podpod install
will respect the podfile.lock
, but will try installing every pod mentioned in the podfile based on the versions its locked to (in the Podfile.lock).This diagram helps better understand the differences:
The major problem comes from the ~>
aka optimistic operator.
Podfile
is not enoughSome might think that specifying exact versions of their pods in their Podfile
, like pod 'A', '1.0.0'
, is enough to guarantee that every user will have the same version as other people on the team.
Then they might even use pod update
, even when just adding a new pod, thinking it would never risk updating other pods because they are fixed to a specific version in the Podfile
.
But in fact, that is not enough to guarantee that user1 and user2 in our above scenario will always get the exact same version of all their pods.
One typical example is if the pod A
has a dependency on pod A2
— declared in A.podspec
as dependency 'A2', '~> 3.0'
. In such case, using pod 'A', '1.0.0'
in your Podfile will indeed force user1 and user2 to both always use version 1.0.0 of the pod A, but:
A2
in version 3.4
(because that was A2
's latest version at that time)pod install
when joining the project later, they might get pod A2
in version 3.5
(because the maintainer of A2
might have released a new version in the meantime).
That's why the only way to ensure every team member work with the same versions of all the pod on each's the computer is to use the Podfile.lock
and properly use pod install
vs. pod update
.The above excerpt was all derived from pod install vs. pod update
I also highly recommend watching what does a podfile.lock
do
Try this code, Let $ be defined
(function ($, Drupal) {
'use strict';
Drupal.behaviors.module_name = {
attach: function (context, settings) {
jQuery(document).ready(function($) {
$("#search_text").autocomplete({
source:results,
minLength:2,
position: { offset:'-30 0' },
select: function(event, ui ) {
goTo(ui.item.value);
return false;
}
});
});
}
};
})(jQuery, Drupal);
Create an Ant file and tell Eclipse to build it. There are only two steps and each is easy with the step-by-step instructions below.
Step 1 Create a build.xml file and add to package explorer:
<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file -->
<project name="TestMain" default="CreateJar">
<target name="CreateJar" description="Create Jar file">
<jar jarfile="Test.jar" basedir="." includes="*.class" />
</target>
</project>
Eclipse should looks something like the screenshot below. Note the Ant icon on build.xml.
Step 2 Right-click on the root node in the project. - Select Properties - Select Builders - Select New - Select Ant Build - In the Main tab, complete the path to the build.xml file in the bin folder.
Check the Output
The Eclipse output window (named Console) should show the following after a build:
Buildfile: /home/<user>/src/Test/build.xml
CreateJar:
[jar] Building jar: /home/<user>/src/Test/Test.jar
BUILD SUCCESSFUL
Total time: 152 milliseconds
EDIT: Some helpful comments by @yeoman and @betlista
@yeoman I think the correct include would be /.class, not *.class, as most people use packages and thus recursive search for class files makes more sense than flat inclusion
@betlista I would recomment to not to have build.xml in src folder