I am proposing my idea about it against any disadvantages array_values( )
function, because I think that is not a direct get function.
In this way it have to create a copy of the values numerically indexed array and then access. If PHP does not hide a method that automatically translates an integer in the position of the desired element, maybe a slightly better solution might consist of a function that runs the array with a counter until it leads to the desired position, then return the element reached.
So the work would be optimized for very large array of sizes, since the algorithm would be best performing indices for small, stopping immediately. In the solution highlighted of array_values( )
, however, it has to do with a cycle flowing through the whole array, even if, for e.g., I have to access $ array [1].
function array_get_by_index($index, $array) {
$i=0;
foreach ($array as $value) {
if($i==$index) {
return $value;
}
$i++;
}
// may be $index exceedes size of $array. In this case NULL is returned.
return NULL;
}
You can use that for string Enum
public enum EnumTest {
NAME_ONE("Name 1"),
NAME_TWO("Name 2");
private final String name;
/**
* @param name
*/
private EnumTest(final String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And call from main method
public class Test {
public static void main (String args[]){
System.out.println(EnumTest.NAME_ONE.getName());
System.out.println(EnumTest.NAME_TWO.getName());
}
}
Installing nodejs will install npm ... so just remove nodejs then reinstall it: $ sudo apt-get remove nodejs
$ sudo apt-get --purge remove nodejs node npm
$ sudo apt-get clean
$ sudo apt-get autoclean
$ sudo apt-get -f install
$ sudo apt-get autoremove
Check with "uname -a" and/or "lsb_release -a" to see which version of Linux you are actually running on your AWS instance. The default Amazon AMI image uses YUM for its package manager.
As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.
For example:
Assume we have double _bmi;
and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:
String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}
or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.
Use -Xms1024m -Xmx1024m to control your heap size (1024m is only for demonstration, the exact number depends your system memory). Setting minimum and maximum heap size to the same is usually a best practice since JVM doesn't have to increase heap size at runtime.
This simple(st) solution doesn't provide indentation, but it is nevertheless much easier on the human eye. Also it allows the xml to be handled more easily by simple tools like grep, head, awk, etc.
Use sed
to replace '<' with itself preceeded with a newline.
And as mentioned by Gilles, it's probably not a good idea to use this in production.
# check you are getting more than one line out
sed 's/</\n</g' sample.xml | wc -l
# check the output looks generally ok
sed 's/</\n</g' sample.xml | head
# capture the pretty xml in a different file
sed 's/</\n</g' sample.xml > prettySample.xml
Try replacing this
var query = context.Search(id, searchText);
with
var query = context.Search(id, searchText).tolist();
and everything will work well.
The reason why you get your error is because a "1 by n" matrix is different from an array of length n.
I recommend using hstack()
and vstack()
instead.
Like this:
import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:] # last column of that matrix.
result = np.hstack((a,b)) # stack them horizontally like this:
#array([[ 0, 1, 2, 3, 4, 5, 6, 7, 7],
# [ 8, 9, 10, 11, 12, 13, 14, 15, 15],
# [16, 17, 18, 19, 20, 21, 22, 23, 23],
# [24, 25, 26, 27, 28, 29, 30, 31, 31]])
Notice the repeated "7, 15, 23, 31" column.
Also, notice that I used a[:,-1:]
instead of a[:,-1]
. My version generates a column:
array([[7],
[15],
[23],
[31]])
Instead of a row array([7,15,23,31])
Edit: append()
is much slower. Read this answer.
Not PIL, but imageio.imread
might still be interesting:
import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So the pixel at position (x, y)
is
color = tuple(im[y][x])
r, g, b = color
scipy.misc.imread
is deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr!)
<html>
<head>
<script type="text/javascript">
function prepHref(linkElement) {
var myDiv = document.getElementById('Div_contain_image');
var myImage = myDiv.children[0];
linkElement.href = myImage.src;
}
</script>
</head>
<body>
<div id="Div_contain_image"><img src="YourImage.jpg" alt='MyImage'></div>
<a href="#" onclick="prepHref(this)" download>Click here to download image</a>
</body>
</html>
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
I came across this question when I was trying similar things.
A very nice and simple sample is presented at w3schools website.
https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Modal Example</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Extending Jianxun's answer, using set_value
mehtod in pandas. It sets value for a column at given index.
From pandas documentations:
DataFrame.set_value(index, col, value)
To set value at particular index for a column, do:
df.set_value(index, 'COL_NAME', x)
Hope it helps.
I can confirm that I have the same bug on Windows 7 using Chrome Version 35 but I share my partial solution who is open a new tab on Chrome and showing a dialog.
For other browser when the user click on cancel automatically close the new print window.
//Chrome's versions > 34 is some bug who stop all javascript when is show a prints preview
//http://stackoverflow.com/questions/23071291/javascript-window-print-in-chrome-closing-new-window-or-tab-instead-of-cancel
if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
var popupWin = window.open();
popupWin.window.focus();
popupWin.document.write('<!DOCTYPE html><html><head>' +
'<link rel="stylesheet" type="text/css" href="style.css" />' +
'</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></html>');
popupWin.onbeforeunload = function (event) {
return 'Please use the cancel button on the left side of the print preview to close this window.\n';
};
}else {
var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
popupWin.document.write('<!DOCTYPE html><html><head>' +
'<link rel="stylesheet" type="text/css" href="style.css" />' +
'</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div>' +
'<script>setTimeout(function(){ window.parent.focus(); window.close() }, 100)</script></html>');
}
popupWin.document.close();
The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.
When working to create Cross Browser Favicons (including touch icons) there are several things to consider.
The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->
To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon"
for IE to recognize the icon it needs the word shortcut
which is not standard. Also we wrap the .ico
favicon in a IE conditional comment because Chrome and Safari will use the .ico
file if it is present, despite other options available, not what we would like.
The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.
For the rest of the browsers we are going to use the standard way to cite a favicon:
<link rel="icon" href="path/to/favicon.png">
This icon should be 196x196 pixels in size to cover all devices that may use this icon.
To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
Using rel="apple-touch-icon-precomposed"
will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon"
. This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed"
.
As a note: Chrome for Android states:
The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).
Custom Tiles for IE 11+ on Windows 8.1+
IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.
Microsoft recommends creating a few tiles at the following size:
Small: 128 x 128
Medium: 270 x 270
Wide: 558 x 270
Large: 558 x 558
These should be transparent images as we will define a color background next.
Once these images are created you should create an xml file called browserconfig.xml
with the following code:
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square70x70logo src="images/smalltile.png"/>
<square150x150logo src="images/mediumtile.png"/>
<wide310x150logo src="images/widetile.png"/>
<square310x310logo src="images/largetile.png"/>
<TileColor>#009900</TileColor>
</tile>
</msapplication>
</browserconfig>
Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head
:
<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />
For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.
Putting it all together:
To put it all together the above code would look like this:
<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->
<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. -->
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">
Windows Phone Live Tiles
If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:
Here are detailed instructions from Microsoft but here is a synopsis:
Step 1
Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.
Step 2
Add a hidden overlay of this image. Here is example code from Microsoft:
<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
<img src="customtile.png" width="320" height="320" />
<div style='margin-top: 40px'>
Add text/graphic asking user to pin to start using the menu...
</div>
</div>
Step 3
You then can add thew following line to add a pin to start link:
<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>
Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.
Step 4
Next you add some JS to toggle the overlay visibility
<script>
function ToggleTileOverlay() {
var newVisibility = (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
document.getElementById('TileOverlay').style.visibility = newVisibility;
}
</script>
Note on Sizes
I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.
Further Reading
For those who would like more details see the links below:
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
Put the UNIQUE declaration within the column definition section; working example:
CREATE TABLE a (
i INT,
j INT,
UNIQUE(i, j) ON CONFLICT REPLACE
);
Yes, you can use the native javascript Date() object and its methods.
For instance you can create a function like:
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
And display also the am / pm and the correct time.
Remember to use getFullYear() method and not getYear() because it has been deprecated.
I believe that, if you need to use the %20
variant, you could perhaps use rawurlencode()
.
Simply place this on a new line in .gitignore
**/.DS_Store
From git documentation
- A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".
If you have troubles with hotkeys, try to open Key Binding Resolver Window
with Cmd + .. It will show you keys you're pressing in the realtime.
For example, Cmd + Shift + ' is actually Cmd + "
Java doesn't have delegates and is proud of it :). From what I read here I found in essence 2 ways to fake delegates: 1. reflection; 2. inner class
Reflections are slooooow! Inner class does not cover the simplest use-case: sort function. Do not want to go into details, but the solution with inner class basically is to create a wrapper class for an array of integers to be sorted in ascending order and an class for an array of integers to be sorted in descending order.
You can consider shapely:
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
print(polygon.contains(point))
From the methods you've mentioned I've only used the second, path.contains_points
, and it works fine. In any case depending on the precision you need for your test I would suggest creating a numpy bool grid with all nodes inside the polygon to be True (False if not). If you are going to make a test for a lot of points this might be faster (although notice this relies you are making a test within a "pixel" tolerance):
from matplotlib import path
import matplotlib.pyplot as plt
import numpy as np
first = -3
size = (3-first)/100
xv,yv = np.meshgrid(np.linspace(-3,3,100),np.linspace(-3,3,100))
p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)]) # square with legs length 1 and bottom left corner at the origin
flags = p.contains_points(np.hstack((xv.flatten()[:,np.newaxis],yv.flatten()[:,np.newaxis])))
grid = np.zeros((101,101),dtype='bool')
grid[((xv.flatten()-first)/size).astype('int'),((yv.flatten()-first)/size).astype('int')] = flags
xi,yi = np.random.randint(-300,300,100)/100,np.random.randint(-300,300,100)/100
vflag = grid[((xi-first)/size).astype('int'),((yi-first)/size).astype('int')]
plt.imshow(grid.T,origin='lower',interpolation='nearest',cmap='binary')
plt.scatter(((xi-first)/size).astype('int'),((yi-first)/size).astype('int'),c=vflag,cmap='Greens',s=90)
plt.show()
, the results is this:
I hope this function will be useful
function formatDate(dDate,sMode){
var today = dDate;
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
if (sMode+""==""){
sMode = "dd/mm/yyyy";
}
if (sMode == "yyyy-mm-dd"){
return yyyy + "-" + mm + "-" + dd + "";
}
if (sMode == "dd/mm/yyyy"){
return dd + "/" + mm + "/" + yyyy;
}
}
System.out.println("...") in Java code is translated into JVM. Looking into the JVM gave me better understanding what is going on behind the hood.
From the book Programming form the Java Virtual Machine. This code is copied from https://github.com/ymasory/programming-for-the-jvm/blob/master/examples/HelloWorld.j.
This is the JVM source code.
.class public HelloWorld
.super java/lang/Object
.method public static main([Ljava/lang/String;)V
.limit stack 2
.limit locals 1
getstatic java/lang/System/out Ljava/io/PrintStream;
ldc "Hello, world"
invokevirtual java/io/PrintStream/println
(Ljava/lang/String;)V
return
.end method
.end class
As "The JVM doesn't permit byte-level access to memory" the out
object in type Ljava/io/PrintSteram
; is stored in a stack with getstatic
JVM command.
Then the argument is pushed on the stack before called a method println
of the java/io/PrintStream
class from an instance named out
. The method's parameter is (Ljava/lang/String
;) and output type is void (V).
I had parsing enum problem when i was trying to pass Nullable Enum that we get from Backend. Of course it was working when we get value, but it was problem when the null comes up.
java.lang.IllegalArgumentException: No enum constant
Also the problem was when we at Parcelize read moment write some short if.
My solution for this was
1.Create companion object with parsing method.
enum class CarsType {
@Json(name = "SMALL")
SMALL,
@Json(name = "BIG")
BIG;
companion object {
fun nullableValueOf(name: String?) = when (name) {
null -> null
else -> valueOf(name)
}
}
}
2. In Parcerable read place use it like this
data class CarData(
val carId: String? = null,
val carType: CarsType?,
val data: String?
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
CarsType.nullableValueOf(parcel.readString()),
parcel.readString())
The Java language specification says you can have return with no expression if your method returns void.
As others have pointed out, LEA (load effective address) is often used as a "trick" to do certain computations, but that's not its primary purpose. The x86 instruction set was designed to support high-level languages like Pascal and C, where arrays—especially arrays of ints or small structs—are common. Consider, for example, a struct representing (x, y) coordinates:
struct Point
{
int xcoord;
int ycoord;
};
Now imagine a statement like:
int y = points[i].ycoord;
where points[]
is an array of Point
. Assuming the base of the array is already in EBX
, and variable i
is in EAX
, and xcoord
and ycoord
are each 32 bits (so ycoord
is at offset 4 bytes in the struct), this statement can be compiled to:
MOV EDX, [EBX + 8*EAX + 4] ; right side is "effective address"
which will land y
in EDX
. The scale factor of 8 is because each Point
is 8 bytes in size. Now consider the same expression used with the "address of" operator &:
int *p = &points[i].ycoord;
In this case, you don't want the value of ycoord
, but its address. That's where LEA
(load effective address) comes in. Instead of a MOV
, the compiler can generate
LEA ESI, [EBX + 8*EAX + 4]
which will load the address in ESI
.
Here's a really nice and simple way of doing it with really easy to follow instructions using a custom MultiButtonAttribute:
To summarise, make your submit buttons like this:
<input type="submit" value="Cancel" name="action" />
<input type="submit" value="Create" name="action" />
Your actions like this:
[HttpPost]
[MultiButton(MatchFormKey="action", MatchFormValue="Cancel")]
public ActionResult Cancel()
{
return Content("Cancel clicked");
}
[HttpPost]
[MultiButton(MatchFormKey = "action", MatchFormValue = "Create")]
public ActionResult Create(Person person)
{
return Content("Create clicked");
}
And create this class:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public string MatchFormKey { get; set; }
public string MatchFormValue { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
return controllerContext.HttpContext.Request[MatchFormKey] != null &&
controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
}
}
Use the subprocess module as mentioned above.
I use it like this:
subprocess.call(["notepad"])
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!! Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
<asp:TextBox runat="server" ID="txtPassword" placeholder="Password">
This will work you might some time feel that it is not working due to Intellisence not showing placeholder
Your function worked for me after changing its declaration to this ...
Function processArr(Arr As Variant) As String
You could also consider a ParamArray
like this ...
Function processArr(ParamArray Arr() As Variant) As String
'Dim N As Variant
Dim N As Long
Dim finalStr As String
For N = LBound(Arr) To UBound(Arr)
finalStr = finalStr & Arr(N)
Next N
processArr = finalStr
End Function
And then call the function like this ...
processArr("foo", "bar")
If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample):
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx
And just in case you need the sample in a hurry, here it is in all its plagiarized glory:
using System;
using System.IO;
using System.Security.Cryptography;
namespace RijndaelManaged_Example
{
class RijndaelExample
{
public static void Main()
{
try
{
string original = "Here is some data to encrypt!";
// Create a new instance of the RijndaelManaged
// class. This generates a new key and initialization
// vector (IV).
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.GenerateKey();
myRijndael.GenerateIV();
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
This also does seem to work, although W3C specifies it is not intended "for an external (typically non-HTML) application or interactive content"
<embed src="http://www.somesite.com" width=200 height=200 />
More info: http://www.w3.org/wiki/HTML/Elements/embed http://www.w3schools.com/tags/tag_embed.asp
Note that in the Java implementation, the number of bits to shift is mod'd by the size of the source.
For example:
(long) 4 >> 65
equals 2. You might expect shifting the bits to the right 65 times would zero everything out, but it's actually the equivalent of:
(long) 4 >> (65 % 64)
This is true for <<, >>, and >>>. I have not tried it out in other languages.
You are missing the @Id
entity property, and that's why Hibernate is throwing that exception.
Any JPA entity must have an identifier property, that is marked with the Id
annotation.
There are two types of identifiers:
An assigned identifier looks as follows:
@Id
private Long id;
Notice that we are using a wrapper (e.g.,
Long
,Integer
) instead of a primitive type (e.g.,long
,int
). Using a wrapper type is a better choice when using Hibernate because, by checking if theid
isnull
or not, Hibernate can better determine if an entity is transient (it does not have an associated table row) or detached (it has an associated table row, but it's not managed by the current Persistence Context).
The assigned identifier must be set manually by the application prior to calling persist:
Post post = new Post();
post.setId(1L);
entityManager.persist(post);
An auto-generated identifier requires the @GeneratedValue
annotation besides the @Id
:
@Id
@GeneratedValue
private int id;
There are 3 strategies Hibernate can use to auto-generate the entity identifier:
IDENTITY
SEQUENCE
TABLE
The IDENTITY
strategy is to be avoided if the underlying database supports sequences (e.g., Oracle, PostgreSQL, MariaDB since 10.3, SQL Server since 2012). The only major database that does not support sequences is MySQL.
The problem with
IDENTITY
is that automatic Hibernate batch inserts are disabled for this strategy.
The SEQUENCE
strategy is the best choice unless you are using MySQL. For the SEQUENCE
strategy, you also want to use the pooled
optimizer to reduce the number of database roundtrips when persisting multiple entities in the same Persistence Context.
The TABLE
generator is a terrible choice because it does not scale. For portability, you are better off using SEQUENCE
by default and switch to IDENTITY
for MySQL only.
Put your code inside the try catch block: i.e :
try{
if(in.available()!=0){
// ------
}
}catch(EOFException eof){
//
}catch(Exception e){
//
}
}
You can't do that in Javascript from the browser... If I were you, I would use something like browserify. Write your code using commonjs modules and then compile the javascript file into one.
In your html load the javascript file that you compiled.
$('input[type=file]').change(function(e){
$(this).parents('.parent-selector').find('.element-to-paste-filename').text(e.target.files[0].name);
});
This code will not show C:\fakepath\
before file name in Google Chrome in case of using .val()
.
If you have error while installing PyQt4.
Error: PyQt4-4.11.4-cp27-cp27m-win_amd64.whl is not a supported wheel on this platform.
My system type is 64 bit, But to solve this error I have installed PyQt4 of 32 bit windows system, i.e PyQt4-4.11.4-cp27-cp27m-win32.whl - click here to see more versions.
Kindly select appropriate version of PyQt4 according to your installed python version.
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
Yes, it is possible by using a simple custom pipe. Advantage of using custom pipe is if we need to update the date format in future, we can go and update a single file.
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {
transform(value: string) {
var datePipe = new DatePipe("en-US");
value = datePipe.transform(value, 'MMM-dd-yyyy');
return value;
}
}
{{currentDate | dateFormatPipe }}
You can always use this pipe anywhere , component, services etc
For example:
export class AppComponent {
currentDate : any;
newDate : any;
constructor(){
this.currentDate = new Date().getTime();
let dateFormatPipeFilter = new dateFormatPipe();
this.newDate = dateFormatPipeFilter.transform(this.currentDate);
console.log(this.newDate);
}
Don't forget to import dependencies.
import { Component } from '@angular/core';
import {dateFormatPipe} from './pipes'
"final" guarantees that a variable must be initialized before end of object initializer code. Likewise "static final" guarantees that a variable will be initialized by the end of class initialization code. Omitting the "static" from your initialization code turns it into object initialization code; thus your variable no longer satisfies its guarantees.
The solution is to use display: table-cell
to bring those elements inline instead of using display: inline-block
or float: left
.
div#container {_x000D_
padding: 20px;_x000D_
background: #F1F1F1_x000D_
}_x000D_
.content {_x000D_
width: 150px;_x000D_
background: #ddd;_x000D_
padding: 10px;_x000D_
display: table-cell;_x000D_
vertical-align: top;_x000D_
}_x000D_
.text {_x000D_
font-family: 12px Tahoma, Geneva, sans-serif;_x000D_
color: #555;_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="content">_x000D_
<h1>Title 1</h1>_x000D_
_x000D_
<div class="text">Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text._x000D_
<br>Sample Text. Sample Text. Sample Text._x000D_
<br>Sample Text._x000D_
<br>_x000D_
</div>_x000D_
</div>_x000D_
<div class="content">_x000D_
<h1>Title 2</h1>_x000D_
_x000D_
<div class="text">Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text.</div>_x000D_
</div>_x000D_
</div>
_x000D_
On cpanel -> software and services -> Select PHP Version.
Choose a PHP version which not the native one (I recommend php 5.6 or last one) and you will have / see a new link "Switch To PHP Settings", click it, in PHP Settings you can set upload_max_filesize in last line , clicking on value ( default is 2M ) , and you got a dropbox with values that you can set to upload_max_filesize, and click save .
following commands will do the same perfectly
rm -rf vendor
composer install
Was looking for a way to do this using simple xml
, but couldn't find any helpful answers, so came up with this.
This works on pre-lollipop versions too, and is pretty close to the material design progress bar. You just need to use this drawable
as the indeterminate drawable
in the ProgressBar
layout.
<?xml version="1.0" encoding="utf-8"?><!--<layer-list>-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360">
<layer-list>
<item>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="-90"
android:toDegrees="-90">
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thickness="2dp"
android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
<gradient
android:angle="0"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
</item>
<item>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.6"
android:shape="ring"
android:thickness="4dp"
android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
<gradient
android:angle="0"
android:centerColor="#FFF"
android:endColor="#FFF"
android:startColor="#FFF"
android:useLevel="false" />
</shape>
</rotate>
</item>
</layer-list>
</rotate>
set the above drawable in ProgressBar as follows:
android:indeterminatedrawable="@drawable/above_drawable"
Just change the version of opencv to 3.4.2.16 .Since it is patented it is not available in newer version.
In my case I had the following warnings:
Could not resolve this reference. Could not locate the assembly "x". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
No way to resolve conflict between "x, Version=1.0.0.248, Culture=neutral, PublicKeyToken=null" and "x". Choosing "x, Version=1.0.0.248
The path to the dll was correct in my .csproj file but I had it referenced twice and the second reference was with another version. Once I deleted the unnecessary reference, the warning disappeared.
git commit -m "first commit"
git remote add origin <linkyourrepository>
git push -u origin master
will works!
To get the numbers after decimal point, you can do this:-
read num1 num2
div=`echo $num1 / $num2 | bc -l`
echo $div
<a href="index.html">_x000D_
<button type="button">Submit</button>_x000D_
</a>
_x000D_
<button type="submit" onclick="myFunction()">Submit</button>_x000D_
<script>_x000D_
function myFunction() {_x000D_
var w = window.open(file:///E:/Aditya%20panchal/index.html);_x000D_
}_x000D_
</script>
_x000D_
' Create an HTTP object
myURL = "http://www.google.com"
Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )
' Download the specified URL
objHTTP.Open "GET", myURL, False
objHTTP.Send
intStatus = objHTTP.Status
If intStatus = 200 Then
WScript.Echo " " & intStatus & " A OK " +myURL
Else
WScript.Echo "OOPS" +myURL
End If
then
C:\>cscript geturl.vbs
Microsoft (R) Windows Script Host Version 5.7
Copyright (C) Microsoft Corporation. All rights reserved.
200 A OK http://www.google.com
or just double click it to test in windows
I had these SQL behavior settings enabled on options query execution: ANSI SET IMPLICIT_TRANSACTIONS checked. On execution of your query e.g create, alter table or stored procedure, you have to COMMIT it.
Just type COMMIT and execute it F5
Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
Here is another way to change the text of a label using jQuery:
<script>
$("#lbltipAddedComment").text("your tip has been submitted!");
</script>
Check the JsFiddle example
ls -sh video.mp4 | sed s/video.mp4//g
output, 5.6M
Is it possible the root password is not what you think it is? Have you checked the file /root/.mysql_secret for the password? That is the default location for the automated root password that is generated from starting from version 5.7.
cat /root/.mysql_secret
Make sure that the keys you use to encrypt and decrypt are the same. The padding method even if not explicitly set should still allow for proper decryption/encryption (if not set they will be the same). However if you for some reason are using a different set of keys for decryption than used for encryption you will get this error:
Padding is invalid and cannot be removed
If you are using some algorithm to dynamically generate keys that will not work. They need to be the same for both encryption and decryption. One common way is to have the caller provide the keys in the constructor of the encryption methods class, to prevent the encryption/decryption process having any hand in creation of these items. It focuses on the task at hand (encrypting and decrypting data) and requires the iv
and key
to be supplied by the caller.
I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded. I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});
Dependencies.
var fs = require('fs');
var path = require('path');
Definition.
// String -> [String]
function fileList(dir) {
return fs.readdirSync(dir).reduce(function(list, file) {
var name = path.join(dir, file);
var isDir = fs.statSync(name).isDirectory();
return list.concat(isDir ? fileList(name) : [name]);
}, []);
}
Usage.
var DIR = '/usr/local/bin';
// 1. List all files in DIR
fileList(DIR);
// => ['/usr/local/bin/babel', '/usr/local/bin/bower', ...]
// 2. List all file names in DIR
fileList(DIR).map((file) => file.split(path.sep).slice(-1)[0]);
// => ['babel', 'bower', ...]
Please note that fileList
is way too optimistic. For anything serious, add some error handling.
I've tried Greg's answer with zero success, I must have done something wrong since my database had no data after all the steps: I was using MariaDB's latest image, just in case.
Then I decided to read the entrypoint for the official MariaDB image, and used that to generate a simple docker-compose file:
database:
image: mariadb
ports:
- 3306:3306
expose:
- 3306
volumes:
- ./docker/mariadb/data:/var/lib/mysql:rw
- ./database/schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro
environment:
MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
Now I'm able to persist my data AND generate a database with my own schema!
I found a reason about using decimal over money in accuracy subject.
DECLARE @dOne DECIMAL(19,4),
@dThree DECIMAL(19,4),
@mOne MONEY,
@mThree MONEY,
@fOne FLOAT,
@fThree FLOAT
SELECT @dOne = 1,
@dThree = 3,
@mOne = 1,
@mThree = 3,
@fOne = 1,
@fThree = 3
SELECT (@dOne/@dThree)*@dThree AS DecimalResult,
(@mOne/@mThree)*@mThree AS MoneyResult,
(@fOne/@fThree)*@fThree AS FloatResult
Just test it and make your decision.
Clustered Index - A clustered index defines the order in which data is physically stored in a table. Table data can be sorted in only way, therefore, there can be only one clustered index per table. In SQL Server, the primary key constraint automatically creates a clustered index on that particular column.
Non-Clustered Index - A non-clustered index doesn’t sort the physical data inside the table. In fact, a non-clustered index is stored at one place and table data is stored in another place. This is similar to a textbook where the book content is located in one place and the index is located in another. This allows for more than one non-clustered index per table.It is important to mention here that inside the table the data will be sorted by a clustered index. However, inside the non-clustered index data is stored in the specified order. The index contains column values on which the index is created and the address of the record that the column value belongs to.When a query is issued against a column on which the index is created, the database will first go to the index and look for the address of the corresponding row in the table. It will then go to that row address and fetch other column values. It is due to this additional step that non-clustered indexes are slower than clustered indexes
Differences between clustered and Non-clustered index
For more information refer to this article.
Let maven generate a batch file to start your application. This is the simplest way to this.
You can use the appassembler-maven-plugin for such purposes.
This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.
So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader
instance. Any time you are creating a Reader
from an InputStream
, you need to specify the character encoding, or java.nio.charset.Charset
instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8
). If you don't specify a Charset
, Java will use your platform default encoding, which on Windows is usually CP-1252.
Add line break to ::after
or ::before
pseudo-element content
.yourclass:before {
content: 'text here first \A text here second';
white-space: pre;
}
I just installed MySQL Server 5.7
on Windows 10
and my.ini
file is located here c:\ProgramData\MySQL\MySQL Server 5.7\my.ini
.
The Data
folder (where your dbs are created) is here C:/ProgramData/MySQL/MySQL Server 5.7\Data
.
You can use Coil library to load svg. Just add these lines in build.gradle
// ... Coil (https://github.com/coil-kt/coil)
implementation("io.coil-kt:coil:0.12.0")
implementation("io.coil-kt:coil-svg:0.12.0")
Then Add an extension function
fun AppCompatImageView.loadSvg(url: String) {
val imageLoader = ImageLoader.Builder(this.context)
.componentRegistry { add(SvgDecoder([email protected])) }
.build()
val request = ImageRequest.Builder(this.context)
.crossfade(true)
.crossfade(500)
.data(url)
.target(this)
.build()
imageLoader.enqueue(request)
}
Then call this method in your activity or fragment
your_image_view.loadSvg("your_file_name.svg")
In my case this works fine...
sudo npm i -g browserslist caniuse-lite
You can also use numpy loadtxt like
from numpy import loadtxt
lines = loadtxt("filename.dat", comments="#", delimiter=",", unpack=False)
this can be done very easily with HTML 5, see this link http://www.html5rocks.com/en/tutorials/file/dndfiles/
You can achieved by use bootstrap Spacing. Bootstrap Spacing includes a wide range of shorthand responsive margin and padding. In below example mr-1
set the margin
or padding
to $spacer
* .25.
Example:
<button class="btn btn-outline-primary mr-1" href="#">Sign up</button>
<button class="btn btn-outline-primary" href="#">Login</button>
You can read more at Bootstrap Spacing.
int
is a primitive type. Variables of type int
store the actual binary value for the integer you want to represent. int.parseInt("1")
doesn't make sense because int
is not a class and therefore doesn't have any methods.
Integer
is a class, no different from any other in the Java language. Variables of type Integer
store references to Integer
objects, just as with any other reference (object) type. Integer.parseInt("1")
is a call to the static method parseInt
from class Integer
(note that this method actually returns an int
and not an Integer
).
To be more specific, Integer
is a class with a single field of type int
. This class is used where you need an int
to be treated like any other object, such as in generic types or situations where you need nullability.
Note that every primitive type in Java has an equivalent wrapper class:
byte
has Byte
short
has Short
int
has Integer
long
has Long
boolean
has Boolean
char
has Character
float
has Float
double
has Double
Wrapper classes inherit from Object class, and primitive don't. So it can be used in collections with Object reference or with Generics.
Since java 5 we have autoboxing, and the conversion between primitive and wrapper class is done automatically. Beware, however, as this can introduce subtle bugs and performance problems; being explicit about conversions never hurts.
This version is packed in a function that accepts a custom delimiter, filter, and returns a flat dictionary:
function flatten(source, delimiter, filter) {
var result = {}
;(function flat(obj, stack) {
Object.keys(obj).forEach(function(k) {
var s = stack.concat([k])
var v = obj[k]
if (filter && filter(k, v)) return
if (typeof v === 'object') flat(v, s)
else result[s.join(delimiter)] = v
})
})(source, [])
return result
}
var obj = {
a: 1,
b: {
c: 2
}
}
flatten(obj)
// <- Object {a: 1, b.c: 2}
flatten(obj, '/')
// <- Object {a: 1, b/c: 2}
flatten(obj, '/', function(k, v) { return k.startsWith('a') })
// <- Object {b/c: 2}
You have to add a MySQL jdbc driver to the classpath.
Either put a MySQL binary jar to tomcat lib folder or add it to we application WEB-INF/lib folder.
You can find binary jar (Change version accordingly): https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.27
Mongoose 4.4.0 introduces --true-- bulk insert with the model method .insertMany()
. It is way faster than looping on .create()
or providing it with an array.
Usage:
var rawDocuments = [/* ... */];
Book.insertMany(rawDocuments)
.then(function(mongooseDocuments) {
/* ... */
})
.catch(function(err) {
/* Error handling */
});
Or
Book.insertMany(rawDocuments, function (err, mongooseDocuments) { /* Your callback function... */ });
You can track it on:
You're calling e.nextElement()
twice inside your loop when you're only guaranteed that you can call it once without an exception. Rewrite the loop like so:
while(e.hasMoreElements()){
String param = e.nextElement();
System.out.println(param);
}
Assuming your page is available under "http://example.com"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://example.com")
Select element by id:
inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')
Now you can simulate hitting ENTER:
inputElement.send_keys(Keys.ENTER)
or if it is a form you can submit:
inputElement.submit()
Another issue could be with your dev-dependencies. Please check if they have been installed properly (check if they are availabe in the node_modules folder)
If not then a quick fix would be:
npm i --only=dev
Or check how your npm settings are regarding prod:
npm config get production
In case they are set to true - change them to false:
npm config set -g production false
and setup a new angular project.
Found that hint here: https://github.com/angular/angular-cli/issues/10661 (ken107 and lichunbin814)
Hope that helps.
This kind of problems can be easy solved by dictionaries (HashMap in Java).
// The solution itself
HashMap<Integer, Integer> repetitions = new HashMap<Integer, Integer>();
for (int i = 0; i < crr_array.length; ++i) {
int item = crr_array[i];
if (repetitions.containsKey(item))
repetitions.put(item, repetitions.get(item) + 1);
else
repetitions.put(item, 1);
}
// Now let's print the repetitions out
StringBuilder sb = new StringBuilder();
int overAllCount = 0;
for (Map.Entry<Integer, Integer> e : repetitions.entrySet()) {
if (e.getValue() > 1) {
overAllCount += 1;
sb.append("\n");
sb.append(e.getKey());
sb.append(": ");
sb.append(e.getValue());
sb.append(" times");
}
}
if (overAllCount > 0) {
sb.insert(0, " repeated numbers:");
sb.insert(0, overAllCount);
sb.insert(0, "There are ");
}
System.out.print(sb.toString());
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
@Zelazny7's answer works, but if you want to keep ties you could do:
df[which(df$Amount == min(df$Amount)), ]
For example with the following data frame:
df <- data.frame(Name = c("A", "B", "C", "D", "E"),
Amount = c(150, 120, 175, 160, 120))
df[which.min(df$Amount), ]
# Name Amount
# 2 B 120
df[which(df$Amount == min(df$Amount)), ]
# Name Amount
# 2 B 120
# 5 E 120
Edit: If there are NAs in the Amount
column you can do:
df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]
Spring has built-in support for this with an AbstractRequestLoggingFilter
:
@Bean
public Filter loggingFilter(){
final AbstractRequestLoggingFilter filter = new AbstractRequestLoggingFilter() {
@Override
protected void beforeRequest(final HttpServletRequest request, final String message) {
}
@Override
protected void afterRequest(final HttpServletRequest request, final String message) {
}
};
filter.setIncludePayload(true);
filter.setIncludeQueryString(false);
filter.setMaxPayloadLength(1000000);
return filter;
}
Unfortunately you still won't be able to read the payload directly off the request, but the String message parameter will include the payload so you can grab it from there as follows:
String body = message.substring(message.indexOf("{"), message.lastIndexOf("]"));
Simply use Contains method. Note that it works based on the equality function Equals
bool alreadyExist = list.Contains(item);
int? nullableValue = null;
object nullableValueDB
{
get{
if(nullableValue==null)
return DBNull.Value;
else
return (int)nullableValue;
}
}
I'm solving like that.
You need to remove your submodule git repository (projectfolder in this case) first for git path.
rm -rf projectfolder
git rm -r projectfolder
and then add submodule
git submodule add <git_submodule_repository> projectfolder
If you're only running the commands in one shot then you can just use subprocess.check_output
convenience function:
def subprocess_cmd(command):
output = subprocess.check_output(command, shell=True)
print output
When using TypeScript, the default tab width is always two regardless of what it says in the toolbar. You have to set "prettier.tabWidth" in your user settings to change it.
Ctrl + P, Type ? user settings, add:
"prettier.tabWidth": 4
I had run into the similar problem recently, and managed to fix it with adding classes
body .btn-primary {
background-color: #7bc143;
border-color: #7bc143;
color: #FFF; }
body .btn-primary:hover, body .btn-primary:focus {
border-color: #6fb03a;
background-color: #6fb03a;
color: #FFF; }
body .btn-primary:active, body .btn-primary:visited, body .btn-primary:active:focus, body .btn-primary:active:hover {
border-color: #639d34;
background-color: #639d34;
color: #FFF; }
Also pay attention to [disabled] and [disabled]:hover, if this class is used on input[type=submit]. Like this:
body .btn-primary[disabled], body .btn-primary[disabled]:hover {
background-color: #7bc143;
border-color: #7bc143; }
SQL is a standard and there are many database vendors like Microsoft,Oracle who implements this standard using their own proprietary language.
Microsoft uses T-SQL to implement SQL standard to interact with data whereas oracle uses PL/SQL.
This is more a comment to previous Thomas Mueller's post rather than an answer, but haven't got enough reputation for it. Another way of getting the connection if you are Spring JDBC Template is using the following:
jdbcTemplate.getDataSource().getConnection();
So on debug mode if you add to the "Expressions" view in Eclipse it will open the browser showing you the H2 Console:
org.h2.tools.Server.startWebServer(jdbcTemplate.getDataSource().getConnection());
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}
... prints -2
and 12
.
-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \
as \\
in a Java String though. So, \d+ matches 1 or more digits.
Hello
you can use WordGenerator or LoremIpsumGenerator from MMLib.RapidPrototyping nuget package.
using MMLib.RapidPrototyping.Generators;
public void WordGeneratorExample()
{
WordGenerator generator = new WordGenerator();
var randomWord = generator.Next();
Console.WriteLine(randomWord);
}
The w
and h
variables in img.onload
function are not in the same scope with those in the getMeta()
function. One way to do it, is as follows:
Fiddle: http://jsfiddle.net/ppanagi/28UES/2/
function getMeta(varA, varB) {
if (typeof varB !== 'undefined') {
alert(varA + ' width ' + varB + ' height');
} else {
var img = new Image();
img.src = varA;
img.onload = getMeta(this.width, this.height);
}
}
getMeta("http://snook.ca/files/mootools_83_snookca.png");
Here is a nice and simple way to do it (but on CENTOS), without braking the operating system.
yum install scl-utils
next
yum install centos-release-scl-rh
And lastly you install the version that you want, lets say python3.5
yum install rh-python35
And lastly:
scl enable rh-python35 bash
Since MAC-OS is a unix operating system, the way to do it it should be quite similar.
And in addition to the above nice answers.
RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.
Maybe the OrderedDictonary will help you out.
I ran into the same problem and was able to resolve it in very powerful way that allows unlimited sorting possibilities.
I created a View using (saving) 2 sort orders (*explanation on how to do so below).
After that I simply applied the update queries to the View created and it worked great.
Here are the 2 queries I used on the view:
1st Query:
Update MyView
Set SortID=0
2nd Query:
DECLARE @sortID int
SET @sortID = 0
UPDATE MyView
SET @sortID = sortID = @sortID + 1
*To be able to save the sorting on the View I put TOP into the SELECT statement. This very useful workaround allows the View results to be returned sorted as set when the View was created when the View is opened. In my case it looked like:
(NOTE: Using this workaround will place an big load on the server if using a large table and it is therefore recommended to include as few fields as possible in the view if working with large tables)
SELECT TOP (600000)
dbo.Items.ID, dbo.Items.Code, dbo.Items.SortID, dbo.Supplier.Date,
dbo.Supplier.Code AS Expr1
FROM dbo.Items INNER JOIN
dbo.Supplier ON dbo.Items.SupplierCode = dbo.Supplier.Code
ORDER BY dbo.Supplier.Date, dbo.Items.ID DESC
Running: SQL Server 2005 on a Windows Server 2003
Additional Keywords: How to Update a SQL column with Ascending or Descending Numbers - Numeric Values / how to set order in SQL update statement / how to save order by in sql view / increment sql update / auto autoincrement sql update / create sql field with ascending numbers
Use blur event to call your function when element loses focus :
$('#filter').blur(function() {
$('#options').hide();
});
http://www.htmlgoodies.com/beyond/php/show-progress-report-for-long-running-php-scripts.html
I was searching for a similar solution and found this one use full.
var es;
function startTask() {
es = new EventSource('yourphpfile.php');
//a message is received
es.addEventListener('message', function(e) {
var result = JSON.parse( e.data );
console.log(result.message);
if(e.lastEventId == 'CLOSE') {
console.log('closed');
es.close();
var pBar = document.getElementById('progressor');
pBar.value = pBar.max; //max out the progress bar
}
else {
console.log(response); //your progress bar action
}
});
es.addEventListener('error', function(e) {
console.log('error');
es.close();
});
}
and your server outputs
header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
function send_message($id, $message, $progress) {
$d = array('message' => $message , 'progress' => $progress); //prepare json
echo "id: $id" . PHP_EOL;
echo "data: " . json_encode($d) . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
//LONG RUNNING TASK
for($i = 1; $i <= 10; $i++) {
send_message($i, 'on iteration ' . $i . ' of 10' , $i*10);
sleep(1);
}
send_message('CLOSE', 'Process complete');
As mentioned by other folks, the variable length of the string is the issue.
Rather than reinventing the wheel, Apache Commons has a nice, clean solution for this in StringUtils.
StringUtils.rightPad("String to extend",100); //100 is the length you want to pad out to.
You can do it the following way:
DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit
OR
CurrentDb.OpenRecordset("yourQueryName")
How about JsonConvert.DeserializeObject(object.ToString());
I found that the answer by cballou was no longer working in Firefox as of Jan. 2014. Specifically, if (self.pageYOffset)
didn't trigger if the client had scrolled right, but not down - because 0
is a falsey number. This went undetected for a while because Firefox supported document.body.scrollLeft
/Top
, but this is no longer working for me (on Firefox 26.0).
Here's my modified solution:
var getPageScroll = function(document_el, window_el) {
var xScroll = 0, yScroll = 0;
if (window_el.pageYOffset !== undefined) {
yScroll = window_el.pageYOffset;
xScroll = window_el.pageXOffset;
} else if (document_el.documentElement !== undefined && document_el.documentElement.scrollTop) {
yScroll = document_el.documentElement.scrollTop;
xScroll = document_el.documentElement.scrollLeft;
} else if (document_el.body !== undefined) {// all other Explorers
yScroll = document_el.body.scrollTop;
xScroll = document_el.body.scrollLeft;
}
return [xScroll,yScroll];
};
Tested and working in FF26, Chrome 31, IE11. Almost certainly works on older versions of all of them.
I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified
dataType: "json"
once I did, unlike the "accepted answer", that actually fixed the problem.
Ctrl + Shift + P Duplicate Workspace in New Window Enter
from: https://code.visualstudio.com/updates/v1_24#_duplicate-workspace-in-new-window
if(navigator.app){
navigator.app.exitApp();
}else if(navigator.device){
navigator.device.exitApp();
}
Use extra memory to do this. That way you can solve it with less time complexity, O(n) instead of o(n*n).
function getDiff(arr1,arr2){
let k = {};
let diff = []
arr1.map(i=>{
if (!k.hasOwnProperty(i)) {
k[i] = 1
}
}
)
arr2.map(j=>{
if (!k.hasOwnProperty(j)) {
k[j] = 1;
} else {
k[j] = 2;
}
}
)
for (var i in k) {
if (k[i] === 1)
diff.push(+i)
}
return diff
}
getDiff([4, 3, 52, 3, 5, 67, 9, 3],[4, 5, 6, 75, 3, 334, 5, 5, 6])
io.js has an exit
and a beforeExit
event, which do what you want.
create_table :you_table_name do |t| t.references :studant, index: { name: 'name_for_studant_index' } t.references :teacher, index: { name: 'name_for_teacher_index' } end
A scalar always holds a single element. Whatever is in a scalar variable is always a scalar. A reference is a scalar value.
If you want to know if it is a reference, you can use ref
. If you want to know the reference type,
you can use the reftype
routine from Scalar::Util.
If you want to know if it is an object, you can use the blessed
routine from Scalar::Util. You should never care what the blessed package is, though. UNIVERSAL
has some methods to tell you about an object: if you want to check that it has the method you want to call, use can
; if you want to see that it inherits from something, use isa
; and if you want to see it the object handles a role, use DOES
.
If you want to know if that scalar is actually just acting like a scalar but tied to a class, try tied
. If you get an object, continue your checks.
If you want to know if it looks like a number, you can use looks_like_number
from Scalar::Util. If it doesn't look like a number and it's not a reference, it's a string. However, all simple values can be strings.
If you need to do something more fancy, you can use a module such as Params::Validate.
Pretty late and not sure if this was available when the question was asked, set width: auto;
Seems to do the trick
In order to have have a less verbose code, and avoid name conflicts between datetime and datetime.datetime, you should rename the classes with CamelCase names.
from datetime import datetime as DateTime, timedelta as TimeDelta
So you can do the following, which I think it is clearer.
date_1 = DateTime.today()
end_date = date_1 + TimeDelta(days=10)
Also, there would be no name conflict if you want to import datetime
later on.
Assuming you know how big the item in the vector are:
std::vector<int> myArray;
myArray.resize (item_count, 0);
memcpy (&myArray.front(), source, item_count * sizeof(int));
Also you can use COALESCE instead of CASE expression. Because result of concatenating anything to NULL, even itself, is always NULL
INSERT TblStuff(FullName,Address,City,Zip)
SELECT COALESCE(Fname + ' ' + Middle + ' ' + Lname, Fname + LName) AS FullName,
COALESCE(Address1 + ', ' + Address2, Address1) AS Address, City, Zip
FROM tblImport
Demo on SQLFiddle
Well, I figured it out myself, right after posting, which is the most embarassing way. :)
It seems every member of a StackPanel will simply fill its minimum requested size.
In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.
I would love to see a more elegant method of handling this, but it will do.
I'm certain there are better ways of doing this, but I have in the past used a method something like the following to serialize an object into a string that I can log:
private string ObjectToXml(object output)
{
string objectAsXmlString;
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(output.GetType());
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
try
{
xs.Serialize(sw, output);
objectAsXmlString = sw.ToString();
}
catch (Exception ex)
{
objectAsXmlString = ex.ToString();
}
}
return objectAsXmlString;
}
You'll see that the method might also return the exception rather than the serialized object, so you'll want to ensure that the objects you want to log are serializable.
Solution
DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)
The prompt:
Password for 'https://[email protected]':
suggests, that you are using https not ssh. SSH urls start with git@, for example:
[email protected]:beginninggit/alias.git
Even if you work alone, with a single repo that you own, the operation:
git push
will cause:
Password for 'https://[email protected]':
if the remote origin starts with https
.
Check your remote with:
git remote -v
The remote depends on git clone
. If you want to use ssh clone the repo using its ssh url, for example:
git clone [email protected]:user/repo.git
I suggest you to start with git push
and git pull
for your private repo.
If that works, you have two joices suggested by Lazy Badger:
import (
"bufio"
"os"
)
var (
reader = bufio.NewReader(os.Stdin)
)
func ReadFromStdin() string{
result, _ := reader.ReadString('\n')
witl := result[:len(result)-1]
return witl
}
Here is an example with function ReadFromStdin()
it's like fmt.Scan(&name)
but its takes all strings with blank spaces like: "Hello My Name Is ..."
var name string = ReadFromStdin()
println(name)
require section This section contains the packages/dependencies which are better candidates to be installed/required in the production environment.
require-dev section: This section contains the packages/dependencies which can be used by the developer to test her code (or to experiment on her local machine and she doesn't want these packages to be installed on the production environment).
Stacker posed a great answer, I would go one step farther to make it more dynamic and use Spring 3 EL Expression.
<bean id="listBean" class="java.util.ArrayList">
<constructor-arg>
<value>#{springDAOBean.getGenericListFoo()}</value>
</constructor-arg>
</bean>
I was trying to figure out how I could do this with the util:list but couldn't get it work due to conversion errors.
Make a script like this:
#!/bin/bash
echo $((0x$1)).$((0x$2)).$((0x$3)).$((0x$4))
Example:
sh converthextoip.sh c0 a8 00 0b
Result:
192.168.0.11
I had the same Problem. I had start my Oracle TNS Listener, then it works normally again.
Here is how you can print all permutations in 10 lines of code:
public class Permute{
static void permute(java.util.List<Integer> arr, int k){
for(int i = k; i < arr.size(); i++){
java.util.Collections.swap(arr, i, k);
permute(arr, k+1);
java.util.Collections.swap(arr, k, i);
}
if (k == arr.size() -1){
System.out.println(java.util.Arrays.toString(arr.toArray()));
}
}
public static void main(String[] args){
Permute.permute(java.util.Arrays.asList(3,4,6,2,1), 0);
}
}
You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element. The tricky part is that after recursive call you must swap i-th element with first element back, otherwise you could get repeated values at the first spot. By swapping it back we restore order of elements (basically you do backtracking).
Iterators and Extension to the case of repeated values
The drawback of previous algorithm is that it is recursive, and does not play nicely with iterators. Another issue is that if you allow repeated elements in your input, then it won't work as is.
For example, given input [3,3,4,4] all possible permutations (without repetitions) are
[3, 3, 4, 4]
[3, 4, 3, 4]
[3, 4, 4, 3]
[4, 3, 3, 4]
[4, 3, 4, 3]
[4, 4, 3, 3]
(if you simply apply permute
function from above you will get [3,3,4,4] four times, and this is not what you naturally want to see in this case; and the number of such permutations is 4!/(2!*2!)=6)
It is possible to modify the above algorithm to handle this case, but it won't look nice. Luckily, there is a better algorithm (I found it here) which handles repeated values and is not recursive.
First note, that permutation of array of any objects can be reduced to permutations of integers by enumerating them in any order.
To get permutations of an integer array, you start with an array sorted in ascending order. You 'goal' is to make it descending. To generate next permutation you are trying to find the first index from the bottom where sequence fails to be descending, and improves value in that index while switching order of the rest of the tail from descending to ascending in this case.
Here is the core of the algorithm:
//ind is an array of integers
for(int tail = ind.length - 1;tail > 0;tail--){
if (ind[tail - 1] < ind[tail]){//still increasing
//find last element which does not exceed ind[tail-1]
int s = ind.length - 1;
while(ind[tail-1] >= ind[s])
s--;
swap(ind, tail-1, s);
//reverse order of elements in the tail
for(int i = tail, j = ind.length - 1; i < j; i++, j--){
swap(ind, i, j);
}
break;
}
}
Here is the full code of iterator. Constructor accepts an array of objects, and maps them into an array of integers using HashMap
.
import java.lang.reflect.Array;
import java.util.*;
class Permutations<E> implements Iterator<E[]>{
private E[] arr;
private int[] ind;
private boolean has_next;
public E[] output;//next() returns this array, make it public
Permutations(E[] arr){
this.arr = arr.clone();
ind = new int[arr.length];
//convert an array of any elements into array of integers - first occurrence is used to enumerate
Map<E, Integer> hm = new HashMap<E, Integer>();
for(int i = 0; i < arr.length; i++){
Integer n = hm.get(arr[i]);
if (n == null){
hm.put(arr[i], i);
n = i;
}
ind[i] = n.intValue();
}
Arrays.sort(ind);//start with ascending sequence of integers
//output = new E[arr.length]; <-- cannot do in Java with generics, so use reflection
output = (E[]) Array.newInstance(arr.getClass().getComponentType(), arr.length);
has_next = true;
}
public boolean hasNext() {
return has_next;
}
/**
* Computes next permutations. Same array instance is returned every time!
* @return
*/
public E[] next() {
if (!has_next)
throw new NoSuchElementException();
for(int i = 0; i < ind.length; i++){
output[i] = arr[ind[i]];
}
//get next permutation
has_next = false;
for(int tail = ind.length - 1;tail > 0;tail--){
if (ind[tail - 1] < ind[tail]){//still increasing
//find last element which does not exceed ind[tail-1]
int s = ind.length - 1;
while(ind[tail-1] >= ind[s])
s--;
swap(ind, tail-1, s);
//reverse order of elements in the tail
for(int i = tail, j = ind.length - 1; i < j; i++, j--){
swap(ind, i, j);
}
has_next = true;
break;
}
}
return output;
}
private void swap(int[] arr, int i, int j){
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public void remove() {
}
}
Usage/test:
TCMath.Permutations<Integer> perm = new TCMath.Permutations<Integer>(new Integer[]{3,3,4,4,4,5,5});
int count = 0;
while(perm.hasNext()){
System.out.println(Arrays.toString(perm.next()));
count++;
}
System.out.println("total: " + count);
Prints out all 7!/(2!*3!*2!)=210
permutations.
Just no one use $
instead of jQuery
:
if ($.inArray(nearest.node.name, array)>=0){
console.log("is in array");
}else{
console.log("is not in array");
}
Based on http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
What about:
Create Table New_Users Select * from Old_Users Where 1=2;
and if that doesn't work, just select a row and truncate after creation:
Create table New_Users select * from Old_Users Limit 1;
Truncate Table New_Users;
EDIT:
I noticed your comment below about needing indexes, etc. Try:
show create table old_users;
#copy the output ddl statement into a text editor and change the table name to new_users
#run the new query
insert into new_users(id,name...) select id,name,... form old_users group by id;
That should do it. It appears that you are doing this to get rid of duplicates? In which case you may want to put a unique index on id. if it's a primary key, this should already be in place. You can either:
#make primary key
alter table new_users add primary key (id);
#make unique
create unique index idx_new_users_id_uniq on new_users (id);
Peace quote of 2020:
Console.WriteLine("I {0} JavaScript!", ">:D<");
console.log(`I ${'>:D<'} C#`)
After resizing and not being able to view the resizing on my windows XP guest machine, I had to
I saw in other forums that snapshots can interfere for resizing and not being able to remove all snapshots for different errors I got, the only found solution for me was to clone it to remove the snapshots and then resize it, and everything worked. For resizing outside windows, a gparted boot cd that can be found here can help
This comes up in Java 5 and later if you're using collections without type specifiers (e.g., Arraylist()
instead of ArrayList<String>()
). It means that the compiler can't check that you're using the collection in a type-safe way, using generics.
To get rid of the warning, just be specific about what type of objects you're storing in the collection. So, instead of
List myList = new ArrayList();
use
List<String> myList = new ArrayList<String>();
In Java 7 you can shorten generic instantiation by using Type Inference.
List<String> myList = new ArrayList<>();
Just to keep up with the technology, here's a Java 8 version using streams and a custom Collector, eliminating the need for loops or if statements:
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.IntStream;
public class RomanNumeral {
public static void main(String arg[]) {
IntStream.range(1, 4000).forEach(value -> System.out.println( Arrays.stream(Mark.values()).collect(new MarkCollector<Mark>(value)).toString()));
}
enum Mark {
M(1000), CM(900), D(500), CD(400), C(100), XC(90), L(50), XL(40), X(10), IX(9), V(5), IV(4), I(1);
private final int value;
private Mark(int value) { this.value = value; }
public int value() { return value; }
}
static class MarkCollector<T extends Mark> implements Collector<T, StringBuilder, StringBuilder> {
private final int[] valueholder = new int[1];
MarkCollector(int value) { valueholder[0] = value; }
@Override
public Supplier<StringBuilder> supplier() { return () -> StringBuilder::new; }
@Override
public BiConsumer<StringBuilder, T> accumulator() {
return (builder, mark) -> {
builder.append(String.join("", Collections.nCopies(valueholder[0] / mark.value(), mark.name())));
valueholder[0] = valueholder[0] % mark.value();
};
}
@Override
public BinaryOperator<StringBuilder> combiner() { return null; }
@Override
public Function<StringBuilder, StringBuilder> finisher() { return Function.identity(); }
@Override
public Set<Characteristics> characteristics() { return Collections.singleton(Characteristics.IDENTITY_FINISH); }
}
}
Using new ES6 Object.entries()
, it makes for a fun little nested map
/join
:
const encodeGetParams = p => _x000D_
Object.entries(p).map(kv => kv.map(encodeURIComponent).join("=")).join("&");_x000D_
_x000D_
const params = {_x000D_
user: "María Rodríguez",_x000D_
awesome: true,_x000D_
awesomeness: 64,_x000D_
"ZOMG+&=*(": "*^%*GMOZ"_x000D_
};_x000D_
_x000D_
console.log("https://example.com/endpoint?" + encodeGetParams(params))
_x000D_
Instead of copy'n'pasting snippets found here and there, I'd recommend to use a well tested and maintained library: Colors.js (available for node.js and browser). It's just 7 KB (minified, gzipped even less).
import {Injectable, EventEmitter} from "@angular/core";
@Injectable()
export class DataService {
onGetData: EventEmitter = new EventEmitter();
getData() {
this.http.post(...params).map(res => {
this.onGetData.emit(res.json());
})
}
import {Component} from '@angular/core';
import {DataService} from "../services/data.service";
@Component()
export class MyComponent {
constructor(private DataService:DataService) {
this.DataService.onGetData.subscribe(res => {
(from service on .emit() )
})
}
//To send data to all subscribers from current component
sendData() {
this.DataService.onGetData.emit(--NEW DATA--);
}
}
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
I was trying to also sort by a DateTime field descending and this seems to do the trick:
var ud = (from d in env
orderby -d.ReportDate.Ticks
select d.ReportDate.ToString("yyyy-MMM") ).Distinct();
Here is Federico Ramponi's answer in Go. Note: no error-checking :(
import (
"math"
)
// Semi-axes of WGS-84 geoidal reference
const (
// Major semiaxis (meters)
WGS84A = 6378137.0
// Minor semiaxis (meters)
WGS84B = 6356752.3
)
// BoundingBox represents the geo-polygon that encompasses the given point and radius
type BoundingBox struct {
LatMin float64
LatMax float64
LonMin float64
LonMax float64
}
// Convert a degree value to radians
func deg2Rad(deg float64) float64 {
return math.Pi * deg / 180.0
}
// Convert a radian value to degrees
func rad2Deg(rad float64) float64 {
return 180.0 * rad / math.Pi
}
// Get the Earth's radius in meters at a given latitude based on the WGS84 ellipsoid
func getWgs84EarthRadius(lat float64) float64 {
an := WGS84A * WGS84A * math.Cos(lat)
bn := WGS84B * WGS84B * math.Sin(lat)
ad := WGS84A * math.Cos(lat)
bd := WGS84B * math.Sin(lat)
return math.Sqrt((an*an + bn*bn) / (ad*ad + bd*bd))
}
// GetBoundingBox returns a BoundingBox encompassing the given lat/long point and radius
func GetBoundingBox(latDeg float64, longDeg float64, radiusKm float64) BoundingBox {
lat := deg2Rad(latDeg)
lon := deg2Rad(longDeg)
halfSide := 1000 * radiusKm
// Radius of Earth at given latitude
radius := getWgs84EarthRadius(lat)
pradius := radius * math.Cos(lat)
latMin := lat - halfSide/radius
latMax := lat + halfSide/radius
lonMin := lon - halfSide/pradius
lonMax := lon + halfSide/pradius
return BoundingBox{
LatMin: rad2Deg(latMin),
LatMax: rad2Deg(latMax),
LonMin: rad2Deg(lonMin),
LonMax: rad2Deg(lonMax),
}
}
Turning Marc Gravell's answer into an extension method, I made the following.
internal static IEnumerable<Tuple<TLeft, TRight>> LeftJoin<TLeft, TRight, TKey>(
this IEnumerable<TLeft> left,
IEnumerable<TRight> right,
Func<TLeft, TKey> selectKeyLeft,
Func<TRight, TKey> selectKeyRight,
TRight defaultRight = default(TRight),
IEqualityComparer<TKey> cmp = null)
{
return left.GroupJoin(
right,
selectKeyLeft,
selectKeyRight,
(x, y) => new Tuple<TLeft, IEnumerable<TRight>>(x, y),
cmp ?? EqualityComparer<TKey>.Default)
.SelectMany(
x => x.Item2.DefaultIfEmpty(defaultRight),
(x, y) => new Tuple<TLeft, TRight>(x.Item1, y));
}
you can use those functions together with iferror
as a work around.
try =IFERROR(VALUE(A4),(CONCATENATE(A4)))
I came across this post while searching for a way to clear the entire form related to the BFCache (back/forward button cache) in Chrome.
In addition to what Sim supplied, my use case required that the details needed to be combined with Clear Form on Back Button?.
I found that the best way to do this is in allow the form to behave as it expects, and to trigger an event:
$(window).bind("pageshow", function() {
var form = $('form');
// let the browser natively reset defaults
form[0].reset();
});
If you are not handling the input
events to generate an object in JavaScript, or something else for that matter, then you are done. However, if you are listening to the events, then at least in Chrome you need to trigger a change
event yourself (or whatever event you care to handle, including a custom one):
form.find(':input').not(':button,:submit,:reset,:hidden').trigger('change');
That must be added after the reset
to do any good.
The source code looks like -
package com.bluestone.pms.app.boot;
import org.springframework.boot.Banner;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.your.pkg"})
public class BootApplication extends SpringBootServletInitializer {
/**
* @param args Arguments
*/
public static void main(String[] args) {
SpringApplication application = new SpringApplication(BootApplication.class);
/* Setting Boot banner off default value is true */
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
/**
* @param builder a builder for the application context
* @return the application builder
* @see SpringApplicationBuilder
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
builder) {
return super.configure(builder);
}
}
I added this to my vimrc
file.
command! H let @/=""
After you do a search and want to clear the highlights from your search just do :H
Let us say we have a project social_login. To check the traffic to your repo, you can goto https://github.com//social_login/graphs/traffic
The difference between getAttribute and getParameter is that getParameter will return the value of a parameter that was submitted by an HTML form or that was included in a query string. getAttribute returns an object that you have set in the request, the only way you can use this is in conjunction with a RequestDispatcher. You use a RequestDispatcher to forward a request to another resource (JSP / Servlet). So before you forward the request you can set an attribute which will be available to the next resource.
df['FirstName']=df['ID'].apply(lambda x: 'Matt' if x==103 else '')
df['LastName']=df['ID'].apply(lambda x: 'Jones' if x==103 else '')
Do not try doing that using a map function. Map function should be used to map values from one thing to other. When the number of input and output match.
In this case use filter function which is also available on the array. Filter function is used when you want to selectively take values maching certain criteria. Then you can write your code like
var items = list
.filter((i, index) => (index < 3))
.map((i, index) => {
return (
<myview item={i} key={i.id} />
);
});
First find the version you are using with the Git command git --version
. If you have a newer version than 1.7.10, then simply use this command:
git config --global credential.helper wincred
Then do the git fetch
, then it prompts for the password update.
Now, it won't prompt for the password for multiple times in Git.
This works for me:
var test = [1, 2, 3]
var n = 2
var test2 = test[0..<n]
Your issue could be with how you're declaring your array to begin with.
EDIT:
To fix your function, you have to cast your Slice
to an array:
func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
var newNumbers = Array(numbers[0..<position])
return newNumbers
}
// test
aFunction([1, 2, 3], 2) // returns [1, 2]
$('.toggle img').data('block', 'something');
$('.toggle img').attr('src', 'something.jpg');
Use jQuery.data and jQuery.attr.
I'm showing them to you separately for the sake of understanding.
On top of @kp's answer:
I'm dealing with this and in my case, I have to show a child element and correct the height of the parent object accordingly (auto-sizing is not working in a bootstrap header for some reason I don't have time to debug).
But instead of using javascript to modify the parent, I think I'll dynamically add a CSS class to the parent and CSS-selectively show the children accordingly. This will maintain the decisions in the logic and not based on a CSS state.
tl;dr; apply the a
and b
styles to the parent <div>
, not the child (of course, not everyone will be able to do this. i.e. Angular components making decisions of their own).
<style>
.parent { height: 50px; }
.parent div { display: none; }
.with-children { height: 100px; }
.with-children div { display: block; }
</style>
<div class="parent">
<div>child</div>
</div>
<script>
// to show the children
$('.parent').addClass('with-children');
</script>
This can also occur if your stored procedure encounters a compile failure after opening a transaction (e.g. table not found, invalid column name).
I found i had to use 2 stored procedures a "worker" one and a wrapper one with try/catch both with logic similar to that outlined by Remus Rusanu. The worker catch is used to handle the "normal" failures and the wrapper catch to handle compile failure errors.
https://msdn.microsoft.com/en-us/library/ms175976.aspx
Errors Unaffected by a TRY…CATCH Construct
The following types of errors are not handled by a CATCH block when they occur at the same level of execution as the TRY…CATCH construct:
- Compile errors, such as syntax errors, that prevent a batch from running.
- Errors that occur during statement-level recompilation, such as object name resolution errors that occur after compilation because of deferred name resolution.
Hopefully this helps someone else save a few hours of debugging...
Add this single line in manifest (for permission)
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Then paste this code in your activity
private ArrayList<String> getPrimaryMailId() {
ArrayList<String> accountsList = new ArrayList<String>();
try {
Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
for (Account account : accounts) {
accountsList.add(account.name);
Log.e("GetPrimaryMailId ", account.name);
}
} catch (Exception e) {
Log.e("GetPrimaryMailId", " Exception : " + e);
}
return accountsList;
}
In my case it was the ErrorLog directive in httpd.conf. Just accidently noticed it already after I gave up. Decided to share the discovery ) Now I know where to find the 500-errors.
EDIT: Check if the api you’re interacting with is set to Content-Type: application/json
, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”
, instead of body: { ...normal payload }
). All I had to do was change the api to Content-Type: text/plain
, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.
ORIGINAL: If your Googles keep landing you here and your api throws errors unless your JSON double quotes are escaped ("{\"foo\": true}"
), all you need to do is stringify twice e.g. JSON.stringify(JSON.stringify(bar))
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
an EXE
file is created as long as you build the project. you can usually find this on the debug folder of you project.
C:\Users\username\Documents\Visual Studio 2012\Projects\ProjectName\bin\Debug
If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc
This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array
import numpy as np
from sklearn.metrics import auc
dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)
print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))
both output the same area: 4607.5
the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect
Copy-pasted from here: Incrementing a date in JavaScript
Three options for you:
Using just JavaScript's Date object (no libraries):
var today = new Date(); var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
Or if you don't mind changing the date in place (rather than creating a new date):
var dt = new Date(); dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));
Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Using MomentJS:
var today = moment(); var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today() var tomorrow = today.add(1).day();
You would need to add a trigger on insert, update, delete that sets a value in another table to sysdate.
When you run application, it would read the value and save it somewhere so that the next time it is run it has a reference to compare.
Would you consider that "Special Admin Stuff"?
It would be better to describe what you're actually doing so you get clearer answers.
Just use Control.Invoke Method or Control.BeginInvoke Method.
Great example: How to: Make Thread-Safe Calls to Windows Forms Controls.
You need to go to Settings and set under the Java compiler the following:
also check the Project Settings
If the JSON parsing tool, jq
is available
wget -q https://registry.hub.docker.com/v1/repositories/debian/tags -O - | \
jq -r '.[].name'
Your Manifest
Must Change like this Activity name must Specified like ".YourActivityname"
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8" android:targetSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainTabPanel"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyBookActivity" >
</activity>
</application>
I used the CSS in the accepted answer here for my responsive YouTube videos - worked great right up until YouTube updated their system around the start of August 2015. The videos on YouTube are the same dimensions but for whatever reason the CSS in the accepted answer now letterboxes all our videos. Black bands across top and bottom.
I've tickered around with the sizes and settled on getting rid of the top padding and changing the bottom padding to 56.45%
. Seems to look good.
.videowrapper {
position: relative;
padding-bottom: 56.45%;
height: 0;
}
left: 50%;
margin-left: -400px; /* Half of the width */
I don't program Scala, but I use another language with implicit returns (Ruby). You have code after your if (elem.isEmpty)
block -- the last line of code is what's returned, which is why you're not getting what you're expecting.
EDIT: Here's a simpler way to write your function too. Just use the boolean value of isEmpty and count to return true or false automatically:
def balanceMain(elem: List[Char]): Boolean =
{
elem.isEmpty && count == 0
}
We can do with by using few lines of JS code:
if(typeof window.LIT !== 'undefined') {
clearTimeout(window.LIT);
}
window.LIT = setTimeout(() => this.updateTable(), 1000);
Simple solution! Work Perfect! Hope, will be helpful for you guys.
Vishal Chaudhry's answer above worked for me. I would also add that in order to manually trigger the seque using:
[self performSegueWithIdentifier:@"mySegueName" sender:self];
from within the ViewController you must also select the unwind segue under the ViewController's Scene in the storyboard and in the properties view on the RHS ensure that the Indentifier field contains the namer you're referring to in the code ("mySegueName" in the example above).
If you omit this step, the line above will throw an exception that the seque name is not known.
The whereBetween
method verifies that a column's value is between
two values.
$from = date('2018-01-01');
$to = date('2018-05-02');
Reservation::whereBetween('reservation_from', [$from, $to])->get();
In some cases you need to add date range dynamically. Based on @Anovative's comment you can do this:
Reservation::all()->filter(function($item) {
if (Carbon::now->between($item->from, $item->to) {
return $item;
}
});
If you would like to add more condition then you can use orWhereBetween
. If you would like to exclude a date interval then you can use whereNotBetween
.
Reservation::whereBetween('reservation_from', [$from1, $to1])
->orWhereBetween('reservation_to', [$from2, $to2])
->whereNotBetween('reservation_to', [$from3, $to3])
->get();
Other useful where clauses: whereIn
, whereNotIn
, whereNull
, whereNotNull
, whereDate
, whereMonth
, whereDay
, whereYear
, whereTime
, whereColumn
, whereExists
, whereRaw
.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);
This works. You have to use two SimpleDateFormats, one for input and one for output, but it will give you just what you are wanting.
If you're really lucky, like I was, you can go back into your text editor and hit 'undo'.
I know that's not really a proper answer, but it saved me half a day's work so hopefully it'll do the same for someone else!
You can also try this to determine the current global sql_mode
value:
SELECT @@GLOBAL.sql_mode;
or session sql_mode
value:
SELECT @@SESSION.sql_mode;
I also had the feeling that the SQL mode was indeed empty.
I'd say the minimum would be to
In addition to the already excellent answers, also consider this function to retrieve both the number of dimensions and their bounds, which is similar to John's answer, but works and looks a little differently:
Function sizeOfArray(arr As Variant) As String
Dim str As String
Dim numDim As Integer
numDim = NumberOfArrayDimensions(arr)
str = "Array"
For i = 1 To numDim
str = str & "(" & LBound(arr, i) & " To " & UBound(arr, i)
If Not i = numDim Then
str = str & ", "
Else
str = str & ")"
End If
Next i
sizeOfArray = str
End Function
Private Function NumberOfArrayDimensions(arr As Variant) As Integer
' By Chip Pearson
' http://www.cpearson.com/excel/vbaarrays.htm
Dim Ndx As Integer
Dim Res As Integer
On Error Resume Next
' Loop, increasing the dimension index Ndx, until an error occurs.
' An error will occur when Ndx exceeds the number of dimension
' in the array. Return Ndx - 1.
Do
Ndx = Ndx + 1
Res = UBound(arr, Ndx)
Loop Until Err.Number <> 0
NumberOfArrayDimensions = Ndx - 1
End Function
Example usage:
Sub arrSizeTester()
Dim arr(1 To 2, 3 To 22, 2 To 9, 12 To 18) As Variant
Debug.Print sizeOfArray(arr())
End Sub
And its output:
Array(1 To 2, 3 To 22, 2 To 9, 12 To 18)
You can use CSS gradient - although there are not consistent across browsers so You would have to code it for every one
Like that: CSS3 Transparency + Gradient
Gradient should be more transparent on top or on top right corner (depending on capabilities)
Browser development progresses:
Number.toLocaleString(locale);
// E.g.
parseFloat("1234567.891").toLocaleString(window.document.documentElement.lang);
"1,234,567.891"
function:
function print_call_stack(err) {
var stack = err.stack;
console.error(stack);
}
use case:
try{
aaa.bbb;//error throw here
}
catch (err){
print_call_stack(err);
}
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
unsorted_list.sort(key=lambda x: x[3])
I was getting this error because I did release that my ant release
was failing because I ran out of disk space.
These are listed in RFC3986. See the Collected ABNF for URI to see what is allowed where and the regex for parsing/validation.
Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:
textView.setTextColor(getResources().getColor(R.color.some_color));
Please note that from API 23, getResources().getColor()
is deprecated. Use instead:
textView.setTextColor(ContextCompat.getColor(context, R.color.some_color));
where the required color is defined in an xml as:
<resources>
<color name="some_color">#bdbdbd</color>
</resources>
Update:
This method was deprecated in API level 23. Use getColor(int, Theme) instead.
Check this.
Try this:
(add-hook 'text-mode-hook
(function
(lambda ()
(setq tab-width 4)
(define-key text-mode-map "\C-i" 'self-insert-command)
)))
That will make TAB always insert a literal TAB character with tab stops every 4 characters (but only in Text mode). If that's not what you're asking for, please describe the behavior you'd like to see.
The installation of these tools may vary on different OS.
Under Windows, node-sass currently supports VS2015 by default, if you only have VS2013 in your box and meet any error while running the command, you can define the version of VS by adding: --msvs_version=2013. This is noted on the node-sass npm page.
So, the safe command line that works on Windows with VS2013 is: npm install --msvs_version=2013 gulp node-sass gulp-sass
Just in case you are looking for an alternate way and the environment you use is Windows, Microsoft's Network Monitor 3.3 is a good choice. It has the process name column. You easily add it to a filter using the context menu and apply the filter.. As usual the GUI is very intuitive...
%0|%0
is a fork bomb. It will spawn another process using a pipe |
which runs a copy of the same program asynchronously. This hogs the CPU and memory, slowing down the system to a near-halt (or even crash the system).
%0
refers to the command used to run the current program. For example, script.bat
A pipe |
symbol will make the output or result of the first command sequence as the input for the second command sequence. In the case of a fork bomb, there is no output, so it will simply run the second command sequence without any input.
Expanding the example, %0|%0
could mean script.bat|script.bat
. This runs itself again, but also creating another process to run the same program again (with no input).
Well, i had a similar issue and the problems was the PHP magic quotes in the server... here is my solution:
if(get_magic_quotes_gpc()){
$param = stripslashes($_POST['param']);
}else{
$param = $_POST['param'];
}
$param = json_decode($param,true);
The difference between substring and slice - is how they work with negative and overlooking lines abroad arguments:
substring (start, end)
Negative arguments are interpreted as zero. Too large values ??are truncated to the length of the string: alert ( "testme" .substring (-2)); // "testme", -2 becomes 0
Furthermore, if start > end, the arguments are interchanged, i.e. plot line returns between the start and end:
alert ( "testme" .substring (4, -1)); // "test"
// -1 Becomes 0 -> got substring (4, 0)
// 4> 0, so that the arguments are swapped -> substring (0, 4) = "test"
slice
Negative values ??are measured from the end of the line:
alert ( "testme" .slice (-2)); // "me", from the end position 2
alert ( "testme" .slice (1, -1)); // "estm", from the first position to the one at the end.
It is much more convenient than the strange logic substring.
A negative value of the first parameter to substr supported in all browsers except IE8-.
If the choice of one of these three methods, for use in most situations - it will be slice: negative arguments and it maintains and operates most obvious.
Without hitting db we can fetch all months name.
WITH CTE_Sample1 AS
(
Select 0 as MonthNumber
UNION ALL
select MonthNumber+1 FROM CTE_Sample1
WHERE MonthNumber+1<12
)
Select DateName( month , DateAdd( month , MonthNumber ,0 ) ) from CTE_Sample1
A solution that helped me: Go to Tools > NuGet Package Manager > Manage NuGet Packaged for Solution... > Browse > Search for System.IO.Compression.ZipFile and install it
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.