There are a lot of ways to accomplish this, and this is but one of them.
$("table").find("tbody td").eq(0).children().first()
If you don't care about supporting old browsers, you can use :not()
to exclude that element:
.parent:hover span:not(:hover) {
border: 10px solid red;
}
Demo: http://jsfiddle.net/vz9A9/1/
If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:
.parent span:hover {
border: 10px solid green;
}
From your FirstActivity call the SecondActivity using startActivityForResult() method.
For example:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.
For example: In secondActivity if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
If you don't want to return data:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
Now in your FirstActivity class write following code for the onActivityResult() method.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
In case you want to use that padding space... then here's something:
All the colors are background colors.
My case was different the child view already had a parent view i am adding the child view inside parent view to different parent. example code below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/lineGap"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black1"
android:layout_gravity="center"
android:gravity="center"
/>
</LinearLayout>
And i was inflating this view and adding to another LinearLayout, then i removed the LinaarLayout from the above layout and its started working
below code fixed the issue:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="@color/black1" />
I had the same problem and I fixed by setting transparent png image as background for the parent tag.
This is the 1px x 1px PNG Image that I have created with 60% Opacity of black background !
Many ways to skin the cat here and @Mitch's suggestion is a good way. If you want the client form to have more 'control', you may want to pass the instance of the parent to the child when created and then you can call any public parent method on the child.
Check my answer here
The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view
Feeela is right but you can get a parent div
contracting or expanding to a child element if you reverse your div
positioning like this:
.parent {
position: absolute;
/* position it in the browser using the `left`, `top` and `margin`
attributes */
}
.child {
position: relative;
height: 100%;
width: 100%;
overflow: hidden;
/* to pad or move it around using `left` and `top` inside the parent */
}
This should work for you.
Just pass the object reference to the following function and you will get the index
function thisindex(elm)
{
var the_li = elm;
var the_ul = elm.parentNode;
var li_list = the_ul.childNodes;
var count = 0; // Tracks the index of LI nodes
// Step through all the child nodes of the UL
for( var i = 0; i < li_list.length; i++ )
{
var node = li_list.item(i);
if( node )
{
// Check to see if the node is a LI
if( node.nodeName == "LI" )
{
// Increment the count of LI nodes
count++;
// Check to see if this node is the one passed in
if( the_li == node )
{
// If so, alert the current count
alert(count-1);
}
}
}
}
}
Just add <relativePath />
so the parent in pom should look like:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath />
</parent>
Why not just use:
$("#foo span")
or
$("#foo > span")
$('span', $('#foo'));
works fine on my machine ;)
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main (){
int pid;
int status;
printf("Parent: %d\n", getpid());
pid = fork();
if (pid == 0){
printf("Child %d\n", getpid());
sleep(2);
exit(EXIT_SUCCESS);
}
//Comment from here to...
//Parent waits process pid (child)
waitpid(pid, &status, 0);
//Option is 0 since I check it later
if (WIFSIGNALED(status)){
printf("Error\n");
}
else if (WEXITSTATUS(status)){
printf("Exited Normally\n");
}
//To Here and see the difference
printf("Parent: %d\n", getpid());
return 0;
}
in my case i was using compile sdk 23
and build tools 25.0.0
just changed compile sdk
to 25 and done..
/// <summary>
/// Contains global variables for project.
/// </summary>
public static class GlobalVar
{
/// <summary>
/// Global variable that is constant.
/// </summary>
public const string GlobalString = "Important Text";
/// <summary>
/// Static value protected by access routine.
/// </summary>
static int _globalValue;
/// <summary>
/// Access routine for global variable.
/// </summary>
public static int GlobalValue
{
get
{
return _globalValue;
}
set
{
_globalValue = value;
}
}
/// <summary>
/// Global static field.
/// </summary>
public static bool GlobalBoolean;
}
Try this:
.navbar {
position: relative;
}
.brand {
position: absolute;
left: 50%;
margin-left: -50px !important; /* 50% of your logo width */
display: block;
}
Centering your logo by 50% and minus half of your logo width so that it won't have problem when zooming in and out.
See fiddle
I know this thread has been idle for a while, but I just wanted to add my two cents to supplement jariq's comment...
Per manual, you don't necessary want to use -password
option.
Let's say mykey.key
has a password and your want to protect iphone-dev.p12
with another password, this is what you'd use:
pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -passin pass:password_for_mykey -passout pass:password_for_iphone_dev
Have fun scripting!!
Here is simple example of how you can do this.
Just replace the image file and you are done.
HTML Code
<input type="radio" id="r1" name="rr" />
<label for="r1"><span></span>Radio Button 1</label>
<p>
<input type="radio" id="r2" name="rr" />
<label for="r2"><span></span>Radio Button 2</label>
CSS
input[type="radio"] {
display:none;
}
input[type="radio"] + label {
color:#f2f2f2;
font-family:Arial, sans-serif;
font-size:14px;
}
input[type="radio"] + label span {
display:inline-block;
width:19px;
height:19px;
margin:-1px 4px 0 0;
vertical-align:middle;
background:url(check_radio_sheet.png) -38px top no-repeat;
cursor:pointer;
}
input[type="radio"]:checked + label span {
background:url(check_radio_sheet.png) -57px top no-repeat;
}
Using this you can avoid the loop.
// obj is the params object with key-value pair.
// This is how you convert that to HttpParams and pass this to GET API.
const params = Object.getOwnPropertyNames(obj)
.reduce((p, key) => p.set(key, obj[key]), new HttpParams());
Furthermore, I suggest making toHttpParams function in your commonly used service. So you can call the function to convert the object to the HttpParams.
/**
* Convert Object to HttpParams
* @param {Object} obj
* @returns {HttpParams}
*/
toHttpParams(obj: Object): HttpParams {
return Object.getOwnPropertyNames(obj)
.reduce((p, key) => p.set(key, obj[key]), new HttpParams());
}
Update:
Since 5.0.0-beta.6 (2017-09-03) they added new feature (accept object map for HttpClient headers & params)
Going forward the object can be passed directly instead of HttpParams.
This is the other reason if you have used one common function like toHttpParams mentioned above, you can easily remove it or do changes if required.
string queryString = "Default.aspx?Agent=10&Language=2"; //Request.QueryString.ToString();
string parameterToRemove="Language"; //parameter which we want to remove
string regex=string.Format("(&{0}=[^&\s]+|{0}=[^&\s]+&?)",parameterToRemove);
string finalQS = Regex.Replace(queryString, regex, "");
Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range
Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)
Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
strFirstAddress = rngFindValue.Address
Do
Set rngFindValue = search.FindNext(rngFindValue)
Loop Until rngFindValue.Address = strFirstAddress
Select Product
from formula bar in your answer cell.
Select cells you want to multiply.
I realize this has been answered, but I used a different approach and thought it might be worth sharing. Also, I feel like my approach might produce unwanted overhead. However, I'm not able to observer or calculate anything happening that is that bad under the loads we observe. I was looking for any useful feedback on this approach.
The problem with working with dynamics is that you can't attach any functions to the dynamic object directly. You have to use something that can figure out the assignments that you don't want to figure out every time.
When planning this simple solution, I looked at what the valid intermediaries are when attempting to retype similar objects. I found that a binary array, string (xml, json) or hard coding a conversion (IConvertable) were the usual approaches. I don't want to get into binary conversions due to a code maintainability factor and laziness.
My theory was that Newtonsoft could do this by using a string intermediary.
As a downside, I am fairly certain that when converting the string to an object, that it would use reflection by searching the current assembly for an object with matching properties, create the type, then instantiate the properties, which would require more reflection. If true, all of this can be considered avoidable overhead.
C#:
//This lives in a helper class
public static ConvertDynamic<T>(dynamic data)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(Newtonsoft.Json.JsonConvert.SerializeObject(data));
}
//Same helper, but in an extension class (public static class),
//but could be in a base class also.
public static ToModelList<T>(this List<dynamic> list)
{
List<T> retList = new List<T>();
foreach(dynamic d in list)
{
retList.Add(ConvertDynamic<T>(d));
}
}
With that said, this fits another utility I've put together that lets me make any object into a dynamic. I know I had to use reflection to do that correctly:
public static dynamic ToDynamic(this object value)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
expando.Add(property.Name, property.GetValue(value));
return expando as ExpandoObject;
}
I had to offer that function. An arbitrary object assigned to a dynamic typed variable cannot be converted to an IDictionary, and will break the ConvertDynamic function. For this function chain to be used it has to be provided a dynamic of System.Dynamic.ExpandoObject, or IDictionary<string, object>.
So here is the solution for this:
I check port 80
used by Skype, after that I changes port to 81
and also along with that somewhere i read this error may be because of SSL Port then I changed SSL port to 444
. However this got resolved easily.
One most important thing to notice here, all the port changes should be done inside config files, for http port change: httpd.conf for SSL httpd-ssl.conf. Otherwise changes will not replicate to Apache, Sometime PC reboot is also required.
Edit: Make Apache use port 80 and make Skype communicate on other Port
For those who are struggling with Skype, want to change its port and to make Apache to use port 80.
No need to Re-Install, Here is simply how to change Skype Port
Goto: Tools > Options > Advanced > Connection
There you need to uncheck
Use port 80 and 443 as alternative for incoming connections.
That's it, here is screen shot of it.
we can do this easily with html5 also, just need to add some jquery code
HTML
<form>
<div class="form-group options">
<input type="checkbox" name="type[]" value="A" required /> A
<input type="checkbox" name="type[]" value="B" required /> B
<input type="checkbox" name="type[]" value="C" required /> C
<input type="submit">
</div>
</form>
Jquery
$(function(){
var requiredCheckboxes = $('.options :checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
} else {
requiredCheckboxes.attr('required', 'required');
}
});
});
I guess you won't be able to really find all possible exploits by parsing your source files.
also if there are really great lists provided in here, you can miss a function which can be exploitet
there still could be "hidden" evil code like this
$myEvilRegex = base64_decode('Ly4qL2U=');
preg_replace($myEvilRegex, $_POST['code']);
you could now say, i simply extend my script to also match this
but then you will have that mayn "possibly evil code" which additionally is out of it's context
so to be (pseudo-)secure, you should really write good code and read all existing code yourself
I think it's better to round the time to milliseconds before the division.
func makeTimestamp() int64 {
return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}
Here is an example program:
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(unixMilli(time.Unix(0, 123400000)))
fmt.Println(unixMilli(time.Unix(0, 123500000)))
m := makeTimestampMilli()
fmt.Println(m)
fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}
func unixMilli(t time.Time) int64 {
return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}
func makeTimestampMilli() int64 {
return unixMilli(time.Now())
}
The above program printed the result below on my machine:
123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST
To get the all selected Items in a CheckedListBox try this:
In this case ths value is a String but it's run with other type of Object:
for (int i = 0; i < myCheckedListBox.Items.Count; i++)
{
if (myCheckedListBox.GetItemChecked(i) == true)
{
MessageBox.Show("This is the value of ceckhed Item " + myCheckedListBox.Items[i].ToString());
}
}
In MVC5.2, add Date.cshtml to folder ~/Views/Shared/EditorTemplates:
@model DateTime?
@{
IDictionary<string, object> htmlAttributes;
object objAttributes;
if (ViewData.TryGetValue("htmlAttributes", out objAttributes))
{
htmlAttributes = objAttributes as IDictionary<string, object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(objAttributes);
}
else
{
htmlAttributes = new RouteValueDictionary();
}
htmlAttributes.Add("type", "date");
String format = (Request.UserAgent != null && Request.UserAgent.Contains("Chrome")) ? "{0:yyyy-MM-dd}" : "{0:d}";
@Html.TextBox("", Model, format, htmlAttributes)
}
You're attempting to access indicies within an array which are not set. This raises a notice.
Mostly likely you're noticing it now because your code has moved to a server where php.ini has error_reporting
set to include E_NOTICE
. Either suppress notices by setting error_reporting to E_ALL & ~E_NOTICE
(not recommended), or verify that the index exists before you attempt to access it:
$month = array_key_exists('month', $_POST) ? $_POST['month'] : null;
I am not sure why you cannot use "lat" but, if you must you can rename the columns in a derived table.
select a.latitude from (SELECT lat AS latitude FROM poi_table) a where latitude < 500
Change your code to
document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
Just add onsubmit
event handler for your form:
<form action="insert.php" onsubmit="return myFunction()" method="post">
Remove onclick
from button
and make it input
with type submit
<input type="submit" value="Submit">
And add boolean return statements to your function:
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var ok = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
return false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
var array = string.split(',')
and good morning, too, since I have to type 30 chars ...
Like pagination
you can use below formule for taking slice of list or elements
:
var slice = myList.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
Example 1: first five items
var pageNumber = 1;
var pageSize = 5;
Example 2: second five items
var pageNumber = 2;
var pageSize = 5;
Example 3: third five items
var pageNumber = 3;
var pageSize = 5;
If notice to formule parameters
pageSize = 5
andpageNumber
is changing, if you want to change number of items in slicing you changepageSize
.
Here is a one-line Bash snippet to move all tables from one schema to another:
history -d $((HISTCMD-1)) && mysql -udb_user -p'db_password' -Dold_schema -ABNnqre'SHOW TABLES;' | sed -e's/.*/RENAME TABLE old_schema.`&` TO new_schema.`&`;/' | mysql -udb_user -p'db_password' -Dnew_schema
The history command at the start simply ensures that the MySQL commands containing passwords aren't saved to the shell history.
Make sure that db_user
has read/write/drop permissions on the old schema, and read/write/create permissions on the new schema.
today is 2020-12-25, my VSC is 1.52.1, tried all above not very successful. Here is complete steps I did to add my existing local project to GitHub using VSC (Note: Do not create a corresponding repository at GitHub):
<your username>/<your new repository name>
. For example, my username is "myname" and my local folder is named "HelloWorld". So, it will be myname/HelloWorld
in the type-in box.The web.xml
file is the deployment descriptor for a Servlet-based Java web application (which most Java web apps are). Among other things, it declares which Servlets exist and which URLs they handle.
The part you cite defines a Servlet Filter. Servlet filters can do all kinds of preprocessing on requests. Your specific example is a filter had the Wicket framework uses as its entry point for all requests because filters are in some way more powerful than Servlets.
The accepted answer by Francisco Spaeth works and is easy to follow. However, I think that method of building JSON sucks! This was really driven home for me as I converted some Python to Java where I could use dictionaries and nested lists, etc. to build JSON with ridiculously greater ease.
What I really don't like is having to instantiate separate objects (and generally even name them) to build up these nestings. If you have a lot of objects or data to deal with, or your use is more abstract, that is a real pain!
I tried getting around some of that by attempting to clear and reuse temp json objects and lists, but that didn't work for me because all the puts and gets, etc. in these Java objects work by reference not value. So, I'd end up with JSON objects containing a bunch of screwy data after still having some ugly (albeit differently styled) code.
So, here's what I came up with to clean this up. It could use further development, but this should help serve as a base for those of you looking for more reasonable JSON building code:
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;
// create and initialize an object
public static JSONObject buildObject( final SimpleEntry... entries ) {
JSONObject object = new JSONObject();
for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() );
return object;
}
// nest a list of objects inside another
public static void putObjects( final JSONObject parentObject, final String key,
final JSONObject... objects ) {
List objectList = new ArrayList<JSONObject>();
for( JSONObject o : objects ) objectList.add( o );
parentObject.put( key, objectList );
}
Implementation example:
JSONObject jsonRequest = new JSONObject();
putObjects( jsonRequest, "parent1Key",
buildObject(
new SimpleEntry( "child1Key1", "someValue" )
, new SimpleEntry( "child1Key2", "someValue" )
)
, buildObject(
new SimpleEntry( "child2Key1", "someValue" )
, new SimpleEntry( "child2Key2", "someValue" )
)
);
The below url is doing same as above answers. Instead of downloading some jar files and doing much activities, you can try to decompile by:
This should get you there every single time.
background-image: url(<%= asset_data_uri 'transparent_2x2.png'%>);
Try:
Type type = Type.GetType(inputString); //target type
object o = Activator.CreateInstance(type); // an instance of target type
YourType your = (YourType)o;
Jon Skeet is right as usually :)
Update: You can specify assembly containing target type in various ways, as Jon mentioned, or:
YourType your = (YourType)Activator.CreateInstance("AssemblyName", "NameSpace.MyClass");
In Swift 2.0:
let date = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let components = calendar.components([.Month, .Day], fromDate: date)
let (month, day) = (components.month, components.day)
The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename
method. See this deprecation note in the documentation for more detail.
This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg
method.
These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.
Before we get there, let's create a four column DataFrame.
df = pd.DataFrame({'A' : list('wwwwxxxx'),
'B':list('yyzzyyzz'),
'C':np.random.rand(8),
'D':np.random.rand(8)})
A B C D
0 w y 0.643784 0.828486
1 w y 0.308682 0.994078
2 w z 0.518000 0.725663
3 w z 0.486656 0.259547
4 x y 0.089913 0.238452
5 x y 0.688177 0.753107
6 x z 0.955035 0.462677
7 x z 0.892066 0.368850
Let's say we want to group by columns A, B
and aggregate column C
with mean
and median
and aggregate column D
with max
. The following code would do this.
df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})
D C
max mean median
A B
w y 0.994078 0.476233 0.476233
z 0.725663 0.502328 0.502328
x y 0.753107 0.389045 0.389045
z 0.462677 0.923551 0.923551
This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:
df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'},
'D':{'D_max': 'max'}})
D C
D_max C_mean C_median
A B
w y 0.994078 0.476233 0.476233
z 0.725663 0.502328 0.502328
x y 0.753107 0.389045 0.389045
z 0.462677 0.923551 0.923551
This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0)
.
I've developed jmxfuse which exposes JMX Mbeans as a Linux FUSE filesystem with similar functionality as the /proc fs. It relies on Jolokia as the bridge to JMX. Attributes and operations are exposed for reading and writing.
http://code.google.com/p/jmxfuse/
For example, to read an attribute:
me@oddjob:jmx$ cd log4j/root/attributes
me@oddjob:jmx$ cat priority
to write an attribute:
me@oddjob:jmx$ echo "WARN" > priority
to invoke an operation:
me@oddjob:jmx$ cd Catalina/none/none/WebModule/localhost/helloworld/operations/addParameter
me@oddjob:jmx$ echo "myParam myValue" > invoke
Same like update 3 but with modern css (=less rules) so that no special positioning on the pseudo element is required.
#box {_x000D_
background-color: #3D6AA2;_x000D_
width: 160px;_x000D_
height: 90px;_x000D_
position: absolute;_x000D_
top: calc(10% - 10px);_x000D_
left: calc(50% - 80px);_x000D_
}_x000D_
_x000D_
.box-shadow:after {_x000D_
content:"";_x000D_
position:absolute;_x000D_
width:100%;_x000D_
bottom:1px;_x000D_
z-index:-1;_x000D_
transform:scale(.9);_x000D_
box-shadow: 0px 0px 8px 2px #000000;_x000D_
}
_x000D_
<div id="box" class="box-shadow"></div>
_x000D_
All my previous answers have been using extra markup to get create this effect, which is not necessarily needed. I think this a much cleaner solution... the only trick is playing around with the values to get the right positioning of the shadow as well as the right strength/opacity of the shadow. Here's a new fiddle, using pseudo-elements:
http://jsfiddle.net/UnsungHero97/ARRRZ/2/
HTML
<div id="box" class="box-shadow"></div>
CSS
#box {
background-color: #3D6AA2;
width: 160px;
height: 90px;
margin-top: -45px;
margin-left: -80px;
position: absolute;
top: 50%;
left: 50%;
}
.box-shadow:after {
content: "";
width: 150px;
height: 1px;
margin-top: 88px;
margin-left: -75px;
display: block;
position: absolute;
left: 50%;
z-index: -1;
-webkit-box-shadow: 0px 0px 8px 2px #000000;
-moz-box-shadow: 0px 0px 8px 2px #000000;
box-shadow: 0px 0px 8px 2px #000000;
}
Apparently, you can do this with just an extra parameter to the box-shadow CSS as everyone else just pointed out. Here's the demo:
http://jsfiddle.net/K88H9/821/
CSS
-webkit-box-shadow: 0 4px 4px -2px #000000;
-moz-box-shadow: 0 4px 4px -2px #000000;
box-shadow: 0 4px 4px -2px #000000;
This would be a better solution. The extra parameter that is added is described as:
The fourth length is a spread distance. Positive values cause the shadow shape to expand in all directions by the specified radius. Negative values cause the shadow shape to contract.
Check out the demo at jsFiddle: http://jsfiddle.net/K88H9/4/
What I did was create a "shadow element" that would hide behind the actual element that you would want to have a shadow. I made the width of the "shadow element" to be exactly less wide than the actual element by 2 times the shadow you specify; then I aligned it properly.
HTML
<div id="wrapper">
<div id="element"></div>
<div id="shadow"></div>
</div>
CSS
#wrapper {
width: 84px;
position: relative;
}
#element {
background-color: #3D668F;
height: 54px;
width: 100%;
position: relative;
z-index: 10;
}
#shadow {
background-color: #3D668F;
height: 8px;
width: 80px;
margin-left: -40px;
position: absolute;
bottom: 0px;
left: 50%;
z-index: 5;
-webkit-box-shadow: 0px 2px 4px #000000;
-moz-box-shadow: 0px 2px 4px #000000;
box-shadow: 0px 2px 4px #000000;
}
Yes, you can do this with the same syntax you have provided. The first value controls the horizontal positioning and the second value controls the vertical positioning. So just set the first value to 0px
and the second to whatever offset you'd like as follows:
-webkit-box-shadow: 0px 5px #000000;
-moz-box-shadow: 0px 5px #000000;
box-shadow: 0px 5px #000000;
For more info on box shadows, check out these:
I hope this helps.
As per official Cordova documentation it supports only JDK 1.8 not greater till the date (April 2018). Or there might be problem with version detection script within cordova.
Answered this just to emphasize @rblarsen comment on question :
You don't need the style tags in the CSS-file
If you remove the style tag from your css file it will work.
Also it can be achieved with pure js in such a way:
var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
Just to have a simple and complete example for Python 3, which most people seem to be using now.
class MySuper(object):
def __init__(self,a):
self.a = a
class MySub(MySuper):
def __init__(self,a,b):
self.b = b
super().__init__(a)
my_sub = MySub(42,'chickenman')
print(my_sub.a)
print(my_sub.b)
gives
42
chickenman
Use the -ExpandProperty
flag of Select-Object
$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority
Update to answer the other question:
Note that you can as well just access the property:
$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority
So to get multiple of these into variables:
$var=Get-WSManInstance -enumerate wmicimv2/win32_process
$prio = $var.Priority
$pid = $var.ProcessID
DATEADD and DATEDIFF are better than CONVERTing to varchar. Both queries have the same execution plan, but execution plans are primarly about data access strategies and do not always reveal implicit costs involved in the CPU time taken to perform all the pieces. If both queries are run against a table with millions of rows, the CPU time using DateDiff can be close to 1/3rd of the Convert CPU time!
To see execution plans for queries:
set showplan_text on
GO
Both DATEADD and DATEDIFF will execute a CONVERT_IMPLICIT.
Although the CONVERT solution is simpler and easier to read for some, it is slower. There is no need to cast back to datetime (this is implicitly done by the server). There is also no real need in the DateDiff method for DateAdd afterward as the integer result will also be implicitly converted back to datetime.
SELECT CONVERT(varchar, MyDate, 101) FROM DatesTable
|--Compute Scalar(DEFINE:([Expr1004]=CONVERT(varchar(30),[TEST].[dbo].[DatesTable].[MyDate],101)))
|--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, MyDate)) FROM DatesTable
|--Compute Scalar(DEFINE:([Expr1004]=dateadd(day,(0),CONVERT_IMPLICIT(datetime,datediff(day,'1900-01-01 00:00:00.000',CONVERT_IMPLICIT(datetime,[TEST].[dbo].[DatesTable].[MyDate],0)),0))))
|--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))
Using FLOOR() as @digi suggested has performance closer to DateDiff, but is not recommended as casting the datetime data type to float and back does not always yield the original value.
Remember guys: Don't believe anyone. Look at the performance statistics, and test it yourself!
Be careful when you're testing your results. Selecting many rows to the client will hide the performance difference becauses it takes longer to send the rows over the network than it does to perform the calculations. So make sure that the work for all the rows is done by the server but there is no rowset sent to the client.
There seems to be confusion for some people about when cache optimization affects queries. Running two queries in the same batch or in separate batches has no effect on caching. So you can either expire the cache manually or simply run the queries back and forth multiple times. Any optimization for query #2 would also affect any subsequent queries, so throw out execution #1 if you like.
Here is full test script and performance results that prove DateDiff is substantially faster than converting to varchar.
The chances are that the problem is in one of the unit tests that you've asked Maven to run.
As such, fiddling with the heap size is the wrong approach. Instead, you should be looking at the unit test that has caused the OOME, and trying to figure out if it is the fault of the unit test or the code that it is testing.
Start by looking at the stack trace. If there isn't one, run mvn ... test
again with the -e
option.
If you are trying to ignore changes to a file that's already tracked in the repository (e.g. a dev.properties file that you would need to change for your local environment but you would never want to check in these changes) than what you want to do is:
git update-index --assume-unchanged <file>
If you wanna start tracking changes again
git update-index --no-assume-unchanged <file>
See git-update-index(1) Manual Page.
Also have a look at the skip-worktree
and no-skip-worktree
options for update-index if you need this to persist past a git-reset (via)
Update: Since people have been asking, here's a convenient (and updated since commented on below) alias for seeing which files are currently "ignored" (--assume-unchanged) in your local workspace
$ git config --global alias.ignored = !git ls-files -v | grep "^[[:lower:]]"
Using aggregate function like below :
[
{$group: {_id : {book : '$book',address:'$addr'}, total:{$sum :1}}},
{$project : {book : '$_id.book', address : '$_id.address', total : '$total', _id : 0}}
]
it will give you result like following :
{
"total" : 1,
"book" : "book33",
"address" : "address90"
},
{
"total" : 1,
"book" : "book5",
"address" : "address1"
},
{
"total" : 1,
"book" : "book99",
"address" : "address9"
},
{
"total" : 1,
"book" : "book1",
"address" : "address5"
},
{
"total" : 1,
"book" : "book5",
"address" : "address2"
},
{
"total" : 1,
"book" : "book3",
"address" : "address4"
},
{
"total" : 1,
"book" : "book11",
"address" : "address77"
},
{
"total" : 1,
"book" : "book9",
"address" : "address3"
},
{
"total" : 1,
"book" : "book1",
"address" : "address15"
},
{
"total" : 2,
"book" : "book1",
"address" : "address2"
},
{
"total" : 3,
"book" : "book1",
"address" : "address1"
}
I didn't quite get your expected result format, so feel free to modify this to one you need.
I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL
values while using UNIQUE
?" Or "How to only allow one UNIQUE
NULL
value?"
The question has already been answered, yes you can have duplicate NULL
values while using the UNIQUE
index.
Since I stumbled upon this answer while searching for "how to allow one UNIQUE
NULL
value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...
In MySQL you can not have one UNIQUE
NULL
value, however you can have one UNIQUE
empty value by inserting with the value of an empty string.
Warning: Numeric and types other than string may default to 0 or another default value.
There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.
Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.
import Tkinter as tk
root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")
frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")
root.mainloop()
According to OAUTH 2.0:
There will be Auth problem for this case beacuse FCM now using OAUTH 2
So I read firebase documentation and according to documentation new way to post data message is;
POST: https://fcm.googleapis.com/v1/projects/YOUR_FIREBASEDB_ID/messages:send
Headers
Key: Content-Type, Value: application/json
Auth
Bearer YOUR_TOKEN
Example Body
{
"message":{
"topic" : "xxx",
"data" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message"
}
}
}
In the url there is Database Id which you can find it on your firebase console. (Go project setttings)
And now lets take our token (It will valid only 1 hr):
First in the Firebase console, open Settings > Service Accounts. Click Generate New Private Key, securely store the JSON file containing the key. I was need this JSON file to authorize server requests manually. I downloaded it.
Then I create a node.js project and used this function to get my token;
var PROJECT_ID = 'YOUR_PROJECT_ID';
var HOST = 'fcm.googleapis.com';
var PATH = '/v1/projects/' + PROJECT_ID + '/messages:send';
var MESSAGING_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
var SCOPES = [MESSAGING_SCOPE];
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
getAccessToken().then(function(accessToken) {
console.log("TOKEN: "+accessToken)
})
});
function getAccessToken() {
return new Promise(function(resolve, reject) {
var key = require('./YOUR_DOWNLOADED_JSON_FILE.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
null
);
jwtClient.authorize(function(err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
Now I can use this token in my post request. Then I post my data message, and it is now handled by my apps onMessageReceived function.
CPMSifDlg::EncodeAndSend()
method is declared as non-static
and thus it must be called using an object of CPMSifDlg
. e.g.
CPMSifDlg obj;
return obj.EncodeAndSend(firstName, lastName, roomNumber, userId, userFirstName, userLastName);
If EncodeAndSend
doesn't use/relate any specifics of an object (i.e. this
) but general for the class CPMSifDlg
then declare it as static
:
class CPMSifDlg {
...
static int EncodeAndSend(...);
^^^^^^
};
In general:
select rand()*(@upper-@lower)+@lower;
For your question:
select rand()*(6-3)+3;
<=>
select rand()*3+3;
jminix is an embedded web based JMX console. Not sure if it's maintained any longer, but still.
if (!$_GET) echo "empty";
why do you need such a checking?
lol
you guys too direct-minded.
don't take as offense but sometimes not-minded at all
$_GET is very special variable, not like others.
it is supposed to be always set. no need to treat it as other variables.
when $_GET is not set and it's expected - it is emergency case and that's what "Undefined variable" notice invented for
Easiest way is probably to convert from a VARCHAR to a DATE; then format it back to a VARCHAR again in the format you want;
SELECT TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') FROM EmpTable;
As provided by ePharaoh, the answer is
/"([^"\\]*(\\.[^"\\]*)*)"/
To have the above apply to either single quoted or double quoted strings, use
/"([^"\\]*(\\.[^"\\]*)*)"|\'([^\'\\]*(\\.[^\'\\]*)*)\'/
If you have tried installing via the official docker-compose page, where you need to download the binary using curl:
curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
Then do not forget to add executable flag to the binary:
chmod +x /usr/local/bin/docker-compose
If docker-compose is installed using python-pip
sudo apt-get -y install python-pip
sudo pip install docker-compose
try using pip show --files docker-compose
to see where it is installed.
If docker-compose is installed in user path, then try:
sudo "PATH=$PATH" docker-compose
As I see from your updated post, docker-compose is installed in user path /home/user/.local/bin
and if this path is not in your local path $PATH
, then try:
sudo "PATH=$PATH:/home/user/.local/bin" docker-compose
Go to
Settings -> Preferences -> Backup/Autocompletion
Check Enable auto-completion on each input. By default the radio button for Function completion gets checked, that will complete related function name as you type. But when you are editing something other than code, you can check for Word completion.
Check Function parameters hint on input, if you find it difficult to remember function parameters and their ordering.
spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]
index=spell_list.index("Annual")
print(index)
You have it, that's all. But so, basically, what's the point of unions?
You can put in the same location content of different types. You have to know the type of what you have stored in the union (so often you put it in a struct
with a type tag...).
Why is this important? Not really for space gains. Yes, you can gain some bits or do some padding, but that's not the main point anymore.
It's for type safety, it enables you to do some kind of 'dynamic typing': the compiler knows that your content may have different meanings and the precise meaning of how your interpret it is up to you at run-time. If you have a pointer that can point to different types, you MUST use a union, otherwise you code may be incorrect due to aliasing problems (the compiler says to itself "oh, only this pointer can point to this type, so I can optimize out those accesses...", and bad things can happen).
Do you want something like in LINQ skip 5 and take 10?
SELECT TOP(10) * FROM MY_TABLE
WHERE ID not in (SELECT TOP(5) ID From My_TABLE);
This approach will work in any SQL version.
This is a classic case of rebase --onto
:
# let's go to current master (X, where quickfix2 should begin)
git checkout master
# replay every commit *after* quickfix1 up to quickfix2 HEAD.
git rebase --onto master quickfix1 quickfix2
So you should go from
o-o-X (master HEAD)
\
q1a--q1b (quickfix1 HEAD)
\
q2a--q2b (quickfix2 HEAD)
to:
q2a'--q2b' (new quickfix2 HEAD)
/
o-o-X (master HEAD)
\
q1a--q1b (quickfix1 HEAD)
This is best done on a clean working tree.
See git config --global rebase.autostash true
, especially after Git 2.10.
The basic difference between Servlets and JSP is that in Servlets we write java code and in that we embed HTML code and there is just reverse case with JSP . In JSP we write HTML code and in that we embed java code using tags provided by JSP.
For Angular(7+) Project:
::ng-deep .modal-backdrop.show {
opacity: 0.7 !important;
}
Otherwise you can use:
.modal-backdrop.show {
opacity: 0.7 !important;
}
I have faced the same issue. I almost wasted almost couple of weeks to resolved this issue. Finally I had on doubt on myself and tried to create another project by copy and paste some startup files like SplashScreen & LoginScreen.
But with the same code still i was getting SPAN_EXCLUSIVE_EXCLUSIVE.
Then i have removed the handler code from splash screen and tried again and Wow its working. I am not getting SPAN_EXCLUSIVE_EXCLUSIVE issue in logcat.
I wondering, why it is? till the time did not get any other solution but by removing handler from splash screen it is working.
Try and update here if it is resolved or not.
The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR']
or $_SERVER['REMOTE_HOST']
variables.
However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.
The below both functions are equivalent with the difference only in how and from where the values are retrieved.
getenv() is used to get the value of an environment variable in PHP.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$_SERVER is an array that contains server variables created by the web server.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
uint16_t
is guaranteed to be a unsigned integer that is 16 bits large
unsigned short int
is guaranteed to be a unsigned short integer
, where short integer
is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer
is 16 bits large.
Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler
Minimum Type Limits
Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.
Type Minimum Range
signed char -127 to +127 unsigned char 0 to 255 short int -32767 to +32767 unsigned short int 0 to 65535
Look at jQuery Toggle
HTML:
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
jQuery:
jQuery(document).ready(function(){
jQuery('#hideshow').live('click', function(event) {
jQuery('#content').toggle('show');
});
});
For versions of jQuery 1.7 and newer use
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#content').toggle('show');
});
});
For reference, kindly check this demo
write following statement in your app's build.gradle file.
com.android.support:appcompat-v7:18.0.+
That's it
Place your css in the following script and paste it into your CSS file.
@media screen and (-webkit-min-device-pixel-ratio:0) { your complete css style }
For example: @media screen and (-webkit-min-device-pixel-ratio:0) { container { margin-top: 120px;} }
Works like a charm.
If you want to do it from code behind, try this:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Message');", true);
We can also use this if we want to change all multiple joined blank spaces with a single character:
str.replace(/\s+/g,'X');
See it in action here: https://regex101.com/r/d9d53G/1
Explanation
/
\s+
/ g
\s+
matches any whitespace character (equal to [\r\n\t\f\v ]
)+
Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
The thread is very old, but I came looking for answer here hence providing new solution.
With MongoDB version 3.6+, it is now possible to use the positional operator to update all items in an array. See official documentation here.
Following query would work for the question asked here. I have also verified with Java-MongoDB driver and it works successfully.
.update( // or updateMany directly, removing the flag for 'multi'
{"events.profile":10},
{$set:{"events.$[].handled":0}}, // notice the empty brackets after '$' opearor
false,
true
)
Hope this helps someone like me.
If someone is looking for the simplest way without collections
module. I guess this will be helpful:
>>> s = "asldaksldkalskdla"
>>> {i:s.count(i) for i in set(s)}
{'a': 4, 'd': 3, 'k': 3, 's': 3, 'l': 4}
or
>>> [(i,s.count(i)) for i in set(s)]
[('a', 4), ('k', 3), ('s', 3), ('l', 4), ('d', 3)]
A very simple (and lame) one line solution is to use the window.onblur()
event to close the loading dialog. Of course, if it takes too long and the user decides to do something else (like reading emails) the loading dialog will close.
You can detect this only in limited circumstances. Specifically, in chrome if a file was selected earlier and then the file dialog is clicked and cancel clicked, Chrome clears the file and fires the onChange event.
https://code.google.com/p/chromium/issues/detail?id=2508
In this scenario, you can detect this by handling the onChange event and checking the files property.
Well, to all who actually can't find the error anywhere in your code, neither "undefined as it says in local storage nor null"..simply just comment out your code and write another one that actually removes the item in local storage ..after that ,u can comment or delet the current code and reset again the previous one by simply uncommenting it out (if u dint delet t ...if u did u can write it again:))
LocalStorage.setItem('Previous' , "removeprevious");
LocalStorage.removeItem('Previous');
Console.log(LocalStorage.getItem('Previous'));
Console will show null and that it ..reset your code again if t doesn't work, dude!you got errors.
sorry for my English!
In my case I had special instruction into nginx configuration file:
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
try_files $uri =404;
}
All clients have received '404' because nginx nothing known about Flask.
I hope it help someone.
One division is
A dynamically interpreted language is interpreted at runtime whereas a compiled language is compiled before execution.
I should add that as Jörg has pointed out, the interpreted / compiled distinction is not a feature of the language, but of the execution engine.
You might also be interested in this explanation of Type system, which is related and focuses more on the language aspect, instead of the execution engine. Most scripting languages are dynamically typed, whereas "normal" languages are mostly statically typed.
In general the division of statically vs dynamically typed languages is better defined and has more implications on the usability of the language.
The most common culprit for me has been Visual Studio trying to run the tests using a different architecture than the library it's testing. Unfortunately there are multiple places where it seems this can go wrong.
In VS 2017, try creating a Run Settings file, e.g. Default.runsettings
in your test project. If your main lib is x64, the contents should be:
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<RunConfiguration>
<TargetPlatform>x64</TargetPlatform>
</RunConfiguration>
</RunSettings>
Then choose this file from Test -> Test Settings -> Select Test Settings File.
Then, under Test -> Test Settings, Default Processor Architecture, choose the correct architecture again.
Be sure to Clean and Build the entire solution. You may need to close and reopen the Test Explorer window. Look for any additional errors in the Output -> Test window, for more clues about incorrect architecture types.
FYI additional Test Settings entries can be found here.
var persons = new List<Person>
{
new Person {ID = 1, Name = "jhon", Salary = 2500},
new Person {ID = 2, Name = "Sena", Salary = 1500},
new Person {ID = 3, Name = "Max", Salary = 5500},
new Person {ID = 4, Name = "Gen", Salary = 3500}
};
var acertainperson = persons.Where(p => p.Name == "jhon").First();
Console.WriteLine("{0}: {1} points",
acertainperson.Name, acertainperson.Salary);
jhon: 2500 points
var doingprettywell = persons.Where(p => p.Salary > 2000);
foreach (var person in doingprettywell)
{
Console.WriteLine("{0}: {1} points",
person.Name, person.Salary);
}
jhon: 2500 points
Max: 5500 points
Gen: 3500 points
var astupidcalc = from p in persons
where p.ID > 2
select new
{
Name = p.Name,
Bobos = p.Salary*p.ID,
Bobotype = "bobos"
};
foreach (var person in astupidcalc)
{
Console.WriteLine("{0}: {1} {2}",
person.Name, person.Bobos, person.Bobotype);
}
Max: 16500 bobos
Gen: 14000 bobos
This one is great:
<style type="text/css">
textarea.test
{
width: 100%;
height: 100%;
border-color: Transparent;
}
</style>
<textarea class="test"></textarea>
The answers using grep are wrong. You need to add an -x option to match the entire line otherwise lines like #text to add
will still match when looking to add exactly text to add
.
So the correct solution is something like:
grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar
%UserProfile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Cache
paste this in your address bar and enter, you will get all the files
just rename the files extension into the extension which u r looking.
ie. open command prompt then
C:\>cd %UserProfile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Cache
then
C:\Users\User\AppData\Local\Google\Chrome\User Data\Default\Cache>ren *.* *.jpg
Take a look at this project: http://code.google.com/p/tarlog-plugins/downloads/detail?name=tarlog.eclipse.plugins_1.4.2.jar&can=2&q=
It has some other features, but most importantly, it has Ctrl++ and Ctrl+- to change the font size, it's awesome.
To access from remote server to mydb database only
GRANT ALL PRIVILEGES ON mydb.* TO 'root'@'192.168.2.21';
To access from remote server to all databases.
GRANT ALL PRIVILEGES ON * . * TO 'root'@'192.168.2.21';
The general approach is to convert the data to long format (using melt()
from package reshape
or reshape2
) or gather()
/pivot_longer()
from the tidyr
package:
library("reshape2")
library("ggplot2")
test_data_long <- melt(test_data, id="date") # convert to long format
ggplot(data=test_data_long,
aes(x=date, y=value, colour=variable)) +
geom_line()
Also see this question on reshaping data from wide to long.
If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.
To get it done only with XAML you need to add Validation Rules for individual properties. But i would recommend you to go with code behind approach. In your code, define your specifications in properties setters and throw exceptions when ever it doesn't compliance to your specifications. And use error template to display your errors to user in UI. Your XAML will look like this
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="CustomTextBoxTextStyle" TargetType="TextBox">
<Setter Property="Foreground" Value="Green" />
<Setter Property="MaxLength" Value="40" />
<Setter Property="Width" Value="392" />
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Trigger.Setters>
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
<Setter Property="Background" Value="Red"/>
</Trigger.Setters>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox Name="tb2" Height="30" Width="400"
Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"
Style="{StaticResource CustomTextBoxTextStyle}"/>
</Grid>
Code Behind:
public partial class MainWindow : Window
{
private ExampleViewModel m_ViewModel;
public MainWindow()
{
InitializeComponent();
m_ViewModel = new ExampleViewModel();
DataContext = m_ViewModel;
}
}
public class ExampleViewModel : INotifyPropertyChanged
{
private string m_Name = "Type Here";
public ExampleViewModel()
{
}
public string Name
{
get
{
return m_Name;
}
set
{
if (String.IsNullOrEmpty(value))
{
throw new Exception("Name can not be empty.");
}
if (value.Length > 12)
{
throw new Exception("name can not be longer than 12 charectors");
}
if (m_Name != value)
{
m_Name = value;
OnPropertyChanged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
My approach is slightly different. I do not copy properties into new instances, I just change the prototype of existing POJOs (may not work well on older browsers). Each class is responsible for providing a SetPrototypes method to set the prototoypes of any child objects, which in turn provide their own SetPrototypes methods.
(I also use a _Type property to get the class name of unknown objects but that can be ignored here)
class ParentClass
{
public ID?: Guid;
public Child?: ChildClass;
public ListOfChildren?: ChildClass[];
/**
* Set the prototypes of all objects in the graph.
* Used for recursive prototype assignment on a graph via ObjectUtils.SetPrototypeOf.
* @param pojo Plain object received from API/JSON to be given the class prototype.
*/
private static SetPrototypes(pojo: ParentClass): void
{
ObjectUtils.SetPrototypeOf(pojo.Child, ChildClass);
ObjectUtils.SetPrototypeOfAll(pojo.ListOfChildren, ChildClass);
}
}
class ChildClass
{
public ID?: Guid;
public GrandChild?: GrandChildClass;
/**
* Set the prototypes of all objects in the graph.
* Used for recursive prototype assignment on a graph via ObjectUtils.SetPrototypeOf.
* @param pojo Plain object received from API/JSON to be given the class prototype.
*/
private static SetPrototypes(pojo: ChildClass): void
{
ObjectUtils.SetPrototypeOf(pojo.GrandChild, GrandChildClass);
}
}
Here is ObjectUtils.ts:
/**
* ClassType lets us specify arguments as class variables.
* (where ClassType == window[ClassName])
*/
type ClassType = { new(...args: any[]): any; };
/**
* The name of a class as opposed to the class itself.
* (where ClassType == window[ClassName])
*/
type ClassName = string & {};
abstract class ObjectUtils
{
/**
* Set the prototype of an object to the specified class.
*
* Does nothing if source or type are null.
* Throws an exception if type is not a known class type.
*
* If type has the SetPrototypes method then that is called on the source
* to perform recursive prototype assignment on an object graph.
*
* SetPrototypes is declared private on types because it should only be called
* by this method. It does not (and must not) set the prototype of the object
* itself - only the protoypes of child properties, otherwise it would cause a
* loop. Thus a public method would be misleading and not useful on its own.
*
* https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript
*/
public static SetPrototypeOf(source: any, type: ClassType | ClassName): any
{
let classType = (typeof type === "string") ? window[type] : type;
if (!source || !classType)
{
return source;
}
// Guard/contract utility
ExGuard.IsValid(classType.prototype, "type", <any>type);
if ((<any>Object).setPrototypeOf)
{
(<any>Object).setPrototypeOf(source, classType.prototype);
}
else if (source.__proto__)
{
source.__proto__ = classType.prototype.__proto__;
}
if (typeof classType["SetPrototypes"] === "function")
{
classType["SetPrototypes"](source);
}
return source;
}
/**
* Set the prototype of a list of objects to the specified class.
*
* Throws an exception if type is not a known class type.
*/
public static SetPrototypeOfAll(source: any[], type: ClassType): void
{
if (!source)
{
return;
}
for (var i = 0; i < source.length; i++)
{
this.SetPrototypeOf(source[i], type);
}
}
}
Usage:
let pojo = SomePlainOldJavascriptObjectReceivedViaAjax;
let parentObject = ObjectUtils.SetPrototypeOf(pojo, ParentClass);
// parentObject is now a proper ParentClass instance
Here is how to split one commit in IntelliJ IDEA, PyCharm, PhpStorm etc
In Version Control log window, select the commit you would like to
split, right click and select the Interactively Rebase from Here
mark the one you want to split as edit
, click Start
Rebasing
You should see a yellow tag is placed meaning that the HEAD is set
to that commit. Right click on that commit, select Undo Commit
Now those commits are back to staging area, you can then commit them separately. After all change has been committed, the old commit becomes inactive.
This is an ES6 version
let date = new Date()
let newDate = new Date(date.setDate(date.getDate()-30))
console.log(newDate.getMonth()+1 + '/' + newDate.getDate() + '/' + newDate.getFullYear() )
A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.
Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute.
A data contract can be defined as follows:
It describes the external format of data passed to and from service operations
It defines the structure and types of data exchanged in service messages
We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract and DataMember attribute.
One workaround that I have done is:
Ctrl
+ a
to select everything in the slideCtrl
+ c
to copy itCtrl
+ v
to paste all the vectors/text into the imageIt looks pretty much exactly the same as in Powerpoint, and the vectors/text are very clean with their transparency edges.
Use In
instead of =
select * from dbo.books
where isbn in (select isbn from dbo.lending
where act between @fdate and @tdate
and stat ='close'
)
or you can use Exists
SELECT t1.*,t2.*
FROM books t1
WHERE EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
t2.act between @fdate and @tdate and t2.stat ='close' )
def import_class(cl):
d = cl.rfind(".")
classname = cl[d+1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname)
If you use any(lst)
you see that lst
is the iterable, which is a list of some items. If it contained [0, False, '', 0.0, [], {}, None]
(which all have boolean values of False
) then any(lst)
would be False
. If lst
also contained any of the following [-1, True, "X", 0.00001]
(all of which evaluate to True
) then any(lst)
would be True
.
In the code you posted, x > 0 for x in lst
, this is a different kind of iterable, called a generator expression. Before generator expressions were added to Python, you would have created a list comprehension, which looks very similar, but with surrounding []
's: [x > 0 for x in lst]
. From the lst
containing [-1, -2, 10, -4, 20]
, you would get this comprehended list: [False, False, True, False, True]
. This internal value would then get passed to the any
function, which would return True
, since there is at least one True
value.
But with generator expressions, Python no longer has to create that internal list of True(s)
and False(s)
, the values will be generated as the any
function iterates through the values generated one at a time by the generator expression. And, since any
short-circuits, it will stop iterating as soon as it sees the first True
value. This would be especially handy if you created lst
using something like lst = range(-1,int(1e9))
(or xrange
if you are using Python2.x). Even though this expression will generate over a billion entries, any
only has to go as far as the third entry when it gets to 1
, which evaluates True
for x>0
, and so any
can return True
.
If you had created a list comprehension, Python would first have had to create the billion-element list in memory, and then pass that to any
. But by using a generator expression, you can have Python's builtin functions like any
and all
break out early, as soon as a True
or False
value is seen.
Use an associative array:
$code_names = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France');
foreach($code_names as $code => $name) {
//...
}
I believe that using an associative array is the most sensible approach as opposed to using array_combine()
because once you have an associative array, you can simply use array_keys()
or array_values()
to get exactly the same array you had before.
WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL '-3' DAY);
use quotes on the -3 value
Currently, ExplorerCanvas is the only option to emulate HTML5 canvas for IE6, 7, and 8. You're also right about its performance, which is pretty poor.
I found a particle simulatior that benchmarks the difference between true HTML5 canvas handling in Google Chrome, Safari, and Firefox, vs ExplorerCanvas in IE. The results show that the major browsers that do support the canvas tag run about 20 to 30 times faster than the emulated HTML5 in IE with ExplorerCanvas.
I doubt that anyone will go through the effort of creating an alternative because 1) excanvas.js is about as cleanly coded as it gets and 2) when IE9 is released all of the major browsers will finally support the canvas object. Hopefully, We'll get IE9 within a year
Eric @ www.webkrunk.com
Use:
Get-Service BITS | Select StartType
Or use:
(Get-Service -Name BITS).StartType
Then
Set-Service BITS -StartupType xxx
[PowerShell 5.1]
Assuming your byte1
is a byte(8bits), When you do a bitwise AND of a byte with 0xFF, you are getting the same byte.
So byte1
is the same as byte1 & 0xFF
Say byte1
is 01001101
, then byte1 & 0xFF = 01001101 & 11111111 = 01001101 = byte1
If byte1 is of some other type say integer of 4 bytes, bitwise AND with 0xFF leaves you with least significant byte(8 bits) of the byte1.
I second that.
Dex2jar will generate a WORKING jar, which you can add as your project source, with the xmls you got from apktool.
However, JDGUI generates .java files which have ,more often than not, errors.
It has got something to do with code obfuscation I guess.
For a field named isCurrent
, the correct getter / setter naming is setCurrent()
/ isCurrent()
(at least that's what Eclipse thinks), which is highly confusing and can be traced back to the main problem:
Your field should not be called isCurrent
in the first place. Is is a verb and verbs are inappropriate to represent an Object's state. Use an adjective instead, and suddenly your getter / setter names will make more sense:
private boolean current;
public boolean isCurrent(){
return current;
}
public void setCurrent(final boolean current){
this.current = current;
}
To expand on RiggsFolly’s answer—or for anyone who is facing the same issue but is using Apache 2.2 or below—this format should work well:
Order Deny,Allow
Deny from all
Allow from 127.0.0.1 ::1
Allow from localhost
Allow from 192.168
Allow from 10
Satisfy Any
For more details on the format changes for Apache 2.4, the official Upgrading to 2.2 from 2.4 page is pretty clear & concise. Key point being:
The old access control idioms should be replaced by the new authentication mechanisms, although for compatibility with old configurations, the new module
mod_access_compat
is provided.
Which means, system admins around the world don’t necessarily have to panic about changing Apache 2.2 configs to be 2.4 compliant just yet.
Gustavo Niemeyer's answer is great. But in Windows, runtime proc is mostly in another dir, like this:
"C:\Users\XXX\AppData\Local\Temp"
If you use relative file path, like "/config/api.yaml"
, this will use your project path where your code exists.
Could you provide a whole makefile? But right now I can tell - you should check that "install" target already exists. So, check Makefile whether it contains a
install: (anything there)
line. If not, there is no such target and so make has right. Probably you should use just "make" command to compile and then use it as is or install yourself, manually.
Install is not any standard of make, it is just a common target, that could exists, but not necessary.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class CharCountFromAllFilesInFolder {
public static void main(String[] args)throws IOException {
try{
//C:\Users\MD\Desktop\Test1
System.out.println("Enter Your FilePath:");
Scanner sc = new Scanner(System.in);
Map<Character,Integer> hm = new TreeMap<Character, Integer>();
String s1 = sc.nextLine();
File file = new File(s1);
File[] filearr = file.listFiles();
for (File file2 : filearr) {
System.out.println(file2.getName());
FileReader fr = new FileReader(file2);
BufferedReader br = new BufferedReader(fr);
String s2 = br.readLine();
for (int i = 0; i < s2.length(); i++) {
if(!hm.containsKey(s2.charAt(i))){
hm.put(s2.charAt(i), 1);
}//if
else{
hm.put(s2.charAt(i), hm.get(s2.charAt(i))+1);
}//else
}//for2
System.out.println("The Char Count: "+hm);
}//for1
}//try
catch(Exception e){
System.out.println("Please Give Correct File Path:");
}//catch
}
}
We can use context Like this try now Where the parent is the ViewGroup.
Context context = parent.getContext();
I couldn't just pass by... Here's my Haskell one-liner. It's actually quite readable:
sum <$> (read <$>) <$> lines <$> getContents
Unfortunately there's no ghci -e
to just run it, so it needs the main function, print and compilation.
main = (sum <$> (read <$>) <$> lines <$> getContents) >>= print
To clarify, we read entire input (getContents
), split it by lines
, read
as numbers and sum
. <$>
is fmap
operator - we use it instead of usual function application because sure this all happens in IO. read
needs an additional fmap
, because it is also in the list.
$ ghc sum.hs
[1 of 1] Compiling Main ( sum.hs, sum.o )
Linking sum ...
$ ./sum
1
2
4
^D
7
Here's a strange upgrade to make it work with floats:
main = ((0.0 + ) <$> sum <$> (read <$>) <$> lines <$> getContents) >>= print
$ ./sum
1.3
2.1
4.2
^D
7.6000000000000005
Html for content, CSS for style
<body style='margin-top:0;margin-left:0;margin-right:0;'>
Twitter bootstrap tables can be styled and well designed. You can style your table just adding some classes on your table and it’ll look nice. You might use it on your data reports, showing information, etc.
You can use :
basic table
Striped rows
Bordered table
Hover rows
Condensed table
Contextual classes
Responsive tables
Striped rows Table :
<table class="table table-striped" width="647">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Address</th>
<th>mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Thomas bell</td>
<td>Brick lane, London</td>
<td>[email protected]</td>
</tr>
<tr>
<td height="29">2</td>
<td>Yan Chapel</td>
<td>Toronto Australia</td>
<td>[email protected]</td>
</tr>
<tr>
<td>3</td>
<td>Pit Sampras</td>
<td>Berlin, Germany</td>
<td>Pit @yahoo.com</td>
</tr>
</tbody>
</table>
Condensed table :
Compacting a table you need to add class class=”table table-condensed” .
<table class="table table-condensed" width="647">
<thead>
<tr>
<th>#</th>
<th>Sample Name</th>
<th>Address</th>
<th>Mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Thomas bell</td>
<td>Brick lane, London</td>
<td>[email protected]</td>
</tr>
<tr>
<td height="29">2</td>
<td>Yan Chapel</td>
<td>Toronto Australia</td>
<td>[email protected]</td>
</tr>
<tr>
<td>3</td>
<td>Pit Sampras</td>
<td>Berlin, Germany</td>
<td>Pit @yahoo.com</td>
</tr>
<tr>
<td></td>
<td colspan="3" align="center"></td>
</tr>
</tbody>
</table>
Ref : http://twitterbootstrap.org/twitter-bootstrap-table-example-tutorial
There are two big difference the sorting and the character matching:
Sorting:
utf8mb4_general_ci
removes all accents and sorts one by one which may create incorrect sort results.utf8mb4_unicode_ci
sorts accurate.Character Matching
They match characters differently.
For example, in utf8mb4_unicode_ci
you have i != i
, but in utf8mb4_general_ci
it holds i=i
.
For example, imagine you have a row with name="Yilmaz"
. Then
select id from users where name='Yilmaz';
would return the row if collocation is utf8mb4_general_ci
, but if it is collocated with utf8mb4_unicode_ci
it would not return the row!
On the other hand we have that a=ª
and ß=ss
in utf8mb4_unicode_ci
which is not the case in utf8mb4_general_ci
. So imagine you have a row with name="ªßi"
, then
select id from users where name='assi';
would return the row if collocation is utf8mb4_unicode_ci
, but would not return a row if collocation is set to utf8mb4_general_ci
.
A full list of matches for each collocation may be found here.
“JSONP is JSON with extra code” would be too easy for the real world. No, you gotta have little discrepancies. What’s the fun in programming if everything just works?
Turns out JSON is not a subset of JavaScript. If all you do is take a JSON object and wrap it in a function call, one day you will be bitten by strange syntax errors, like I was today.
When you call Business.where(:user_id => current_user.id)
you will get an array. This Array may have no objects or one or many objects in it, but it won't be null. Thus the check == nil will never be true.
You can try the following:
if Business.where(:user_id => current_user.id).count == 0
So you check the number of elements in the array and compare them to zero.
or you can try:
if Business.find_by_user_id(current_user.id).nil?
this will return one or nil.
This is what I did. Works well.
First add the OkHttp to the gradle build file of the app module:
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
Then make a class extending Application
import android.app.Application;
import com.jakewharton.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;
public class Global extends Application {
@Override
public void onCreate() {
super.onCreate();
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE));
Picasso built = builder.build();
built.setIndicatorsEnabled(true);
built.setLoggingEnabled(true);
Picasso.setSingletonInstance(built);
}
}
add it to the Manifest file as follows :
<application
android:name=".Global"
.. >
</application>
Now use Picasso as you normally would. No changes.
EDIT:
if you want to use cached images only. Call the library like this. I've noticed that if we don't add the networkPolicy, images won't show up in an fully offline start even if they are cached. The code below solves the problem.
Picasso.with(this)
.load(url)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView);
EDIT #2
the problem with the above code is that if you clear cache, Picasso will keep looking for it offline in cache and fail, the following code example looks at the local cache, if not found offline, it goes online and replenishes the cache.
Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
//Try again online if cache failed
Picasso.with(getActivity())
.load(posts.get(position).getImageUrl())
.error(R.drawable.header)
.into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Log.v("Picasso","Could not fetch image");
}
});
}
});
<v-layout justify-center>
<v-card-actions>
<v-btn primary>
<span>SignUp</span>
</v-btn>`enter code here`
</v-card-actions>
</v-layout>
You could not iterate or store more data than the length of your array. In this case you could do like this:
for (int i = 0; i <= name.length - 1; i++) {
// ....
}
Or this:
for (int i = 0; i < name.length; i++) {
// ...
}
With me the problem was solved by removing the type
attribute:
<embed name="myMusic" loop="true" hidden="true" src="Music.mp3"></embed>
Cerntainly not the cleanest way.
If you're using HTML5: MP3 isn't supported by Firefox. Wav and Ogg are though. Here you can find an overview of which browser support which type of audio: http://www.w3schools.com/html/html5_audio.asp
<pre lang="xml" >{{xmlString}}</pre>
This worked for me. Thanks to http://www.codeproject.com/Answers/998872/Display-XML-in-HTML-Div#answer1
Simple kotlin version
fun download(link: String, path: String) {
URL(link).openStream().use { input ->
FileOutputStream(File(path)).use { output ->
input.copyTo(output)
}
}
}
EDIT
or as extension
fun String.saveTo(path: String) {
URL(this).openStream().use { input ->
FileOutputStream(File(path)).use { output ->
input.copyTo(output)
}
}
}
// ...
"http://example.site/document".saveTo("some/path/file")
You need to put the worksheet identifier in your range statements as shown below ...
Option Explicit
Dim ws As Worksheet, a As Range
Sub forEachWs()
For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next
End Sub
Sub resizingColumns()
ws.Range("A:A").ColumnWidth = 20.14
ws.Range("B:B").ColumnWidth = 9.71
ws.Range("C:C").ColumnWidth = 35.86
ws.Range("D:D").ColumnWidth = 30.57
ws.Range("E:E").ColumnWidth = 23.57
ws.Range("F:F").ColumnWidth = 21.43
ws.Range("G:G").ColumnWidth = 18.43
ws.Range("H:H").ColumnWidth = 23.86
ws.Range("i:I").ColumnWidth = 27.43
ws.Range("J:J").ColumnWidth = 36.71
ws.Range("K:K").ColumnWidth = 30.29
ws.Range("L:L").ColumnWidth = 31.14
ws.Range("M:M").ColumnWidth = 31
ws.Range("N:N").ColumnWidth = 41.14
ws.Range("O:O").ColumnWidth = 33.86
End Sub
Difference between each annotation are :
+-------------------------------------------------------------------------------------------------------+
¦ Feature ¦ Junit 4 ¦ Junit 5 ¦
¦--------------------------------------------------------------------------+--------------+-------------¦
¦ Execute before all test methods of the class are executed. ¦ @BeforeClass ¦ @BeforeAll ¦
¦ Used with static method. ¦ ¦ ¦
¦ For example, This method could contain some initialization code ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after all test methods in the current class. ¦ @AfterClass ¦ @AfterAll ¦
¦ Used with static method. ¦ ¦ ¦
¦ For example, This method could contain some cleanup code. ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute before each test method. ¦ @Before ¦ @BeforeEach ¦
¦ Used with non-static method. ¦ ¦ ¦
¦ For example, to reinitialize some class attributes used by the methods. ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after each test method. ¦ @After ¦ @AfterEach ¦
¦ Used with non-static method. ¦ ¦ ¦
¦ For example, to roll back database modifications. ¦ ¦ ¦
+-------------------------------------------------------------------------------------------------------+
Most of annotations in both versions are same, but few differs.
Order of Execution.
Dashed box -> optional annotation.
I do the following, handles any overflows:
var totalPages = totalResults.IsDivisble(recordsperpage) ? totalResults/(recordsperpage) : totalResults/(recordsperpage) + 1;
And use this extension for if there's 0 results:
public static bool IsDivisble(this int x, int n)
{
return (x%n) == 0;
}
Also, for the current page number (wasn't asked but could be useful):
var currentPage = (int) Math.Ceiling(recordsperpage/(double) recordsperpage) + 1;
Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.
Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/
Kudos to this answer for showing me the way.
The margins vary depending on the printer. In Windows GDI, you call the following functions to get the built-in margins, the "no-print zone":
GetDeviceCaps(hdc, PHYSICALWIDTH);
GetDeviceCaps(hdc, PHYSICALHEIGHT);
GetDeviceCaps(hdc, PHYSICALOFFSETX);
GetDeviceCaps(hdc, PHYSICALOFFSETY);
Printing right to the edge is called a "bleed" in the printing industry. The only laser printer I ever knew to print right to the edge was the Xerox 9700: 120 ppm, $500K in 1980.
var_dump(extension_loaded('curl'));
Pretty self explanatory.
repeat{
statements...
if(condition){
break
}
}
Or something like that I would think. To get the effect of the do while loop, simply check for your condition at the end of the group of statements.
int returnIntLength(int value){
int counter = 0;
if(value < 0)
{
counter++;
value = -value;
}
else if(value == 0)
return 1;
while(value > 0){
value /= 10;
counter++;
}
return counter;
}
I think this method is well suited for this task:
value and answers:
-50 -> 3 //it will count - as one character as well if you dont want to count minus then remove counter++ from 5th line.
566666 -> 6
0 -> 1
505 -> 3
Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:
<T extends ClassA & InterfaceB>
See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName
for each one that you need.
This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max
, which (wrapped onto two lines) is:
public static <T extends Object & Comparable<? super T>> T
max(Collection<? extends T> coll)
why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.
It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:
class classB { }
interface interfaceC { }
public class MyClass<T extends classB & interfaceC> {
Class<T> variable;
}
to get variable
that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>
, the class name must come first, and interfaces follow. And of course you can only list a single class.
Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.
You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).
On UNIX / Linux / Mac OS X you can copy and override files, can't you? So how about this solution:
cp /dev/null /var/mail/root
Shorter version of previous using map()
function (works for python 2.7):
"".join(map(chr, myList))
If your compiler supports C++11 standard, there is a constructor inheritance using using
(pun intended). For more see Wikipedia C++11 article. You write:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
using A::A;
};
This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.
Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.
pip
itself is just a normal python package. Thus you can install pip with pip.
Of cource, you don't want to affect the system's pip, install it inside a virtualenv.
pip install pip==1.2.1
Check this reference link:
Give Safe User Permission To Use Port 80
Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like
http://ip:port/
Unfortunately, unless you sign on as root, you’ll normally have to use a URL like
http://ip:port
- where port number > 1024.A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:
sudo apt-get install libcap2-bin sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``
Now, when you tell a Node application that you want it to run on port 80, it will not complain.
I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.
[TestMethod]
public void OneIsOne()
{
using (ConsoleRedirector cr = new ConsoleRedirector())
{
Assert.IsFalse(cr.ToString().Contains("New text"));
/* call some method that writes "New text" to stdout */
Assert.IsTrue(cr.ToString().Contains("New text"));
}
}
The disposable ConsoleRedirector
is defined as:
internal class ConsoleRedirector : IDisposable
{
private StringWriter _consoleOutput = new StringWriter();
private TextWriter _originalConsoleOutput;
public ConsoleRedirector()
{
this._originalConsoleOutput = Console.Out;
Console.SetOut(_consoleOutput);
}
public void Dispose()
{
Console.SetOut(_originalConsoleOutput);
Console.Write(this.ToString());
this._consoleOutput.Dispose();
}
public override string ToString()
{
return this._consoleOutput.ToString();
}
}
I faced similar problem but I followed following steps in my case :-
1).inside project under .idea folder open modules.xml. 2).check if there are two entries for same iml file. 3).delete one of duplicate entry and close android studio or build gradle file again.
In my case it worked. Hope it helps
There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.
Try this if you have array and add objects to it.
$product_details = array();
foreach ($products_in_store as $key => $objects) {
$product_details[$key] = new stdClass(); //the magic
$product_details[$key]->product_id = $objects->id;
//see new object member created on the fly without warning.
}
This sends ARRAY of Objects for later use~!
If you're using Spring Boot, the simplest way to disable the Spring Security default headers is to use security.headers.*
properties. In particular, if you want to disable the X-Frame-Options
default header, just add the following to your application.properties
:
security.headers.frame=false
There is also security.headers.cache
, security.headers.content-type
, security.headers.hsts
and security.headers.xss
properties that you can use. For more information, take a look at SecurityProperties
.
Use onChange={this.handleChange.bind(this, "name")
method and value={this.state.fields["name"]}
on input text field and below that create span element to show error, see the below example.
export default class Form extends Component {
constructor(){
super()
this.state ={
fields: {
name:'',
email: '',
message: ''
},
errors: {},
disabled : false
}
}
handleValidation(){
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
if(!fields["name"]){
formIsValid = false;
errors["name"] = "Name field cannot be empty";
}
if(typeof fields["name"] !== "undefined" && !fields["name"] === false){
if(!fields["name"].match(/^[a-zA-Z]+$/)){
formIsValid = false;
errors["name"] = "Only letters";
}
}
if(!fields["email"]){
formIsValid = false;
errors["email"] = "Email field cannot be empty";
}
if(typeof fields["email"] !== "undefined" && !fields["email"] === false){
let lastAtPos = fields["email"].lastIndexOf('@');
let lastDotPos = fields["email"].lastIndexOf('.');
if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') === -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
formIsValid = false;
errors["email"] = "Email is not valid";
}
}
if(!fields["message"]){
formIsValid = false;
errors["message"] = " Message field cannot be empty";
}
this.setState({errors: errors});
return formIsValid;
}
handleChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
handleSubmit(e){
e.preventDefault();
if(this.handleValidation()){
console.log('validation successful')
}else{
console.log('validation failed')
}
}
render(){
return (
<form onSubmit={this.handleSubmit.bind(this)} method="POST">
<div className="row">
<div className="col-25">
<label htmlFor="name">Name</label>
</div>
<div className="col-75">
<input type="text" placeholder="Enter Name" refs="name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
<span style={{color: "red"}}>{this.state.errors["name"]}</span>
</div>
</div>
<div className="row">
<div className="col-25">
<label htmlFor="exampleInputEmail1">Email address</label>
</div>
<div className="col-75">
<input type="email" placeholder="Enter Email" refs="email" aria-describedby="emailHelp" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
<span style={{color: "red"}}>{this.state.errors["email"]}</span>
</div>
</div>
<div className="row">
<div className="col-25">
<label htmlFor="message">Message</label>
</div>
<div className="col-75">
<textarea type="text" placeholder="Enter Message" rows="5" refs="message" onChange={this.handleChange.bind(this, "message")} value={this.state.fields["message"]}></textarea>
<span style={{color: "red"}}>{this.state.errors["message"]}</span>
</div>
</div>
<div className="row">
<button type="submit" disabled={this.state.disabled}>{this.state.disabled ? 'Sending...' : 'Send'}</button>
</div>
</form>
)
}
}
Array.prototype.find() does just that, more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
What is ARIA?
ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.
The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.
It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.
Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.
I did a search, which requires you to input a certain value, then it will look for a value from the list which contains your input:
my_list = ['abc-123',
'def-456',
'ghi-789',
'abc-456'
]
imp = raw_input('Search item: ')
for items in my_list:
val = items
if any(imp in val for items in my_list):
print(items)
Try searching for 'abc'.
document.getElementsByClassName('btn-pageMenu')
delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display
(if it's the first element from that list you want to change.
If you want to change style.display
for all nodes loop through the list:
var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
elems[i].style.display = 'block';
}
to be complete: if you use jquery it is as simple as:
?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????
Yes - this is possible. In order to do it, you need to assign a tabindex...
<div tabindex="0">Hello World</div>
A tabindex of 0 will put the tag "in the natural tab order of the page". A higher number will give it a specific order of priority, where 1 will be the first, 2 second and so on.
You can also give a tabindex of -1, which will make the div only focus-able by script, not the user.
document.getElementById('test').onclick = function () {_x000D_
document.getElementById('scripted').focus();_x000D_
};
_x000D_
div:focus {_x000D_
background-color: Aqua;_x000D_
}
_x000D_
<div>Element X (not focusable)</div>_x000D_
<div tabindex="0">Element Y (user or script focusable)</div>_x000D_
<div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>_x000D_
<div id="test">Set Focus To Element Z</div>
_x000D_
Obviously, it is a shame to have an element you can focus by script that you can't focus by other input method (especially if a user is keyboard only or similarly constrained). There are also a whole bunch of standard elements that are focusable by default and have semantic information baked in to assist users. Use this knowledge wisely.
This a single solution, in where your_field is a field that will set and new_value is a new value field, that can a function or a single value
foreach ($array as $key => $item) {
$item["your_field"] = "new_value";
$array[$key] = $item;
}
In your case new_value will be a date() function
index=1
value=2
awk -F"," -v i=$index -v v=$value '$(i)==v' file
I got this to finally work in a semi-automatic fashion without the use of scripts... but it does take up 3 cells to pull it off. Borrowing from a bit from previous answers, I start with a cell that has nothing more than =NOW() it in to show the time. For example, we'll put this into cell A1...
=NOW()
This function updates automatically every minute. In the next cell, put a pointer formula using the sheets own name to point to the previous cell. For example, we'll put this in A2...
='Sheet Name'!A1
Cell formatting aside, cell A1 and A2 should at this point display the same content... namely the current time.
And, the last cell is the part I'm borrowing from previous solutions using a regex expression to pull the fomula from the second cell and then strip out the name of the sheet from said formula. For example, we'll put this into cell A3...
=REGEXREPLACE(FORMULATEXT(A2),"='?([^']+)'?!.*","$1")
At this point, the resultant value displayed in A3 should be the name of the sheet.
From my experience, as soon as the name of the sheet is changed, the formula in A2 is immediately updated. However that's not enough to trigger A3 to update. But, every minute when cell A1 recalculates the time, the result of the formula in cell A2 is subsequently updated and then that in turn triggers A3 to update with the new sheet name. It's not a compact solution... but it does seem to work.
I was driving myself crazy with this exact problem. My JSON Marshaller and Unmarshaller were not populating my Go struct. Then I found the solution at https://eager.io/blog/go-and-json:
"As with all structs in Go, it’s important to remember that only fields with a capital first letter are visible to external programs like the JSON Marshaller."
After that, my Marshaller and Unmarshaller worked perfectly!
Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.
Angular 5 Solution:
import {HttpClient} from '@angular/common/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = {} as any; // Set any options you like
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.httpClient.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Angular 4 Solution:
// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = new RequestOptions();
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.http.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Within the environment align
from the package amsmath
it is possible to combine the use of \label
and \tag
for each equation or line. For example, the code:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
Write
\begin{align}
x+y\label{eq:eq1}\tag{Aa}\\
x+z\label{eq:eq2}\tag{Bb}\\
y-z\label{eq:eq3}\tag{Cc}\\
y-2z\nonumber
\end{align}
then cite \eqref{eq:eq1} and \eqref{eq:eq2} or \eqref{eq:eq3} separately.
\end{document}
produces:
string utf8String = "Acción";
string propEncodeString = string.Empty;
byte[] utf8_Bytes = new byte[utf8String.Length];
for (int i = 0; i < utf8String.Length; ++i)
{
utf8_Bytes[i] = (byte)utf8String[i];
}
propEncodeString = Encoding.UTF8.GetString(utf8_Bytes, 0, utf8_Bytes.Length);
Output should look like
Acción
day’s displays day's
call DecodeFromUtf8();
private static void DecodeFromUtf8()
{
string utf8_String = "day’s";
byte[] bytes = Encoding.Default.GetBytes(utf8_String);
utf8_String = Encoding.UTF8.GetString(bytes);
}
Use RGB values combined with opacity to get the transparency that you wish.
For instance,
<div style=" background: rgb(255, 0, 0) ; opacity: 0.2;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.4;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.6;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.8;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 1;"> </div>
Similarly, with actual values without opacity, will give the below.
<div style=" background: rgb(243, 191, 189) ; "> </div>
<div style=" background: rgb(246, 143, 142) ; "> </div>
<div style=" background: rgb(249, 95 , 94) ; "> </div>
<div style=" background: rgb(252, 47, 47) ; "> </div>
<div style=" background: rgb(255, 0, 0) ; "> </div>
You can have a look at this WORKING EXAMPLE.
Now, if we specifically target your issue, here is the WORKING DEMO SPECIFIC TO YOUR ISSUE.
The HTML
<div class="social">
<img src="http://www.google.co.in/images/srpr/logo4w.png" border="0" />
</div>
The CSS:
social img{
opacity:0.5;
}
.social img:hover {
opacity:1;
background-color:black;
cursor:pointer;
background: rgb(255, 0, 0) ; opacity: 0.5;
}
Hope this helps Now.
This is an old but still very relevant question, so I'll add this: What's the first thing you look for when you open up a class file that you may or may not have read before? Fields? Properties? I've realized from experience that almost invariably I go hunting for the constructors, because the most basic thing to understand is how this object is constructed.
Therefore, I've started putting constructors first in class files, and the result has been psychologically very positive. The standard recommendation of putting constructors after a bunch of other things feels dissonant.
The upcoming primary constructor feature in C# 6 provides evidence that the natural place for a constructor is at the very top of a class - in fact primary constructors are specified even before the open brace.
It's funny how much of a difference a reordering like this makes. It reminds me of how using
statements used to be ordered - with the System namespaces first. Visual Studio's "Organize Usings" command used this order. Now using
s are just ordered alphabetically, with no special treatment given to System namespaces. The result just feels simpler and cleaner.
Have you looked at the DateUtils truncate method in Apache Commons Lang?
Date truncatedDate = DateUtils.truncate(new Date(), Calendar.DATE);
will remove the time element.
cd
" to go to your home folder.touch .bash_profile
".open -e .bash_profile
" to open .bash_profile in TextEdit.alias mvn='/[Your file location]/apache-maven-x.x.x/bin/mvn'
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdkx.x.x_xx.jdk/Contents/Home/
(Make sure there are no speech marks or apostrophe's) 8. Make sure you fill the required data (ex your file location and version number).
. .bash_profile
" to reload .bash_profile and update any functions you add. (*make sure you separate the dots with a single space).mvn -version
If successful you should see the following:
Apache Maven 3.1.1
Maven home: /Users/admin/Maven/apache-maven-3.1.1
Java version: 1.7.0_51, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.9.1", arch: "x86_64", family: "mac"
In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for example key at index 1)
print([key for key in x.keys()][1])
# To print a specific value (for example value at index 1)
print([value for value in x.values()][1])
# To print a pair of a key with its value (for example pair at index 2)
print(([key for key in x.keys()][2], [value for value in x.values()][2]))
# To print a key and a different value (for example key at index 0 and value at index 1)
print(([key for key in x.keys()][0], [value for value in x.values()][1]))
# To print all keys and values concatenated together
print(''.join(str(key) + '' + str(value) for key, value in x.items()))
# To print all keys and values separated by commas
print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))
# To print all pairs of (key, value) one at a time
for e in range(len(x)):
print(([key for key in x.keys()][e], [value for value in x.values()][e]))
# To print all pairs (key, value) in a tuple
print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))
If your app for some reason crashes without good stacktrace. Try debug it from first line, and go line by line until crash. Then you will have answer, which line is causing you trouble. Proably you could then wrapp it into try catch block and print error output.
This works for me.
private OnClickListener mDisconnectListener;
mDisconnectListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
};
...
... onCreateView(...){
mButtonDisconnect = (Button) rootView.findViewById(R.id.button_disconnect);
mButtonDisconnect.setOnClickListener(mDisconnectListener);
...
}
Replace
if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged
with
if (obj === undefined) { return undefined;} // return undefined for undefined
if (obj === null) { return null;} // null unchanged
There are three basic types of join:
INNER
join compares two tables and only returns results where a match exists. Records from the 1st table are duplicated when they match multiple results in the 2nd. INNER joins tend to make result sets smaller, but because records can be duplicated this isn't guaranteed.CROSS
join compares two tables and return every possible combination of rows from both tables. You can get a lot of results from this kind of join that might not even be meaningful, so use with caution.OUTER
join compares two tables and returns data when a match is available or NULL values otherwise. Like with INNER join, this will duplicate rows in the one table when it matches multiple records in the other table. OUTER joins tend to make result sets larger, because they won't by themselves remove any records from the set. You must also qualify an OUTER join to determine when and where to add the NULL values:
LEFT
means keep all records from the 1st table no matter what and insert NULL values when the 2nd table doesn't match. RIGHT
means the opposite: keep all records from the 2nd table no matter what and insert NULL values whent he 1st table doesn't match. FULL
means keep all records from both tables, and insert a NULL value in either table if there is no match.Often you see will the OUTER
keyword omitted from the syntax. Instead it will just be "LEFT JOIN", "RIGHT JOIN", or "FULL JOIN". This is done because INNER and CROSS joins have no meaning with respect to LEFT, RIGHT, or FULL, and so these are sufficient by themselves to unambiguously indicate an OUTER join.
Here is an example of when you might want to use each type:
INNER
: You want to return all records from the "Invoice" table, along with their corresponding "InvoiceLines". This assumes that every valid Invoice will have at least one line.OUTER
: You want to return all "InvoiceLines" records for a particular Invoice, along with their corresponding "InventoryItem" records. This is a business that also sells service, such that not all InvoiceLines will have an IventoryItem.CROSS
: You have a digits table with 10 rows, each holding values '0' through '9'. You want to create a date range table to join against, so that you end up with one record for each day within the range. By CROSS-joining this table with itself repeatedly you can create as many consecutive integers as you need (given you start at 10 to 1st power, each join adds 1 to the exponent). Then use the DATEADD() function to add those values to your base date for the range.I tested this code and Works
Javascript
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: 200,
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
});
function sendFile(file, editor, welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
data: data,
type: "POST",
url: "Your URL POST (php)",
cache: false,
contentType: false,
processData: false,
success: function(url) {
editor.insertImage(welEditable, url);
}
});
}
});
</script>
PHP
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$filename = $name.
'.'.$ext;
$destination = '/assets/images/'.$filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'http://test.yourdomain.al/images/'.$filename; //change this URL
} else {
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Update:
After 0.7.0 onImageUpload
should be inside callbacks
option as mentioned by @tugberk
$('#summernote').summernote({
height: 200,
callbacks: {
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
}
});
In general, an alternative to case when ...
is coalesce(nullif(x,bad_value),y)
(that cannot be used in OP's case). For example,
select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from ( (select 'abc' as x, '' as y)
union all (select 'def' as x, 'ghi' as y)
union all (select '' as x, 'jkl' as y)
union all (select null as x, 'mno' as y)
union all (select 'pqr' as x, null as y)
) q
gives:
coalesce | coalesce | x | y
----------+----------+-----+-----
abc | abc | abc |
ghi | def | def | ghi
jkl | jkl | | jkl
mno | mno | | mno
pqr | pqr | pqr |
(5 rows)
ES6 introduces the new Math.trunc
method. This allows to fix @MarkElliot's answer to make it work for negative numbers too:
var div = Math.trunc(y/x);
var rem = y % x;
Note that Math
methods have the advantage over bitwise operators that they work with numbers over 231.
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
Unlike constructors, where throwing exceptions can be a useful way to indicate that object creation succeeded, exceptions should not be thrown in destructors.
The problem occurs when an exception is thrown from a destructor during the stack unwinding process. If that happens, the compiler is put in a situation where it doesn’t know whether to continue the stack unwinding process or handle the new exception. The end result is that your program will be terminated immediately.
Consequently, the best course of action is just to abstain from using exceptions in destructors altogether. Write a message to a log file instead.
Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been repeatedly asked, too, because some people would like to get the actual response headers of the original page request without issuing another one.
If an HTTP request is made over AJAX, it is possible to get the response headers with the getAllResponseHeaders()
method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the fetchSimilarHeaders()
function below. Note that this is a work-around to the problem that won't be reliable for some applications.
myXMLHttpRequest.getAllResponseHeaders();
The API was specified in the following candidate recommendation for XMLHttpRequest: XMLHttpRequest - W3C Candidate Recommendation 3 August 2010
Specifically, the getAllResponseHeaders()
method was specified in the following section: w3.org: XMLHttpRequest
: the getallresponseheaders()
method
The MDN documentation is good, too: developer.mozilla.org: XMLHttpRequest
.
This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.
This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the current page (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.
The following are a few suggestions for getting around that problem.
If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.
function fetchSimilarHeaders (callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
//
// The following headers may often be similar
// to those of the original page request...
//
if (callback && typeof callback === 'function') {
callback(request.getAllResponseHeaders());
}
}
};
//
// Re-request the same page (document.location)
// We hope to get the same or similar response headers to those which
// came with the current page, but we have no guarantee.
// Since we are only after the headers, a HEAD request may be sufficient.
//
request.open('HEAD', document.location, true);
request.send(null);
}
This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.
There are some BOM properties (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g. navigator.userAgent
is set to the value of the HTTP User-Agent
header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.
If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.
In order to capture keystrokes in a Forms control, you must derive a new class that is based on the class of the control that you want, and you override the ProcessCmdKey().
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
//handle your keys here
}
Example :
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
//capture up arrow key
if (keyData == Keys.Up )
{
MessageBox.Show("You pressed Up arrow key");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Full source...Arrow keys in C#
Vayne
The correct One is here (All the above posts will give Cartesian product result when we have more then one index on a table)
select s.name, t.name, i.name, c.name from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id
AND i.index_id = ic.index_id
inner join sys.columns c on c.object_id = t.object_id
and ic.column_id = c.column_id
where i.index_id > 0
and i.type in (1, 2) -- clustered & nonclustered only
and i.is_primary_key = 0 -- do not include PK indexes
and i.is_unique_constraint = 0 -- do not include UQ
and i.is_disabled = 0
and i.is_hypothetical = 0
and ic.key_ordinal > 0
AND t.name = 'DimCustomer'
order by ic.key_ordinal
My problem was that my parent class had no @Test
methodes. I used there only some utilities. When I declared it abstract
it works.
I made this powershell script to unblock all files on a share on my server
Get-ChildItem "\\ServerName\e$\MyDirectory\" -Recurse -File | % {
Unblock-File -Path $_.FullName
}
This will Work For You
http://twitter.com/share?text=text goes here&url=http://url goes here&hashtags=hashtag1,hashtag2,hashtag3
Here is a Live Example About it
There are many ways to achieve this, like flatten-and-filter or simply enumerate, but I think using Boolean/mask array is the easiest one (and iirc a much faster one):
>>> y = np.array([[123,24123,32432], [234,24,23]])
array([[ 123, 24123, 32432],
[ 234, 24, 23]])
>>> b = y > 200
>>> b
array([[False, True, True],
[ True, False, False]], dtype=bool)
>>> y[b]
array([24123, 32432, 234])
>>> len(y[b])
3
>>>> y[b].sum()
56789
Update:
As nneonneo has answered, if all you want is the number of elements that passes threshold, you can simply do:
>>>> (y>200).sum()
3
which is a simpler solution.
Speed comparison with filter
:
### use boolean/mask array ###
b = y > 200
%timeit y[b]
100000 loops, best of 3: 3.31 us per loop
%timeit y[y>200]
100000 loops, best of 3: 7.57 us per loop
### use filter ###
x = y.ravel()
%timeit filter(lambda x:x>200, x)
100000 loops, best of 3: 9.33 us per loop
%timeit np.array(filter(lambda x:x>200, x))
10000 loops, best of 3: 21.7 us per loop
%timeit filter(lambda x:x>200, y.ravel())
100000 loops, best of 3: 11.2 us per loop
%timeit np.array(filter(lambda x:x>200, y.ravel()))
10000 loops, best of 3: 22.9 us per loop
*** use numpy.where ***
nb = np.where(y>200)
%timeit y[nb]
100000 loops, best of 3: 2.42 us per loop
%timeit y[np.where(y>200)]
100000 loops, best of 3: 10.3 us per loop
no idea how this happened, but i had the same problem. I had to reset my root password: http://www.jovicailic.org/2012/04/reset-forgotten-mysql-root-password-under-windows/
But after my databases that i had previously were either dropped or the new connection did not connect to them. Either way i couldn't access them via workbench. But i could use MySQL again, which was a win for me
Looks like you're trying to execute a windows file (.exe) Surely you ought to be using powershell. Anyway on a Linux bash shell a simple one-liner will suffice.
[/home/$] for filename in /Data/*.txt; do for i in {0..3}; do ./MyProgam.exe Data/filenameLogs/$filename_log$i.txt; done done
Or in a bash
#!/bin/bash
for filename in /Data/*.txt;
do
for i in {0..3};
do ./MyProgam.exe Data/filename.txt Logs/$filename_log$i.txt;
done
done
Here is how to set variables in the package from code -
using Microsoft.SqlServer.Dts.Runtime;
private void Execute_Package()
{
string pkgLocation = @"c:\test.dtsx";
Package pkg;
Application app;
DTSExecResult pkgResults;
Variables vars;
app = new Application();
pkg = app.LoadPackage(pkgLocation, null);
vars = pkg.Variables;
vars["A_Variable"].Value = "Some value";
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
Console.WriteLine("Package ran successfully");
else
Console.WriteLine("Package failed");
}
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
Here's one important thing to know in addition to everything said before.
Query plans are often too complex to be represented by the built-in XML column type which has a limitation of 127 levels of nested elements. That is one of the reasons why sys.dm_exec_query_plan may return NULL
or even throw an error in earlier MS SQL versions, so generally it's safer to use sys.dm_exec_text_query_plan instead. The latter also has a useful bonus feature of selecting a plan for a particular statement rather than the whole batch. Here's how you use it to view plans for currently running statements:
SELECT p.query_plan
FROM sys.dm_exec_requests AS r
OUTER APPLY sys.dm_exec_text_query_plan(
r.plan_handle,
r.statement_start_offset,
r.statement_end_offset) AS p
The text column in the resulting table is however not very handy compared to an XML column. To be able to click on the result to be opened in a separate tab as a diagram, without having to save its contents to a file, you can use a little trick (remember you cannot just use CAST(... AS XML)
), although this will only work for a single row:
SELECT Tag = 1, Parent = NULL, [ShowPlanXML!1!!XMLTEXT] = query_plan
FROM sys.dm_exec_text_query_plan(
-- set these variables or copy values
-- from the results of the above query
@plan_handle,
@statement_start_offset,
@statement_end_offset)
FOR XML EXPLICIT
You may use the class java.util.Random with method
char c = (char)(rnd.nextInt(128-32))+32
20x to get Bytes, which you interpret as ASCII. If you're fine with ASCII.
32 is the offset, from where the characters are printable in general.
var cubes = [["string", "string"], ["string", "string"]];
for(var i = 0; i < cubes.length; i++) {
for(var j = 0; j < cubes[i].length; j++) {
console.log(cubes[i][j]);
}
}
I just type following keywords in the opened terminal;
See details in the below image. (VSCode version 1.19.1 - windows 10 OS)
It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)
The documentation for collection interfaces says:
Set — a collection that cannot contain duplicate elements.
List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements.
So if you don't want duplicates, you probably shouldn't use a list.
On Android use:
android.text.TextUtils.join(",", ids);
In C and C++, the &&
and ||
operators "short-circuit". That means that they only evaluate a parameter if required. If the first parameter to &&
is false, or the first to ||
is true, the rest will not be evaluated.
The code you posted is safe, though I question why you'd include an empty else
block.
Run ./mnistCUDNN
in /usr/src/cudnn_samples_v7/mnistCUDNN
Here is an example:
cudnnGetVersion() : 7005 , CUDNN_VERSION from cudnn.h : 7005 (7.0.5)
Host compiler version : GCC 5.4.0
There are 1 CUDA capable devices on your machine :
device 0 : sms 30 Capabilities 6.1, SmClock 1645.0 Mhz, MemSize (Mb) 24446, MemClock 4513.0 Mhz, Ecc=0, boardGroupID=0
Using device 0
In C#, float
is an alias for System.Single
(a bit like int
is an alias for System.Int32
).
Are you using a shared hosting provider? It could be master settings overriding anything you're trying to change. Have you tried adding those into your .htaccess?
php_value upload_max_filesize 10M
php_value post_max_size 10M
I wonder whether the below method is what you want.
You can use defaultdict
.
>>> from collections import defaultdict
>>> s = [('red',1), ('blue',2), ('red',3), ('blue',4), ('red',1), ('blue',4)]
>>> d = defaultdict(list)
>>> for k, v in s:
d[k].append(v)
>>> sorted(d.items())
[('blue', [2, 4, 4]), ('red', [1, 3, 1])]
You can try configure SQL server:
NOTE: ALL TCP port is 1433 Finally, restart the server.
Another solutions using vim (just for reference).
Solution 1:
Open file in vim vim filename
, then execute command :% normal Jj
This command is very easy to understand:
After that, save the file and exit with :wq
Solution 2:
Execute the command in shell, vim -c ":% normal Jj" filename
, then save the file and exit with :wq
.
In order to avoid troubles compiling third party libraries that need boost installed in your system, run this:
sudo port install boost +universal
You could use KEY
unique key (combination of the data) that changes with props, and that component will be rerendered with updated props.
In my case , I got this Error in Tensorflow , Reason was i was trying to feed a array with different length or sequences :
example :
import tensorflow as tf
input_x = tf.placeholder(tf.int32,[None,None])
word_embedding = tf.get_variable('embeddin',shape=[len(vocab_),110],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01))
embedding_look=tf.nn.embedding_lookup(word_embedding,input_x)
with tf.Session() as tt:
tt.run(tf.global_variables_initializer())
a,b=tt.run([word_embedding,embedding_look],feed_dict={input_x:example_array})
print(b)
And if my array is :
example_array = [[1,2,3],[1,2]]
Then i will get error :
ValueError: setting an array element with a sequence.
but if i do padding then :
example_array = [[1,2,3],[1,2,0]]
Now it's working.
However this question is seeking to find the last row using VBA, I think it would be good to include an array formula for worksheet function as this gets visited frequently:
{=ADDRESS(MATCH(INDEX(D:D,MAX(IF(D:D<>"",ROW(D:D)-ROW(D1)+1)),1),D:D,0),COLUMN(D:D))}
You need to enter the formula without brackets and then hit Shift + Ctrl + Enter to make it an array formula.
This will give you address of last used cell in the column D.
There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.
They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.
More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.
The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.
TCP never drops data so no, there is no way to indicate a server should forget about some segment.
Here is an in place replaceAll that will modify the passed in StringBuilder. I thought that I would post this as I was looking to do replaceAll with out creating a new String.
public static void replaceAll(StringBuilder sb, Pattern pattern, String replacement) {
Matcher m = pattern.matcher(sb);
while(m.find()) {
sb.replace(m.start(), m.end(), replacement);
}
}
I was shocked how simple the code to do this was (for some reason I thought changing the StringBuilder while using the matcher would throw of the group start/end but it does not).
This is probably faster than the other regex answers because the pattern is already compiled and your not creating a new String but I didn't do any benchmarking.
this code will return duplicate value in same array
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
if(array_count_values($arr)[$item] > 1){
echo "Found Matched value : ".$item." <br />";
}
}
When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor
method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.
This method is sort of similar to a while (!condition)
sleep loop, but
yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.
export const sleep = (ms: number) => {
return new Promise(resolve => setTimeout(resolve, ms))
}
/**
* Wait until the condition tested in a function returns true, or until
* a timeout is exceeded.
* @param interval The frenequency with which the boolean function contained in condition is called.
* @param timeout The maximum time to allow for booleanFunction to return true
* @param booleanFunction: A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.
*/
export const waitFor = async function (interval: number, timeout: number,
booleanFunction: Function): Promise<boolean> {
let elapsed = 1;
if (booleanFunction()) return true;
while (elapsed < timeout) {
elapsed += interval;
await sleep(interval);
if (booleanFunction()) {
return true;
}
}
return false;
}
The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:
async recalcAccountTotals() : number {
this.accountService.refresh(); //start the async process.
if (this.accounts.dirty) {
let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
}
if(!updateResult) {
console.error("Account refresh timed out, recalc aborted");
return NaN;
}
return ... //calculate the account total.
}
int uniqueId = 0;
int getUniqueId()
{
return uniqueId++;
}
Add synchronized
if you want it to be thread safe.
Another example for the C++11 standard:
set<int> data;
data.insert(4);
data.insert(5);
for (const int &number : data)
cout << number;
Type in your URL localhost/[name of your folder in htdocs]
EDITED
You can look into sys.tables for checking existence desired table:
IF NOT EXISTS (SELECT * FROM sys.tables
WHERE name = N'YourTable' AND type = 'U')
BEGIN
CREATE TABLE [SchemaName].[YourTable](
....
....
....
)
END