A very fast implementation of the Sieve of Atkin is Dan Bernstein's primegen. This sieve is more efficient than the Sieve of Eratosthenes. His page has some benchmark information.
You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.
The System.exit(0)
will terminates the currently running Java Virtual Machine.
Here is a dplyr
based option:
newV = df %>% slice(1) %>% unlist(use.names = FALSE)
# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()
Until CSS's flexbox becomes more mainstream, you can always just absolutely position the sidebar, sticking it zero pixels away from the top and bottom, then set a margin on your main container to compensate.
JSFiddle
HTML
<section class="sidebar">I'm a sidebar.</section>
<section class="main">I'm the main section.</section>
CSS
section.sidebar {
width: 250px;
position: absolute;
top: 0;
bottom: 0;
background-color: green;
}
section.main { margin-left: 250px; }
Note: This is an über simple way to do this but you'll find bottom
does not mean "bottom of page," but "bottom of window." The sidebar will probably abrubtly end if your main content scrolls down.
esModuleInterop
generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:
//ts
import React from 'react'
//js
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
__importDefault
: If the module is not an es
module then what is returned by require becomes the default. This means that if you use default import on a commonjs
module, the whole module is actually the default.
__importStar
is best described in this PR:
TypeScript treats a namespace import (i.e.
import * as foo from "foo"
) as equivalent toconst foo = require("foo")
. Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.Babel first requires in the module, and checks for a property named
__esModule
. If__esModule
is set totrue
, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:
- All properties are plucked off of the require'd module and made available as named imports.
- The originally require'd module is made available as a default import.
So we get this:
// ts
import * as React from 'react'
// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));
allowSyntheticDefaultImports
is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react'
will raise the error Module '".../node_modules/@types/react/index"' has no default export.
if allowSyntheticDefaultImports
is false
.
Taking a look at the source code of OpenPyXL (IterableWorksheet) I've figured out how to get the column and row count from an iterator worksheet:
wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]
row_count = sheet.get_highest_row() - 1
column_count = letter_to_index(sheet.get_highest_column()) + 1
IterableWorksheet.get_highest_column
returns a string with the column letter that you can see in Excel, e.g. "A", "B", "C" etc. Therefore I've also written a function to translate the column letter to a zero based index:
def letter_to_index(letter):
"""Converts a column letter, e.g. "A", "B", "AA", "BC" etc. to a zero based
column index.
A becomes 0, B becomes 1, Z becomes 25, AA becomes 26 etc.
Args:
letter (str): The column index letter.
Returns:
The column index as an integer.
"""
letter = letter.upper()
result = 0
for index, char in enumerate(reversed(letter)):
# Get the ASCII number of the letter and subtract 64 so that A
# corresponds to 1.
num = ord(char) - 64
# Multiply the number with 26 to the power of `index` to get the correct
# value of the letter based on it's index in the string.
final_num = (26 ** index) * num
result += final_num
# Subtract 1 from the result to make it zero-based before returning.
return result - 1
I still haven't figured out how to get the column sizes though, so I've decided to use a fixed-width font and automatically scaled columns in my application.
After a long time finally i found that! Here my Way: File -> New Project -> Android Project From Existing Code -> Browse to your project root directory finish!
write like this:
<div class="parent">
<a href="http://www.example.com">example</a>
</div>
CSS
.parent{
text-align:center
}
I had the same problem, but in my case it turned out to be a cookie issue. The guys working on the back-end had changed the path of the JSESSIONID cookie that's set when we log in to our app, and I had an old cookie by that name on my computer, but with the old path. So when I tried logging in the browser (Chrome) sent two cookies called JSESSIONID, with different values, to the server - which understandably confused it - so it cancelled the request. Deleting the cookies from my computer fixed it.
LR is link register used to hold the return address for a function call.
SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.
From the ARM architecture reference:
SP, the Stack Pointer
Register R13 is used as a pointer to the active stack.
In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.
LR, the Link Register
Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.
When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:
• Return with a BX LR instruction.
• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...
Adding to @pranay-rana's list:
Third way is:
function passFromValue(){
var x = 15;
return x;
}
function passToValue() {
var y = passFromValue();
console.log(y);//15
}
passToValue();
My personal feeling when it comes to reading
if(!status) : if not status
if(status == false) : if status is false
if you are not used to !status reading. I see no harm doing as the second way.
if you use "active" instead of status I thing if(!active) is more readable
As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically. If you look at the source of your plnkr, notice that for the second directive where replace is false that the div tag is still there. For the first directive it is not.
First result:
<span myd1="">directive template1</span>
Second result:
<div myd2=""><span>directive template2</span></div>
Use this to change column name by colname function.
colnames(newprice)[1] = "premium"
colnames(newprice)[2] = "change"
colnames(newprice)[3] = "newprice"
array = ["value1", "value2", "value3"]
it's not so much jquery as javascript
You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.
It should look like that :
#!/usr/bin/env python
or the real path
#!/usr/bin/python
You should also check the file have the right to be execute. chmod +x file.py
As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)
The answer for the last two can also be deducted from the golden rule in C:
Declaration follows use.
int (*arr2)[8];
What happens if you dereference arr2
? You get an array of 8 integers.
int *(arr3[8]);
What happens if you take an element from arr3
? You get a pointer to an integer.
This also helps when dealing with pointers to functions. To take sigjuice's example:
float *(*x)(void )
What happens when you dereference x
? You get a function that you can call with no arguments. What happens when you call it? It will return a pointer to a float
.
Operator precedence is always tricky, though. However, using parentheses can actually also be confusing because declaration follows use. At least, to me, intuitively arr2
looks like an array of 8 pointers to ints, but it is actually the other way around. Just takes some getting used to. Reason enough to always add a comment to these declarations, if you ask me :)
edit: example
By the way, I just stumbled across the following situation: a function that has a static matrix and that uses pointer arithmetic to see if the row pointer is out of bounds. Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_ELEM(ar) (sizeof(ar) / sizeof((ar)[0]))
int *
put_off(const int newrow[2])
{
static int mymatrix[3][2];
static int (*rowp)[2] = mymatrix;
int (* const border)[] = mymatrix + NUM_ELEM(mymatrix);
memcpy(rowp, newrow, sizeof(*rowp));
rowp += 1;
if (rowp == border) {
rowp = mymatrix;
}
return *rowp;
}
int
main(int argc, char *argv[])
{
int i = 0;
int row[2] = {0, 1};
int *rout;
for (i = 0; i < 6; i++) {
row[0] = i;
row[1] += i;
rout = put_off(row);
printf("%d (%p): [%d, %d]\n", i, (void *) rout, rout[0], rout[1]);
}
return 0;
}
Output:
0 (0x804a02c): [0, 0]
1 (0x804a034): [0, 0]
2 (0x804a024): [0, 1]
3 (0x804a02c): [1, 2]
4 (0x804a034): [2, 4]
5 (0x804a024): [3, 7]
Note that the value of border never changes, so the compiler can optimize that away. This is different from what you might initially want to use: const int (*border)[3]
: that declares border as a pointer to an array of 3 integers that will not change value as long as the variable exists. However, that pointer may be pointed to any other such array at any time. We want that kind of behaviour for the argument, instead (because this function does not change any of those integers). Declaration follows use.
(p.s.: feel free to improve this sample!)
If you want to get the back arrow on a Toolbar that's not set as your SupportActionBar:
(kotlin)
val resId = getResIdFromAttribute(toolbar.context, android.R.attr.homeAsUpIndicator)
toolbarFilter.navigationIcon = ContextCompat.getDrawable(toolbar.context, resId)
toolbarFilter.setNavigationOnClickListener { fragmentManager?.popBackStack() }
to get res from attributes:
@AnyRes
fun getResIdFromAttribute(context: Context, @AttrRes attr: Int): Int {
if (attr == 0) return 0
val typedValueAttr = TypedValue()
context.theme.resolveAttribute(attr, typedValueAttr, true)
return typedValueAttr.resourceId
}
let df
be the name of the Pandas DataFrame and any value that is numpy.nan
is a null value.
If you want to see which columns has nulls and which do not(just True and False)
df.isnull().any()
If you want to see only the columns that has nulls
df.loc[:, df.isnull().any()].columns
If you want to see the count of nulls in every column
df.isna().sum()
If you want to see the percentage of nulls in every column
df.isna().sum()/(len(df))*100
If you want to see the percentage of nulls in columns only with nulls:
df.loc[:,list(df.loc[:,df.isnull().any()].columns)].isnull().sum()/(len(df))*100
EDIT 1:
If you want to see where your data is missing visually:
import missingno
missingdata_df = df.columns[df.isnull().any()].tolist()
missingno.matrix(df[missingdata_df])
I don't know of a global setting nither but you can try this:
If you want to filter only items that are less than 7 days old then you just use
Filter
Created
is greater than or equal to
[Today]-7
Note - the screenshot is incorrect.
[Today] is fully supported in view filters in 2007 and onwards (just keep the spaces out!) and you only need to muck around with calculated columns in 2003.
DataSet ds = new DataSet();
DataTable dt = new DataTable("MyTable");
dt.Columns.Add(new DataColumn("id",typeof(int)));
dt.Columns.Add(new DataColumn("name", typeof(string)));
DataRow dr = dt.NewRow();
dr["id"] = 123;
dr["name"] = "John";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
I think this need to be run from the Management Shell rather than the console, it sounds like the module isn't being imported into the Powershell console. You can add the module by running:
Add-PSSnapin Microsoft.Sharepoint.Powershell
in the Powershell console.
use git bundle, or clone
copying the git directory is not a good solution because it is not atomic. If you have a large repository that takes a long time to copy and someone pushes to your repository, it will affect your back up. Cloning or making a bundle will not have this problem.
I generally try to avoid expressions with ng-show and ng-hide as they were designed as booleans, not conditionals. If I need both conditional and boolean logic, I prefer to put in the conditional logic using ng-if as the first check, then add in an additional check for the boolean logic with ng-show and ng-hide
Howerver, if you want to use a conditional for ng-show or ng-hide, here is a link with some examples: Conditional Display using ng-if, ng-show, ng-hide, ng-include, ng-switch
Starting file:
line 1
line 2
line 3
line 4
Code:
with open("filename.txt", "r") as f:
lines = f.readlines()
for line in lines:
stripped = line.strip()
print(stripped)
Output:
line 1
line 2
line 3
line 4
You can use a while loop like this:
String text = "Hello";
while (text.length() < 10) { text += "*"; }
System.out.println(text);
Will give you:
Hello*****
Or get the same result with a custom method:
public static String extendString(String text, String symbol, Integer len) {
while (text.length() < len) { text += symbol; }
return text;
}
Then just call:
extendString("Hello", "*", 10)
It may also be a good idea to set a length check to prevent infinite loop.
The Adjusted R-squared is close to, but different from, the value of R2. Instead of being based on the explained sum of squares SSR and the total sum of squares SSY, it is based on the overall variance (a quantity we do not typically calculate), s2T = SSY/(n - 1) and the error variance MSE (from the ANOVA table) and is worked out like this: adjusted R-squared = (s2T - MSE) / s2T.
This approach provides a better basis for judging the improvement in a fit due to adding an explanatory variable, but it does not have the simple summarizing interpretation that R2 has.
If I haven't made a mistake, you should verify the values of adjusted R-squared and R-squared as follows:
s2T <- sum(anova(v.lm)[[2]]) / sum(anova(v.lm)[[1]])
MSE <- anova(v.lm)[[3]][2]
adj.R2 <- (s2T - MSE) / s2T
On the other side, R2 is: SSR/SSY, where SSR = SSY - SSE
attach(v)
SSE <- deviance(v.lm) # or SSE <- sum((epm - predict(v.lm,list(n_days)))^2)
SSY <- deviance(lm(epm ~ 1)) # or SSY <- sum((epm-mean(epm))^2)
SSR <- (SSY - SSE) # or SSR <- sum((predict(v.lm,list(n_days)) - mean(epm))^2)
R2 <- SSR / SSY
My problem is similar to yours. Here exist an error!
compile 'com.android.support:appcompat-v7:25.3.0'
All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.3.0, 24.0.0. Examples include 'com.android.support:animated-vector-drawable:25.3.0' and 'com.android.support:mediarouter-v7:24.0.0'
Seeing this Examples include 'com.android.support:animated-vector-drawable:25.3.0' and 'com.android.support:mediarouter-v7:24.0.0'
the just add these codes in dependencies, make sure that versions are same.
compile 'com.android.support:animated-vector-drawable:25.3.0'
compile 'com.android.support:mediarouter-v7:25.3.0'
One of the ways that you can run your spring-boot application from command line is as follows :
1) First go to your project directory in command line [where is your project located ?]
2) Then in the next step you have to create jar file for that, this can be done as
mvnw package
[for WINDOWS OS ] or ./mvnw package
[for MAC OS] , this will
create jar file for our application.
3) jar file is created in the target sub-directory
4)Now go to target sub directory as jar was created inside of it , i.e cd target
5) Now run the jar file in there.
Use command java -jar name.jar
[ name is the name of your created jar file.]
and there you go , you are done . Now you can run project in browser,
http://localhost:port_number
if you already install nodejs from source for example, and execjs isn't recognizing it you might want to try this tip: https://coderwall.com/p/hyjdlw
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
Check that the connection string is in your Web.Config. I removed that node and put it in my Web.Debug.config and this is the error I received. Moved it back to the Web.config and worked great.
This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.
In this case, tester method needs to have access to Class, and you can construct
JavaType type = mapper.getTypeFactory().
constructCollectionType(List.class, Foo.class)
and then
List<Foo> list = mapper.readValue(new File("input.json"), type);
I'm late but I'm here with some good research data based on the functions provided by Scott's answer. So I set up a Digital Ocean droplet just for this 5-day long automated test and stored the generated unique strings in a MySQL database.
During this test period, I used 5 different lengths (5, 10, 15, 20, 50) and +/-0.5 million records were inserted for each length. During my test, only the length 5 generated +/-3K duplicates out of 0.5 million and the remaining lengths didn't generate any duplicates. So we can say that if we use a length of 15 or above with Scott's functions, then we can generate highly reliable unique strings. Here is the table showing my research data:
Update: I created a simple Heroku app using these functions that returns the token as a JSON response. The app can be accessed at https://uniquestrings.herokuapp.com/api/token?length=15
I hope this helps.
Try this:
SELECT s.NAME + '.' + t.NAME AS TableName
FROM sys.tables t
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
it will display the schema+table name for all tables in the current database.
Here is a version that will list every table in every database on the current server. it allows a search parameter to be used on any part or parts of the server+database+schema+table names:
SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName nvarchar(4000))
DECLARE @Search nvarchar(4000)
,@SQL nvarchar(4000)
SET @Search=null --all rows
SET @SQL='select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name LIKE ''%'+ISNULL(@SEARCH,'')+'%'''
INSERT INTO @AllTables (CompleteTableName)
EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY 1
set @Search to NULL for all tables, set it to things like 'dbo.users' or 'users' or '.master.dbo' or even include wildcards like '.master.%.u', etc.
Since you're accessing a web.config
you should probably use
using System.Web.Configuration;
WebConfigurationManager.AppSettings["configFile"]
Depends on which "cloud" you would want to use. If it is Google App Engine, you can use Java or Python. Groovy too is supported on Google App Engine which runs on jvm. If you are going with Amazon, you can pretty much install any OS (Amazon Machine Images) you would like with any application server and use any language depending on the application servers support for the language. But doing something like that would mean a lot of technical understanding of scalability concepts. Some of the services might be provided off the shelf like DB services, storage etc. I heard about ruby and Heroku (another cloud application platform). But dont have experience with it.
Personally I prefer Java/Groovy for such things because of the vast libraries and tools available.
Public Class Form1
Private boxes(5) As TextBox
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim newbox As TextBox
For i As Integer = 1 To 5 'Create a new textbox and set its properties26.27.
newbox = New TextBox
newbox.Size = New Drawing.Size(100, 20)
newbox.Location = New Point(10, 10 + 25 * (i - 1))
newbox.Name = "TextBox" & i
newbox.Text = newbox.Name 'Connect it to a handler, save a reference to the array & add it to the form control.
AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
boxes(i) = newbox
Me.Controls.Add(newbox)
Next
End Sub
Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs)
'When you modify the contents of any textbox, the name of that textbox
'and its current contents will be displayed in the title bar
Dim box As TextBox = DirectCast(sender, TextBox)
Me.Text = box.Name & ": " & box.Text
End Sub
End Class
A back link is a link that moves the browser backwards one page, as if the user had clicked the Back button available in most browsers. Back links use JavaScript. It moves the browser back one page if your browser supports JavaScript (which it does) and if it supports the window.history
object, which is necessary for back links.
Simple ways are
<a href="#" onClick="history.go(-1)">Go Back</a>
OR:
function goBack() {_x000D_
window.history.back()_x000D_
}
_x000D_
<a href="#" onclick="goBack()" />Go Back</a>
_x000D_
Generally speaking a back link isn't necessary… the Back button usually suffices quite nicely, and usually you can also simply link to the previous page in your site. However, sometimes you might want to provide a link back to one of several "previous" pages, and that's where a back link comes in handy. So I refer you below tutorial if you want to do in more advanced way:
http://www.htmlcodetutorial.com/linking/linking_famsupp_108.html
You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:
lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)
Then you can get hold of the axes objects (an array of axes):
axes = lm.axes
After that you can tweak the axes properties
axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)
creates:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == 'm')
this.WindowState = FormWindowState.Minimized;
}
You can use this in your case, it will work fine.
user = UniversityDetails.objects.filter(email=email).first()
Coming here from first Google hit:
You can turn off the behavior AND and warning by exporting GIT_DISCOVERY_ACROSS_FILESYSTEM=1
.
On heroku, if you heroku config:set GIT_DISCOVERY_ACROSS_FILESYSTEM=1
the warning will go away.
It's probably because you are building a gem from source and the gemspec shells out to git
, like many do today. So, you'll still get the warning fatal: Not a git repository (or any of the parent directories): .git
but addressing that is for another day :)
My answer is a duplicate of: - comment GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion
The solution is this:
<input (click)="focusOut()" type="text" matInput [formControl]="inputControl"
[matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" >
<mat-option (onSelectionChange)="submitValue($event)" *ngFor="let option of
options | async" [value]="option">
{{option.name | translate}}
</mat-option>
</mat-autocomplete>
TS
focusOut() {
this.inputControl.disable();
this.inputControl.enable();
}
Overload less than operator, then sort. This is an example I found off the web...
class MyData
{
public:
int m_iData;
string m_strSomeOtherData;
bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};
std::sort(myvector.begin(), myvector.end());
Source: here
In Linux, run file on the Eclipse executable, like this:
$ file /usr/bin/eclipse
eclipse: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped
Try this
I recently leaned about $wpdb->prepare
HERE and added into our Free Class Booking plugin, plugin approved on wordpress.org and will live soon:
global $wpdb;
$tablename = $wpdb->prefix . "submitted_form";
$name = "Kumkum"; //string value use: %s
$email = "[email protected]"; //string value use: %s
$phone = "3456734567"; //numeric value use: %d
$country = "India"; //string value use: %s
$course = "Database"; //string value use: %s
$message = "hello i want to read db"; //string value use: %s
$now = new DateTime(); //string value use: %s
$datesent = $now->format('Y-m-d H:i:s'); //string value use: %s
$sql = $wpdb->prepare("INSERT INTO `$tablename` (`name`, `email`, `phone`, `country`, `course`, `message`, `datesent`) values (%s, %s, %d, %s, %s, %s, %s)", $name, $email, $phone, $country, $course, $message, $datesent);
$wpdb->query($sql);
Thanks -Frank
Maybe something changed since 2011 but this worked for me:
$ date +"%Y%m%d"
20150330
No need for the -d
to get the same appearing result.
from above solutions, Nothing worked for me. This worked:
$('#client_filter').html(' '); //this worked
Why is that? :)
$.ajax({
type: 'POST',
url: xyz_ajax,
dataType: "json",
data : { csrfmiddlewaretoken: csrftoken,
instancess : selected_instances },
success: function(response) {
//clear the client DD
$('#client_filter').val('').trigger('change') ; //not working
$('#client_filter').val('').trigger('chosen:updated') ; //not working
$('#client_filter').val('').trigger('liszt:updated') ; //not working
$('#client_filter').html(' '); //this worked
jQuery.each(response, function(index, item) {
$('#client_filter').append('<option value="'+item.id+'">' + item.text + '</option>');
});
$('#client_filter').trigger("chosen:updated");
}
});
}
eval() is very powerful and can be used to execute a JS statement or evaluate an expression. But the question isn't about the uses of eval() but lets just say some how the string you running with eval() is affected by a malicious party. At the end you will be running malicious code. With power comes great responsibility. So use it wisely is you are using it. This isn't related much to eval() function but this article has pretty good information: http://blogs.popart.com/2009/07/javascript-injection-attacks/ If you are looking for the basics of eval() look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
You could handle the exception directly so it would not crash your program (catching the AggregateException
). You could also look at the Inner Exception, this will give you a more detailed explanation of what went wrong:
try {
// your code
} catch (AggregateException e) {
}
$result = mysql_query("SHOW TABLES FROM $dbname");
while($row = mysql_fetch_row($result))
{
$arr[] = $row[0];
}
if(in_array($table,$arr))
{
echo 'Table exists';
}
The question is what you really want to achieve when you asking for a workflow engine.
The general goal which you would like to achieve by using a workflow engine, is to become more flexible in changing your business logic during runtime. The modelling part is surely one of the most important here. BPMN 2.0 is a de-facto standard in this area and all of the discussed engines support this standard.
The second goal is to control the business process in the way of describing the 'what should happen when...' questions. And this part has a lot to do with the business requirements you are confronted within your project.
Some of the workflow engines (Activity, JBPM) can help you to answer this requirement by 'coding' your processes. This means that you model the 'what should happen when..' paradigm in a way, where you decide which part of your code (e.g a task or an event) should be executed by the workflow engine in various situations. A lot of discussion is going about this concept. And developers naturally ask whether this may not even be implemented by themselves. (It is in fact not so easy as it seems at the first glance)
Some other workflow engines (Imixs-Workflow, Bonita) can help you to answer the 'what should happen when...' requirement in a more user-centric way. This is the area of Human-centric business process management, which supports human skills and activities by a task orientated workflow-engine. The focus is more on the distribution of tasks and processes inside an organisation. The workflow engine helps you to distribute a task to a certain user or user group and to secure, log and monitor a long running business process. Maybe these are the things you do not really want to implement by yourself.
So my advice is, not to mix things that need to be considered separately, because workflow covers a very wide area.
Single method for Reactive Forms
TYPESCRIPT
// All is this method
onPasswordChange() {
if (this.confirm_password.value == this.password.value) {
this.confirm_password.setErrors(null);
} else {
this.confirm_password.setErrors({ mismatch: true });
}
}
// getting the form control elements
get password(): AbstractControl {
return this.form.controls['password'];
}
get confirm_password(): AbstractControl {
return this.form.controls['confirm_password'];
}
HTML
// PASSWORD FIELD
<input type="password" formControlName="password" />
// CONFIRM PASSWORD FIELD
<input type="password" formControlName="confirm_password" (change)="onPasswordChange()" />
// SHOW ERROR IF MISMATCH
<span *ngIf="confirm_password.hasError('mismatch')">Password do not match.</span>
You have to specify the path that you are working on:
source = '/home/test/py_test/'
for root, dirs, filenames in os.walk(source):
for f in filenames:
print f
fullpath = os.path.join(source, f)
log = open(fullpath, 'r')
nvm use 8.11.4
Just go with nvm use node_version
This can occur on android too not just computers. Was browsing using Kiwi when the site I was on began to endlessly redirect so I cut net access to close it out and noticed my phone had DL'd something f.txt
in my downloaded files.
Deleted it and didn't open.
Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.
It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.
I faced the same problem in Derby IBM DB2 embedded database in a java desktop application, and after a day of searching I finally found how it's done :
SELECT days (table1.datecolomn) - days (current date) FROM table1 WHERE days (table1.datecolomn) - days (current date) > 5
for more information check this site
from zipfile import ZipFile
ZipFile("YOURZIP.zip").extractall("YOUR_DESTINATION_DIRECTORY")
The directory where you will extract your files doesn't need to exist before, you name it at this moment
YOURZIP.zip is the name of the zip if your project is in the same directory. If not, use the PATH i.e : C://....//YOURZIP.zip
Think to escape the /
by an other /
in the PATH
If you have a permission denied
try to launch your ide (i.e: Anaconda) as administrator
YOUR_DESTINATION_DIRECTORY will be created in the same directory than your project
There's an extension for Chrome (SimpleGet) that has a plugin for Windows and Linux that can execute an app with command line parameters.....
http://pinel.cc/
http://code.google.com/p/simple-get/
http://www.chromeextensions.org/other/simple-get/
$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');
In general, there isn't a way to determine which particular statement caused the error. If you're running several, you could watch profiler and look at the last completed statement and see what the statement after that might be, though I have no idea if that approach is feasible for you.
In any event, one of your parameter variables (and the data inside it) is too large for the field it's trying to store data in. Check your parameter sizes against column sizes and the field(s) in question should be evident pretty quickly.
CHARINDEX is what you are looking for
select CHARINDEX('@', '[email protected]')
-----------
8
(1 row(s) affected)
-or-
select CHARINDEX('c', 'abcde')
-----------
3
(1 row(s) affected)
Open cmd with "Run as administrator" and execute the command pip install mitmproxy
. It will install it.
Below is the code for that (code may not contain all device's string, I'm with other guys are maintaining the same code on GitHub so please take the latest code from there)
Objective-C : GitHub/DeviceUtil
Swift : GitHub/DeviceGuru
#include <sys/types.h>
#include <sys/sysctl.h>
- (NSString*)hardwareDescription {
NSString *hardware = [self hardwareString];
if ([hardware isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
if ([hardware isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([hardware isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
if ([hardware isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([hardware isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
if ([hardware isEqualToString:@"iPod1,1"]) return @"iPodTouch 1G";
if ([hardware isEqualToString:@"iPod2,1"]) return @"iPodTouch 2G";
if ([hardware isEqualToString:@"iPad1,1"]) return @"iPad";
if ([hardware isEqualToString:@"iPad2,6"]) return @"iPad Mini";
if ([hardware isEqualToString:@"iPad4,1"]) return @"iPad Air WIFI";
//there are lots of other strings too, checkout the github repo
//link is given at the top of this answer
if ([hardware isEqualToString:@"i386"]) return @"Simulator";
if ([hardware isEqualToString:@"x86_64"]) return @"Simulator";
return nil;
}
- (NSString*)hardwareString {
size_t size = 100;
char *hw_machine = malloc(size);
int name[] = {CTL_HW,HW_MACHINE};
sysctl(name, 2, hw_machine, &size, NULL, 0);
NSString *hardware = [NSString stringWithUTF8String:hw_machine];
free(hw_machine);
return hardware;
}
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
it will create json object. no need to parse.
jsonStringQuotes = "'" + jsonStringNoQuotes + "'";
will return '[object]'
thats why it(below) is causing error
var myData = JSON.parse(jsonStringQuotes);
$('#tabs a[href="#sample-tab-1"]').click();
or, you can assign an id to the links
<a href="#sample-tab-1" id="tab1">span>One</span></a>
so you can find it's id.
$('#tab1').click();
You should first consider making GetStringData
an async
method and have it await
the task returned from MyAsyncMethod
.
If you're absolutely sure that you don't need to handle exceptions from MyAsyncMethod
or know when it completes, then you can do this:
public string GetStringData()
{
var _ = MyAsyncMethod();
return "hello world";
}
BTW, this is not a "common problem". It's very rare to want to execute some code and not care whether it completes and not care whether it completes successfully.
Update:
Since you're on ASP.NET and wanting to return early, you may find my blog post on the subject useful. However, ASP.NET was not designed for this, and there's no guarantee that your code will run after the response is returned. ASP.NET will do its best to let it run, but it can't guarantee it.
So, this is a fine solution for something simple like tossing an event into a log where it doesn't really matter if you lose a few here and there. It's not a good solution for any kind of business-critical operations. In those situations, you must adopt a more complex architecture, with a persistent way to save the operations (e.g., Azure Queues, MSMQ) and a separate background process (e.g., Azure Worker Role, Win32 Service) to process them.
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
I have used this:
document.onkeydown = keyboardDown;
document.onkeyup = keyboardUp;
document.oncontextmenu = function(e){
var evt = new Object({keyCode:93});
stopEvent(e);
keyboardUp(evt);
}
function stopEvent(event){
if(event.preventDefault != undefined)
event.preventDefault();
if(event.stopPropagation != undefined)
event.stopPropagation();
}
function keyboardDown(e){
...
}
function keyboardUp(e){
...
}
Then I catch e.keyCode property in those two last functions - if e.keyCode == 93, I know that the user either released the right mouse button or pressed/released the Context Menu key.
Hope it helps.
If you want null values to be included from Y.QID then Fastest way is
SELECT * FROM Y
LEFT JOIN X ON y.QID = X.QID
Note: this solution is applicable only if you need null values from Left table i.e. Y (in above case).
Otherwise
INNER JOIN x ON x.qid IS NOT DISTINCT FROM y.qid
is right way to do
I had the same issue with the MVC template not appearing in VS2015.
I checked Web Developer Tools when originally installing. It was still checked when trying to Modify the install. I tried unchecking and updating the install but next time I went back to Modify, it was still checked. And still no MVC template.
I got it working by uninstalling: Microsoft ASP.NET Web Frameworks and Tools 2015
via the Programs and Features
windows and re-installing. Here's the link for those who don't have it.
Vertically aligning has always been tricky.
Here I have covered up some method of vertically aligning a div.
<div style="display:flex;">
<div class="container table">
<div class="tableCell">
<div class="content"><em>Table</em> method</div>
</div>
</div>
<div class="container flex">
<div class="content new"><em>Flex</em> method<br></div>
</div>
<div class="container relative">
<div class="content"><em>Position</em> method</div>
</div>
<div class="container margin">
<div class="content"><em>Margin</em> method</div>
</div>
</div>
em{font-style: normal;font-weight: bold;}
.container {
width:200px;height:200px;background:#ccc;
margin: 5px; text-align: center;
}
.content{
width:100px; height: 100px;background:#37a;margin:auto;color: #fff;
}
.table{display: table;}
.table > div{display: table-cell;height: 100%;width: 100%;vertical-align: middle;}
.flex{display: flex;}
.relative{position: relative;}
.relative > div {position: absolute;top: 0;left: 0;right: 0;bottom: 0;}
.margin > div {position:relative; margin-top: 50%;top: -50px;}
To center align in one of the direction use android:layout_centerHorizontal="true" or android:layout_centerVertical="true" in the child layout
The best solution is just not to use anonymous classes.
public class Test
{
class DummyInterfaceImplementor : IDummyInterface
{
public string A { get; set; }
public string B { get; set; }
}
public void WillThisWork()
{
var source = new DummySource[0];
var values = from value in source
select new DummyInterfaceImplementor()
{
A = value.A,
B = value.C + "_" + value.D
};
DoSomethingWithDummyInterface(values.Cast<IDummyInterface>());
}
public void DoSomethingWithDummyInterface(IEnumerable<IDummyInterface> values)
{
foreach (var value in values)
{
Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
}
}
}
Note that you need to cast the result of the query to the type of the interface. There might be a better way to do it, but I couldn't find it.
You can first split them using String.split(",")
, and then convert the returned String array
to an ArrayList
using Arrays.asList(array)
For me, it helped to link the projects current directory as such:
In the properties -> C++ -> General window, instead of linking the path to the file in "additional include directories". Put "." and uncheck "inheret from parent or project defaults".
Hope this helps.
YES. This method allowed multiple domain.
VB.NET
response.headers.add("X-Frame-Options", "ALLOW-FROM " & request.urlreferer.tostring())
I do like:
var num = 12.749;
parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75
Round the number with 2 decimal points,
then make sure to parse it with parseFloat()
to return Number, not String unless you don't care if it is String or Number.
I sometimes use (in Load)
this.BeginInvoke((MethodInvoker) delegate {
// some code
});
or
this.BeginInvoke((MethodInvoker) this.SomeMethod);
(change "this" to your form variable if you are handling the event on an instance other than "this").
This pushes the invoke onto the windows-forms loop, so it gets processed when the form is processing the message queue.
[updated on request]
The Control.Invoke/Control.BeginInvoke methods are intended for use with threading, and are a mechanism to push work onto the UI thread. Normally this is used by worker threads etc. Control.Invoke does a synchronous call, where-as Control.BeginInvoke does an asynchronous call.
Normally, these would be used as:
SomeCodeOrEventHandlerOnAWorkerThread()
{
// this code running on a worker thread...
string newText = ExpensiveMethod(); // perhaps a DB/web call
// now ask the UI thread to update itself
this.Invoke((MethodInvoker) delegate {
// this code runs on the UI thread!
this.Text = newText;
});
}
It does this by pushing a message onto the windows message queue; the UI thread (at some point) de-queues the message, processes the delegate, and signals the worker that it completed... so far so good ;-p
OK; so what happens if we use Control.Invoke / Control.BeginInvoke on the UI thread? It copes... if you call Control.Invoke, it is sensible enough to know that blocking on the message queue would cause an immediate deadlock - so if you are already on the UI thread it simply runs the code immediately... so that doesn't help us...
But Control.BeginInvoke works differently: it always pushes work onto the queue, even it we are already on the UI thread. This makes a really simply way of saying "in a moment", but without the inconvenience of timers etc (which would still have to do the same thing anyway!).
I also experienced that for example:
This code doesnt work and get the intended block error.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
However, when i press tab before typing return self.title statement, the code works.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
Hope, this will help others.
Do not use list as variable name. You can take a look at the following code too:
clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]
Or in-place editing:
for i,x in enumerate(clist):
if '\t' in x:
clist[i] = x[:x.index('\t')]
Use jQuery before the php command alert
This issue can be resolved by adding TestNG.class package to OnlineStore package as below
This behaviour is now part of the component lifecycle.
A component can implement the ngOnChanges method in the OnChanges interface to get access to input changes.
Example:
import {Component, Input, OnChanges} from 'angular2/core';
@Component({
selector: 'hero-comp',
templateUrl: 'app/components/hero-comp/hero-comp.html',
styleUrls: ['app/components/hero-comp/hero-comp.css'],
providers: [],
directives: [],
pipes: [],
inputs:['hero', 'real']
})
export class HeroComp implements OnChanges{
@Input() hero:Hero;
@Input() real:string;
constructor() {
}
ngOnChanges(changes) {
console.log(changes);
}
}
The add_subplot() method has several call signatures:
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
<-- since 3.1.0Calls 1 and 2 achieve the same thing as one another (up to a limit, explained below). Think of them as first specifying the grid layout with their first 2 numbers (2x2, 1x8, 3x4, etc), e.g:
f.add_subplot(3,4,1)
# is equivalent to:
f.add_subplot(341)
Both produce a subplot arrangement of (3 x 4 = 12) subplots in 3 rows and 4 columns. The third number in each call indicates which axis object to return, starting from 1 at the top left, increasing to the right.
This code illustrates the limitations of using call 2:
#!/usr/bin/env python3
import matplotlib.pyplot as plt
def plot_and_text(axis, text):
'''Simple function to add a straight line
and text to an axis object'''
axis.plot([0,1],[0,1])
axis.text(0.02, 0.9, text)
f = plt.figure()
f2 = plt.figure()
_max = 12
for i in range(_max):
axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))
# If this check isn't in place, a
# ValueError: num must be 1 <= num <= 15, not 0 is raised
if i < 9:
axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
plot_and_text(axis,chr(i+97) + ') ' + str(341+i))
f.tight_layout()
f2.tight_layout()
plt.show()
You can see with call 1 on the LHS you can return any axis object, however with call 2 on the RHS you can only return up to index = 9 rendering subplots j), k), and l) inaccessible using this call.
I.e it illustrates this point from the documentation:
pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.
In rare circumstances, add_subplot may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes.
If no positional arguments are passed, defaults to (1, 1, 1).
i.e., reproducing the call fig.add_subplot(111)
in the question.
I use a simple jQuery plugin to return the numeric value of any single CSS property.
It applies parseFloat
to the value returned by jQuery's default css
method.
Plugin Definition:
$.fn.cssNum = function(){
return parseFloat($.fn.css.apply(this,arguments));
}
Usage:
var element = $('.selector-class');
var numericWidth = element.cssNum('width') * 10 + 'px';
element.css('width', numericWidth);
I had this error before when I was executing a python3 script, after this:
sudo pip3 install requests
the problem solved, If you are using python3, give a shot.
As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).
Your question is based on assumption that the code which may throw NullPointerException
is worse than the code which may not. This assumption is wrong. If you expect that your foobar
is never null due to the program logic, it's much better to use Optional.of(foobar)
as you will see a NullPointerException
which will indicate that your program has a bug. If you use Optional.ofNullable(foobar)
and the foobar
happens to be null
due to the bug, then your program will silently continue working incorrectly, which may be a bigger disaster. This way an error may occur much later and it would be much harder to understand at which point it went wrong.
For .NET development, VS2008 is the best but if you want to check for another best IDE, Eclipse probably the best after VS if you are rating it among the IDEs, ofcourse you cant do .NET development in Eclipse though
Try something like the following code:
MyDAO MyDAO = new MyDAO();
List<MyViewModel> _MyDefault = new List<MyViewModel>() {
new MyViewModel{
Prop1= "All",
Prop2 = "Select all"
}
};
ViewBag.MyViewBag=
new SelectList(MyDAO
.MyList().Union(
_MyDefault
), "Prop1", "Prop2");
In addition to gotomanners answer, in case anyone else came here looking for a null safe solution to the same problem, this is what I ended up with
Collections.max(arrayList, Comparator.nullsFirst(Comparator.naturalOrder()))
The best way is to copy all the files and folders inside a directory on your local file system by: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH
SRC_PATH
is on container
DEST_PATH
is on localhost
Then do docker-compose down
attach a volume to the same DEST_PATH
and run Docker containers by using docker-compose up -d
Add volume by following in docker-compose.yml
volumes:
- DEST_PATH:SRC_PATH
As an extension to @maerics nice answer, I've added a few useful methods:
public class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Tuple)){
return false;
}
Tuple<X,Y> other_ = (Tuple<X,Y>) other;
// this may cause NPE if nulls are valid values for x or y. The logic may be improved to handle nulls properly, if needed.
return other_.x.equals(this.x) && other_.y.equals(this.y);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((x == null) ? 0 : x.hashCode());
result = prime * result + ((y == null) ? 0 : y.hashCode());
return result;
}
}
You can also use a spline. Feed in the values you have and interpolate points between your known points. Linking this with a least-squares fit, moving average or kalman filter (as mentioned in other answers) gives you the ability to calculate the points inbetween your "known" points.
Being able to interpolate the values between your knowns gives you a nice smooth transition and a /reasonable/ approximation of what data would be present if you had a higher-fidelity. http://en.wikipedia.org/wiki/Spline_interpolation
Different splines have different characteristics. The one's I've seen most commonly used are Akima and Cubic splines.
Another algorithm to consider is the Ramer-Douglas-Peucker line simplification algorithm, it is quite commonly used in the simplification of GPS data. (http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm)
If you just want go get
to work real fast, and move along with your work...
Just export GIT_TERMINAL_PROMPT=1
$ export GIT_TERMINAL_PROMPT=1
$ go get [whatever]
It will now prompt you for a user/pass for the rest of your shell session. Put this in your .profile
or setup git
as above for a more permanent solution.
@: one-way binding
=: two-way binding
&: function binding
Straight answer:
String s = "Hello World!";
// String => CharSequence conversion:
CharSequence cs = s; // String is already a CharSequence
CharSequence
is an interface, and the String
class implements CharSequence
.
this.label1.BackColor = System.Drawing.Color.Transparent;
Trello.com Trello is free for unlimited users. Period.
You almost definitely don't need "Sub-cards". Use the checklists instead, or if you REALLY need sub-cards, don't have a parent sub-card. Just name the tickets something like "Epic - Story A" or "Story - task Z" or whatever.
Another idea is to create two boards (did I mention you can have unlimited boards for free too?). One for your epics and one for your stories. Call one your product management board and the other your sprint board, or whatever you like.
I'm not sure what you need different roles for - but, people aren't crazy - they know their job. As a startup if you already have problems getting people to not do crazy things (Where you need to restrict their permissions) you have much much bigger issues.
The point is that you need a SMALL tool to help you track stuff. Not a super rigid tool that makes you work in a super specific way. As a new (I assume?) startup, you should let your process grow into a tool. Don't beef up your process to fit a tool.
I needed to reuse the same iframe and replace the content each time. I've tried a few ways and this worked for me:
// Set the iframe's src to about:blank so that it conforms to the same-origin policy
iframeElement.src = "about:blank";
// Set the iframe's new HTML
iframeElement.contentWindow.document.open();
iframeElement.contentWindow.document.write(newHTML);
iframeElementcontentWindow.document.close();
Here it is as a function:
function replaceIframeContent(iframeElement, newHTML)
{
iframeElement.src = "about:blank";
iframeElement.contentWindow.document.open();
iframeElement.contentWindow.document.write(newHTML);
iframeElement.contentWindow.document.close();
}
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
The command uptime
gives you load averages for the past 1, 5, and 15 minutes.
firstly you have to change the drive, which is allocated to your usb.
follow these step to access your pendrive using CMD. 1- type drivename follow by the colon just like k: 2- type dir it will show all the files and directory in your usb 3- now you can access any file or directory of your usb.
The recommended approach for a singleton service for Angular 6 and beyond is :
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}
In fact the CLI --module
switch doesn't even exist any more for registering a service at the app
level because it doesn't need to modify app.module.ts
anymore.
This will create the above code, without needing to specify a module.
ng g s services/user
So if you don't want your service to be a singleton you must remove the providedIn
code yourself - and then add it manually to providers
for a component or lazy loaded module. Doesn't look like there is currently a switch to not generate the providedIn: 'root'
part so you need to manually remove it.
I eventually used:
weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)
It worked just fine, except that I got the following message.
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated. Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.
If using Visual Studio 2010 you can right-click on the project for the service, and select properties
. Then select the Web
tab. Under the Servers
section you can configure the URL. There is also a button to create the virtual directory.
<script type="text/javascript">
<!--
function newPage(num) {
var url=new Array();
url[0]="http://www.htmlforums.com";
url[1]="http://www.codingforums.com.";
url[2]="http://www.w3schools.com";
url[3]="http://www.webmasterworld.com";
window.location=url[num];``
}
// -->
</script>
</head>
<body>
<form action="#">
<div id="container">
<input class="butts" type="button" value="htmlforums" onclick="newPage(0)"/>
<input class="butts" type="button" value="codingforums" onclick="newPage(1)"/>
<input class="butts" type="button" value="w3schools" onclick="newPage(2)"/>
<input class="butts" type="button" value="webmasterworld" onclick="newPage(3)"/>
</div>
</form>
</body>
Here's the other way, it's simpler than the other one.
<input id="inp" type="button" value="Home Page" onclick="location.href='AdminPage.jsp';" />
It's simpler.
This website contains a much cleaner solution, it leaves pip intact as-well and one can easily switch between 3.5 and 3.6 and then whenever 3.7 is released.
http://ubuntuhandbook.org/index.php/2017/07/install-python-3-6-1-in-ubuntu-16-04-lts/
A short summary:
sudo apt-get install python python-pip python3 python3-pip
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2
Then
$ pip -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)
Then to select python 3.6 run
sudo update-alternatives --config python3
and select '2'. Then
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)
To update pip select the desired version and
pip3 install --upgrade pip
$ pip3 -V
pip 9.0.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Tested on Ubuntu 16.04.
You can copy a string in python via string formatting :
>>> a = 'foo'
>>> b = '%s' % a
>>> id(a), id(b)
(140595444686784, 140595444726400)
although Response::json()
is not getting popular of recent, that does not stop you and Me from using it.
In fact you don't need any facade to use it,
instead of:
$response = Response::json($messages, 200);
Use this:
$response = \Response::json($messages, 200);
with the slash, you are sure good to go.
/**
* Redirect with POST data.
*
* @param string $url URL.
* @param array $post_data POST data. Example: ['foo' => 'var', 'id' => 123]
* @param array $headers Optional. Extra headers to send.
*/
public function redirect_post($url, array $data, array $headers = null) {
$params = [
'http' => [
'method' => 'POST',
'content' => http_build_query($data)
]
];
if (!is_null($headers)) {
$params['http']['header'] = '';
foreach ($headers as $k => $v) {
$params['http']['header'] .= "$k: $v\n";
}
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if ($fp) {
echo @stream_get_contents($fp);
die();
} else {
// Error
throw new Exception("Error loading '$url', $php_errormsg");
}
}
In windows:
pip install tesseract
pip install tesseract-ocr
and check the file which is stored in your system usr/appdata/local/programs/site-pakages/python/python36/lib/pytesseract/pytesseract.py file and compile the file
Git Stash Pop vs apply
Working
If you want to apply your top stashed changes to current non-staged change and delete that stash as well, then you should go for git stash pop
.
# apply the top stashed changes and delete it from git stash area.
git stash pop
But if you are want to apply your top stashed changes to current non-staged change without deleting it, then you should go for git stash apply
.
Note : You can relate this case with
Stack
classpop()
andpeek()
methods, where pop change the top by decrements (top = top-1) butpeek()
only able to get the top element.
New-style classes are ones that subclass "object" (directly or indirectly). They have a __new__
class method in addition to __init__
and have somewhat more rational low-level behavior.
Usually, you'll want to override __getattr__
(if you're overriding either), otherwise you'll have a hard time supporting "self.foo" syntax within your methods.
Extra info: http://www.devx.com/opensource/Article/31482/0/page/4
Radio button without panel
public class RadioButton2 : RadioButton
{
public string GroupName { get; set; }
}
private void RadioButton2_Clicked(object sender, EventArgs e)
{
RadioButton2 rb = (sender as RadioButton2);
if (!rb.Checked)
{
foreach (var c in Controls)
{
if (c is RadioButton2 && (c as RadioButton2).GroupName == rb.GroupName)
{
(c as RadioButton2).Checked = false;
}
}
rb.Checked = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
//a group
RadioButton2 rb1 = new RadioButton2();
rb1.Text = "radio1";
rb1.AutoSize = true;
rb1.AutoCheck = false;
rb1.Top = 50;
rb1.Left = 50;
rb1.GroupName = "a";
rb1.Click += RadioButton2_Clicked;
Controls.Add(rb1);
RadioButton2 rb2 = new RadioButton2();
rb2.Text = "radio2";
rb2.AutoSize = true;
rb2.AutoCheck = false;
rb2.Top = 50;
rb2.Left = 100;
rb2.GroupName = "a";
rb2.Click += RadioButton2_Clicked;
Controls.Add(rb2);
//b group
RadioButton2 rb3 = new RadioButton2();
rb3.Text = "radio3";
rb3.AutoSize = true;
rb3.AutoCheck = false;
rb3.Top = 80;
rb3.Left = 50;
rb3.GroupName = "b";
rb3.Click += RadioButton2_Clicked;
Controls.Add(rb3);
RadioButton2 rb4 = new RadioButton2();
rb4.Text = "radio4";
rb4.AutoSize = true;
rb4.AutoCheck = false;
rb4.Top = 80;
rb4.Left = 100;
rb4.GroupName = "b";
rb4.Click += RadioButton2_Clicked;
Controls.Add(rb4);
}
You may use this to access a specific folder and get particular image
public void Retrieve(String path, String Name)
{
File imageFile = new File(path+Name);
if(imageFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(path+Name);
myImage = (ImageView) findViewById(R.id.savedImage);
myImage.setImageBitmap(myBitmap);
Toast.makeText(SaveImage.this, myBitmap.toString(), Toast.LENGTH_LONG).show();
}
}
And then you can call it by
Retrieve(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images/","Image2.PNG");
Toast.makeText(SaveImage.this, "Saved", Toast.LENGTH_LONG).show();
Old question but you could do something like this:
html:
<textarea class="text-area" rows="1"></textarea>
jquery:
var baseH; // base scroll height
$('body')
.one('focus.textarea', '.text-area', function(e) {
baseH = this.scrollHeight;
})
.on('input.textarea', '.text-area', function(e) {
if(baseH < this.scrollHeight) {
$(this).height(0).height(this.scrollHeight);
}
else {
$(this).height(0).height(baseH);
}
});
This way the auto resize will apply to any textarea with the class "text-area". Also shrinks when text is removed.
jsfiddle:
Try CLPP library. It's simple and flexible library for command line parameters parsing. Header-only and cross-platform. Uses ISO C++ and Boost C++ libraries only. IMHO it is easier than Boost.Program_options.
Library: http://sourceforge.net/projects/clp-parser
26 October 2010 - new release 2.0rc. Many bugs fixed, full refactoring of the source code, documentation, examples and comments have been corrected.
It's subtle.
If the business requirement is "I want to audit the changes to the data - who did what and when?", you can usually use audit tables (as per the trigger example Keethanjan posted). I'm not a huge fan of triggers, but it has the great benefit of being relatively painless to implement - your existing code doesn't need to know about the triggers and audit stuff.
If the business requirement is "show me what the state of the data was on a given date in the past", it means that the aspect of change over time has entered your solution. Whilst you can, just about, reconstruct the state of the database just by looking at audit tables, it's hard and error prone, and for any complicated database logic, it becomes unwieldy. For instance, if the business wants to know "find the addresses of the letters we should have sent to customers who had outstanding, unpaid invoices on the first day of the month", you likely have to trawl half a dozen audit tables.
Instead, you can bake the concept of change over time into your schema design (this is the second option Keethanjan suggests). This is a change to your application, definitely at the business logic and persistence level, so it's not trivial.
For example, if you have a table like this:
CUSTOMER
---------
CUSTOMER_ID PK
CUSTOMER_NAME
CUSTOMER_ADDRESS
and you wanted to keep track over time, you would amend it as follows:
CUSTOMER
------------
CUSTOMER_ID PK
CUSTOMER_VALID_FROM PK
CUSTOMER_VALID_UNTIL PK
CUSTOMER_STATUS
CUSTOMER_USER
CUSTOMER_NAME
CUSTOMER_ADDRESS
Every time you want to change a customer record, instead of updating the record, you set the VALID_UNTIL on the current record to NOW(), and insert a new record with a VALID_FROM (now) and a null VALID_UNTIL. You set the "CUSTOMER_USER" status to the login ID of the current user (if you need to keep that). If the customer needs to be deleted, you use the CUSTOMER_STATUS flag to indicate this - you may never delete records from this table.
That way, you can always find what the status of the customer table was for a given date - what was the address? Have they changed name? By joining to other tables with similar valid_from and valid_until dates, you can reconstruct the entire picture historically. To find the current status, you search for records with a null VALID_UNTIL date.
It's unwieldy (strictly speaking, you don't need the valid_from, but it makes the queries a little easier). It complicates your design and your database access. But it makes reconstructing the world a lot easier.
If you are using Java 8 then try this using lambda expression and org.apache.commons.lang.StringUtils, that will also clear null
and blank
values from array
input
public static String[] cleanArray(String[] array) {
return Arrays.stream(array).filter(x -> !StringUtils.isBlank(x)).toArray(String[]::new);
}
You're very close:
while IFS=$'\t' read -r -a myArray
do
echo "${myArray[0]}"
echo "${myArray[1]}"
echo "${myArray[2]}"
done < myfile
(The -r
tells read
that \
isn't special in the input data; the -a myArray
tells it to split the input-line into words and store the results in myArray
; and the IFS=$'\t'
tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)
And for webkit enabled browsers I've had good results with:
.myElement {
-webkit-overflow-scrolling: touch;
scroll-behavior: smooth; // Added in from answer from Felix
overflow-x: scroll;
}
This makes scrolling behave much more like the standard browser behavior - at least it works well on the iPhone we were testing on!
Hope that helps,
Ed
now google had refused those parameters in my request (access_type, prompt)... :( and there is no "Revoke Access" button at all. I'm frustrating because of getting back my refresh_token lol
UPDATE: I found the answer in here :D you can get back the refresh token by a request https://developers.google.com/identity/protocols/OAuth2WebServer
curl -H "Content-type:application/x-www-form-urlencoded" \ https://accounts.google.com/o/oauth2/revoke?token={token}
The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.
If the revocation is successfully processed, then the status code of the response is 200. For error conditions, a status code 400 is returned along with an error code.
Execute this on the file:
awk 'ORS=NR%3?" ":"\n"' filename
and you'll get what you're looking for.
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
You could use a string stream and read the elements into the vector.
Here are many different examples...
A copy of one of the examples:
std::vector<std::string> split(const std::string& s, char seperator)
{
std::vector<std::string> output;
std::string::size_type prev_pos = 0, pos = 0;
while((pos = s.find(seperator, pos)) != std::string::npos)
{
std::string substring( s.substr(prev_pos, pos-prev_pos) );
output.push_back(substring);
prev_pos = ++pos;
}
output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word
return output;
}
You don't need that sort of solution for string literals, since they are concatenated at the language level, and it wouldn't work anyway because "s""1" isn't a valid preprocessor token.
[Edit: In response to the incorrect "Just for the record" comment below that unfortunately received several upvotes, I will reiterate the statement above and observe that the program fragment
#define PPCAT_NX(A, B) A ## B
PPCAT_NX("s", "1")
produces this error message from the preprocessing phase of gcc: error: pasting ""s"" and ""1"" does not give a valid preprocessing token
]
However, for general token pasting, try this:
/*
* Concatenate preprocessor tokens A and B without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
#define PPCAT_NX(A, B) A ## B
/*
* Concatenate preprocessor tokens A and B after macro-expanding them.
*/
#define PPCAT(A, B) PPCAT_NX(A, B)
Then, e.g., both PPCAT_NX(s, 1)
and PPCAT(s, 1)
produce the identifier s1
, unless s
is defined as a macro, in which case PPCAT(s, 1)
produces <macro value of s>1
.
Continuing on the theme are these macros:
/*
* Turn A into a string literal without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
#define STRINGIZE_NX(A) #A
/*
* Turn A into a string literal after macro-expanding it.
*/
#define STRINGIZE(A) STRINGIZE_NX(A)
Then,
#define T1 s
#define T2 1
STRINGIZE(PPCAT(T1, T2)) // produces "s1"
By contrast,
STRINGIZE(PPCAT_NX(T1, T2)) // produces "T1T2"
STRINGIZE_NX(PPCAT_NX(T1, T2)) // produces "PPCAT_NX(T1, T2)"
#define T1T2 visit the zoo
STRINGIZE(PPCAT_NX(T1, T2)) // produces "visit the zoo"
STRINGIZE_NX(PPCAT(T1, T2)) // produces "PPCAT(T1, T2)"
With Angular2 Bootstrap, you can use nonInput for most scenarios:
<div dropdown autoClose="nonInput">
nonInput - (default) automatically closes the dropdown when any of its elements is clicked — as long as the clicked element is not an input or a textarea.
if not %1 == "" (
must be
if not "%1" == "" (
If an argument isn't given, it's completely empty, not even ""
(which represents an empty string in most programming languages). So we use the surrounding quotes to detect an empty argument.
Your declaration is int ttTreeInsert(int value);
However, your definition/implementation is
ttTree::ttTreeInsert(int value)
{
}
Notice that the return type int
is missing in the implementation. Instead it should be
int ttTree::ttTreeInsert(int value)
{
return 1; // or some valid int
}
This works for me. Got solution from MYSQL webpage
In MySQL run below queries:
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'New_Password';
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
My solution - solved it for Angular 5 with Material View
The connection is through the
formArrayName="notification"
(change)="updateChkbxArray(n.id, $event.checked, 'notification')"
This way it can work for multiple checkboxes arrays in one form. Just set the name of the controls array to connect each time.
constructor(_x000D_
private fb: FormBuilder,_x000D_
private http: Http,_x000D_
private codeTableService: CodeTablesService) {_x000D_
_x000D_
this.codeTableService.getnotifications().subscribe(response => {_x000D_
this.notifications = response;_x000D_
})_x000D_
..._x000D_
}_x000D_
_x000D_
_x000D_
createForm() {_x000D_
this.form = this.fb.group({_x000D_
notification: this.fb.array([])..._x000D_
});_x000D_
}_x000D_
_x000D_
ngOnInit() {_x000D_
this.createForm();_x000D_
}_x000D_
_x000D_
updateChkbxArray(id, isChecked, key) {_x000D_
const chkArray = < FormArray > this.form.get(key);_x000D_
if (isChecked) {_x000D_
chkArray.push(new FormControl(id));_x000D_
} else {_x000D_
let idx = chkArray.controls.findIndex(x => x.value == id);_x000D_
chkArray.removeAt(idx);_x000D_
}_x000D_
}
_x000D_
<div class="col-md-12">_x000D_
<section class="checkbox-section text-center" *ngIf="notifications && notifications.length > 0">_x000D_
<label class="example-margin">Notifications to send:</label>_x000D_
<p *ngFor="let n of notifications; let i = index" formArrayName="notification">_x000D_
<mat-checkbox class="checkbox-margin" (change)="updateChkbxArray(n.id, $event.checked, 'notification')" value="n.id">{{n.description}}</mat-checkbox>_x000D_
</p>_x000D_
</section>_x000D_
</div>
_x000D_
At the end you are getting to save the form with array of original records id's to save/update.
Will be happy to have any remarks for improvement.
I use os.system
import os
os.system("pdftoppm -png {} {}".format(path2pdf, os.path.join(tmpdirname, "temp")))
After "AND" and after "OR" the QUERY has forgotten what it is all about.
I would also not know that it is about in any SQL / programming language.
if(SOMETHING equals "X" or SOMETHING equals "Y")
COLUMN NOT LIKE "A%" AND COLUMN NOT LIKE "B%"
For me worked only adding the config
or ssh_config
file that was on the dir ~/.ssh/config
on my Linux system on the c:\Program Files\Git\etc\ssh\
directory on Windows.
In some git versions we need to edit the C:\Users\<username>\AppData\Local\Programs\Git\etc\ssh\ssh_config
file.
After that, I was able to use all the alias and settings that I normally used on my Linux connecting or pushing via SSH on the Git Bash.
Append IDs at the class declaration
.aclass, #hashone, #hashtwo{ ...codes... }
document.getElementById( "hashone" ).style.visibility = "hidden";
If we want to make a new dictionary with selected keys removed, we can make use of dictionary comprehension
For example:
d = {
'a' : 1,
'b' : 2,
'c' : 3
}
x = {key:d[key] for key in d.keys() - {'c', 'e'}} # Python 3
y = {key:d[key] for key in set(d.keys()) - {'c', 'e'}} # Python 2.*
# x is {'a': 1, 'b': 2}
# y is {'a': 1, 'b': 2}
length(unique(df$col))
is the most simple way I can see.
if you are using Spring version of 3.1 or newer you can specify "produces" in @RequestMapping
annotation. Example below works for me out of box. No need of register converter or anything else if you have web mvc enabled (@EnableWebMvc
).
@ResponseBody
@RequestMapping(value = "/photo2", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto() throws IOException {
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
return IOUtils.toByteArray(in);
}
Late to the party, but here is a bootstrap-only solution that has worked for me. I'm using Bootstrap 4:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<body>_x000D_
<div class="row mt-4">_x000D_
<div class="col-md-12">_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">1</span>_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">2</span>_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">3</span>_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
You basically add bg-dark text-white rounded-circle px-3 py-1 mx-2 h3
classes to your <span>
(or whatever) element and you're done.
Note that you might need to adjust margin and padding classes if your content has more than one digits.
The list is maintaining an object reference to the original value stored in the list. So when you execute this line:
Integer x = i.next();
Both x
and the list are storing a reference to the same object. However, when you execute:
x = Integer.valueOf(9);
nothing has changed in the list, but x
is now storing a reference to a different object. The list has not changed. You need to use some of the list manipulation methods, such as
list.set(index, Integer.valueof(9))
Note: this has nothing to do with the immutability of Integer
, as others are suggesting. This is just basic Java object reference behaviour.
Here's a complete example, to help explain the point. Note that this makes use of the ListIterator
class, which supports removing/setting items mid-iteration:
import java.util.*;
public class ListExample {
public static void main(String[] args) {
List<Foo> fooList = new ArrayList<Foo>();
for (int i = 0; i < 9; i++)
fooList.add(new Foo(i, i));
// Standard iterator sufficient for altering elements
Iterator<Foo> iterator = fooList.iterator();
if (iterator.hasNext()) {
Foo foo = iterator.next();
foo.x = 99;
foo.y = 42;
}
printList(fooList);
// List iterator needed for replacing elements
ListIterator<Foo> listIterator = fooList.listIterator();
if (listIterator.hasNext()) {
// Need to call next, before set.
listIterator.next();
// Replace item returned from next()
listIterator.set(new Foo(99,99));
}
printList(fooList);
}
private static void printList(List<?> list) {
Iterator<?> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next());
}
System.out.println();
}
private static class Foo {
int x;
int y;
Foo(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("[%d, %d]", x, y);
}
}
}
This will print:
[99, 42][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
[99, 99][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
LIke this
css
h2 {
border-bottom-width: 1px;
border-bottom-style: solid;
margin: 0;
padding: 0;
}
.edit_button {
float: right;
}
css
h2 {
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: gray;
float: left;
margin: 0;
padding: 0;
}
.edit_button {
float: right;
}
html
<h2>
Contact Details</h2>
<button type="button" class="edit_button" >My Button</button>
html
<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray; float:left;">
Contact Details
</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>
org.junit.Assert.assertEquals()
and org.junit.Assert.assertArrayEquals()
do the job.
To avoid next questions: If you want to ignore the order put all elements to set and then compare: Assert.assertEquals(new HashSet<String>(one), new HashSet<String>(two))
If however you just want to ignore duplicates but preserve the order wrap you list with LinkedHashSet
.
Yet another tip. The trick Assert.assertEquals(new HashSet<String>(one), new HashSet<String>(two))
works fine until the comparison fails. In this case it shows you error message with to string representations of your sets that can be confusing because the order in set is almost not predictable (at least for complex objects). So, the trick I found is to wrap the collection with sorted set instead of HashSet
. You can use TreeSet
with custom comparator.
Some hash tables (cuckoo hashing) have guaranteed O(1) lookup
You need to reference the namespace
using System.Windows.Form;
and then add in the code
protected void Button1_Click(object sender, EventArgs e)
{
MessageBox.Show(" Hi....");
}
You'll need to find the URI of the message. But once you do I think you should be able to android.content.ContentResolver.delete(...) it.
Here's some more info.
<span style="color:orange;">orange text</span>
Is the only way I know of barring the font tag.
The difference is that the post-increment operator i++
returns i
as it was before incrementing, and the pre-increment operator ++i
returns i
as it is after incrementing. If you're asking about a typical for
loop:
for (i = 0; i < 10; i++)
or
for (i = 0; i < 10; ++i)
They're exactly the same, since you're not using i++
or ++i
as a part of a larger expression.
There is already a string handling function Series.str.startswith()
.
You should try foo[foo.b.str.startswith('f')]
.
Result:
a b
1 2 foo
2 3 fat
I think what you expect.
Alternatively you can use contains with regex option. For example:
foo[foo.b.str.contains('oo', regex= True, na=False)]
Result:
a b
1 2 foo
na=False
is to prevent Errors in case there is nan, null etc. values
You can use the limit(n)
function:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()
Or:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()
You can change your code to this:
$where_au = "(library.available_until >= '{date('Y-m-d H:i:s)}' OR library.available_until = '00-00-00 00:00:00')";
$this->db
->select('*')
->from('library')
->where('library.rating >=', $form['slider'])
->where('library.votes >=', '1000')
->where('library.language !=', 'German')
->where($where_au)
->where('library.release_year >=', $year_start)
->where('library.release_year <=', $year_end)
->join('rating_repo', 'library.id = rating_repo.id');
Tip: to watch the generated query you can use
echo $this->db->last_query(); die();
If you are using the tidyverse, you can use
as_data_frame(table(myvector))
to get a tibble (i.e. a data frame with some minor variations from the base class)
android:textAppearance="?android:attr/textAppearanceLarge"
seemed no effect.
android:minHeight="?android:attr/listPreferredItemHeight"
changed the height for me
You should remove "style" attribute instead of "display" property :
$("span").removeAttr("style");
Instead of specifying a list of directories to ignore (e.g. negative), you can also specify a list of directories to watch (e.g positive):
nodemon --watch dir1 --watch dir2 dir1/examples/index.js
In my particular case, I had one directory I wanted to watch and about nine I wanted to ignore, so specifying '--watch' was much simpler than specifying '--ignore'
If you want to save to a specific filename just ignore the provided extensions in Notepad/Word/whatever. Just set the filename.ext in " " and you're done. "Save as type" will be ignored.
&
is only used for string concatenation. +
is overloaded to do both string concatenation and arithmetic addition.The double purpose of +
leads to confusion, exactly like that in your question. Especially when Option Strict
is Off
, because the compiler will add implicit casts on your strings and integers to try to make sense of your code.
My recommendations
Option Strict On
, then the compiler will force you to add explicit casts where it thinks they are necessary. +
for concatenation because of the ambiguity with arithmetic addition. Both these recommendations are also in the Microsoft Press book Practical Guidelines And Best Practises for VB and C# (sections 1.16, 21.2)
Actually one detail is missing from the answer that is selected as accepted (from Phil Ross)....
it DOES work in Chrome, and the solution is really silly!!
Both the parent and the element onto which you want to control page-breaking must be declared as:
position: relative
check out this fiddle: http://jsfiddle.net/petersphilo/QCvA5/5/show/
This is true for:
page-break-before
page-break-after
page-break-inside
However, controlling page-break-inside in Safari does not work (in 5.1.7, at least)
i hope this helps!!!
PS: The question below brought up that fact that recent versions of Chrome no longer respect this, even with the position: relative; trick. However, they do seem to respect:
-webkit-region-break-inside: avoid;
see this fiddle: http://jsfiddle.net/petersphilo/QCvA5/23/show
so i guess we have to add that now...
Hope this helps!
It seems that using mongoose there is a limit of more than 1000 documents, when using
Potato.collection.insert(potatoBag, onInsert);
You can use:
var bulk = Model.collection.initializeOrderedBulkOp();
async.each(users, function (user, callback) {
bulk.insert(hash);
}, function (err) {
var bulkStart = Date.now();
bulk.execute(function(err, res){
if (err) console.log (" gameResult.js > err " , err);
console.log (" gameResult.js > BULK TIME " , Date.now() - bulkStart );
console.log (" gameResult.js > BULK INSERT " , res.nInserted)
});
});
But this is almost twice as fast when testing with 10000 documents:
function fastInsert(arrOfResults) {
var startTime = Date.now();
var count = 0;
var c = Math.round( arrOfResults.length / 990);
var fakeArr = [];
fakeArr.length = c;
var docsSaved = 0
async.each(fakeArr, function (item, callback) {
var sliced = arrOfResults.slice(count, count+999);
sliced.length)
count = count +999;
if(sliced.length != 0 ){
GameResultModel.collection.insert(sliced, function (err, docs) {
docsSaved += docs.ops.length
callback();
});
}else {
callback()
}
}, function (err) {
console.log (" gameResult.js > BULK INSERT AMOUNT: ", arrOfResults.length, "docsSaved " , docsSaved, " DIFF TIME:",Date.now() - startTime);
});
}
Looks like you are trying to open a directory for reading as if it's a regular file. Many OSs won't let you do that. You don't need to anyway, because what you want (judging from your description) is
x_file = open(os.path.join(direct, "5_1.txt"), "r")
or simply
x_file = open(direct+"/5_1.txt", "r")
Normalization is your best friend in comment/rank/vote system. Learn it. A lot of sites are now moving to PDO ... learn that as well.
there are no right , right-er, or wrong (well there is) ways of doing it, you need to know the basic concepts and take them from there. IF you don't feel like learning, then perhaps invest in a framework like cakephp or zend framework, or a ready made system like wordpress or joomla.
I'd also recommend the book wicked cool php scripts as it has a comment system example in it.
why not select active tab first then active the selected tab content ?
1. Add class 'active' to the < li > element of tab first .
2. then use set 'active' class to selected div.
$(document).ready( function(){
SelectTab(1); //or use other method to set active class to tab
ShowInitialTabContent();
});
function SelectTab(tabindex)
{
$('.nav-tabs li ').removeClass('active');
$('.nav-tabs li').eq(tabindex).addClass('active');
//tabindex start at 0
}
function FindActiveDiv()
{
var DivName = $('.nav-tabs .active a').attr('href');
return DivName;
}
function RemoveFocusNonActive()
{
$('.nav-tabs a').not('.active').blur();
//to > remove :hover :focus;
}
function ShowInitialTabContent()
{
RemoveFocusNonActive();
var DivName = FindActiveDiv();
if (DivName)
{
$(DivName).addClass('active');
}
}
^(((([13578]|0[13578]|1[02])[-](0[1-9]|[1-9]|1[0-9]|2[0-9]|3[01]))|(([469]|0[469]|11)[-]([1-9]|1[0-9]|2[0-9]|3[0]))|((2|02)([-](0[1-9]|1[0-9]|2[0-8]))))[-](19([6-9][0-9])|20([0-9][0-9])))|((02)[-](29)[-](19(6[048]|7[26]|8[048]|9[26])|20(0[048]|1[26]|2[048])))
this regex will validate dates in format:
12-30-2016 (mm-dd-yyyy) or 12-3-2016 (mm-d-yyyy) or 1-3-2016 (m-d-yyyy) or 1-30-2016 (m-dd-yyyy)
In Android Studio, Click on 'Tools' on the top tab bar of android studio
Tools >> Android >> SDK Manager >> Launch Standalone Sdk manager
there you can clearly see which platform tool is missing , then just install that and your adb will start working properly.
Fully install at-least one Api package (Android Api 23 or 24) .
if [ ! -z "$var" ] && [ -e "$var" ]; then
# something ...
fi
That doesn't always work... if it doesn't, try:
img {
display: block;
margin: 0 auto;
}
If you look at the exception stack trace it says that, it failed to convert from ABDeadlineType
to DeadlineType
. Because your repository is going to return you the objects of ABDeadlineType
. How the spring-data-jpa
will convert into the other one(DeadlineType
). You should return the same type from repository and then have some intermediate util class to convert it into your model class.
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
List<ABDeadlineType> findAllSummarizedBy();
}
You're confusing the size of the array list with its capacity:
When you call new ArrayList<Integer>(10)
, you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.
One way to add ten elements to the array list is by using a loop:
for (int i = 0; i < 10; i++) {
arr.add(0);
}
Having done this, you can now modify elements at indices 0..9.
Have a look at this plunker:: this is the simplest example i could think of
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
<br>Input is : <strong>{{Data.FirstName}}</strong><!-- Successfully updates here -->
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{Data.FirstName}}<!-- How do I automatically updated it here? -->
</div>
</div>
// declare the app with no dependencies
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
return { FirstName: '' };
});
myApp.controller('FirstCtrl', function( $scope, Data ){
$scope.Data = Data;
});
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.Data = Data;
});
There are basically two ways of accomplishing this. In an async environment you'll notice that there are two kinds of loops: serial and parallel. A serial loop waits for one iteration to complete before it moves onto the next iteration - this guarantees that every iteration of the loop completes in order. In a parallel loop, all the iterations are started at the same time, and one may complete before another, however, it is much faster than a serial loop. So in this case, it's probably better to use a parallel loop because it doesn't matter what order the walk completes in, just as long as it completes and returns the results (unless you want them in order).
A parallel loop would look like this:
var fs = require('fs');
var path = require('path');
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach(function(file) {
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
if (!--pending) done(null, results);
});
} else {
results.push(file);
if (!--pending) done(null, results);
}
});
});
});
};
A serial loop would look like this:
var fs = require('fs');
var path = require('path');
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var i = 0;
(function next() {
var file = list[i++];
if (!file) return done(null, results);
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
next();
});
} else {
results.push(file);
next();
}
});
})();
});
};
And to test it out on your home directory (WARNING: the results list will be huge if you have a lot of stuff in your home directory):
walk(process.env.HOME, function(err, results) {
if (err) throw err;
console.log(results);
});
EDIT: Improved examples.
I met similar problem. the log is like below
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: still could not bind()
2018/10/31 12:54:23 [alert] 127997#127997: unlink() "/run/nginx.pid" failed (2: No such file or directory)
2018/10/31 22:40:48 [info] 36948#36948: Using 32768KiB of shared memory for push module in /etc/nginx/nginx.conf:68
2018/10/31 22:50:40 [emerg] 37638#37638: duplicate listen options for [::]:80 in /etc/nginx/sites-enabled/default:18
2018/10/31 22:51:33 [info] 37787#37787: Using 32768KiB of shared memory for push module in /etc/nginx/nginx.conf:68
The last [emerg]
shows that duplicate listen options for [::]:80
which means that there are more than one nginx block file containing [::]:80
.
My solution is to remove one of the [::]:80
setting
P.S. you probably have default block file. My advice is to keep this file as default server for port 80. and remove [::]:80
from other block files
It's better to use lambda
functions using df.apply()
-
df["ifor"] = df.apply(lambda x: {value} if {condition} else x["ifor"], axis=1)
There is a solution that works with some versions of awk:
awk '{ $(NF+1)=$1;$1="";$0=$0;} NF=NF ' infile.txt
Explanation:
$(NF+1)=$1 # add a new field equal to field 1.
$1="" # erase the contents of field 1.
$0=$0;} NF=NF # force a re-calc of fields.
# and use NF to promote a print.
Result:
United Arab Emirates AE
Antigua & Barbuda AG
Netherlands Antilles AN
American Samoa AS
Bosnia and Herzegovina BA
Burkina Faso BF
Brunei Darussalam BN
However that might fail with older versions of awk.
awk '{ $(NF+1)=$1;$1="";sub(OFS,"");}1' infile.txt
That is:
awk '{ # call awk.
$(NF+1)=$1; # Add one trailing field.
$1=""; # Erase first field.
sub(OFS,""); # remove leading OFS.
}1' # print the line.
Note that what needs to be erased is the OFS, not the FS. The line gets re-calculated when the field $1 is asigned. That changes all runs of FS to one OFS.
But even that option still fails with several delimiters, as is clearly shown by changing the OFS:
awk -v OFS=';' '{ $(NF+1)=$1;$1="";sub(OFS,"");}1' infile.txt
That line will output:
United;Arab;Emirates;AE
Antigua;&;Barbuda;AG
Netherlands;Antilles;AN
American;Samoa;AS
Bosnia;and;Herzegovina;BA
Burkina;Faso;BF
Brunei;Darussalam;BN
That reveals that runs of FS are being changed to one OFS.
The only way to avoid that is to avoid the field re-calculation.
One function that can avoid re-calc is sub.
The first field could be captured, then removed from $0 with sub, and then both re-printed.
awk '{ a=$1;sub("[^"FS"]+["FS"]+",""); print $0, a;}' infile.txt
a=$1 # capture first field.
sub( " # replace:
[^"FS"]+ # A run of non-FS
["FS"]+ # followed by a run of FS.
" , "" # for nothing.
) # Default to $0 (the whole line.
print $0, a # Print in reverse order, with OFS.
United Arab Emirates AE
Antigua & Barbuda AG
Netherlands Antilles AN
American Samoa AS
Bosnia and Herzegovina BA
Burkina Faso BF
Brunei Darussalam BN
Even if we change the FS, the OFS and/or add more delimiters, it works.
If the input file is changed to:
AE..United....Arab....Emirates
AG..Antigua....&...Barbuda
AN..Netherlands...Antilles
AS..American...Samoa
BA..Bosnia...and...Herzegovina
BF..Burkina...Faso
BN..Brunei...Darussalam
And the command changes to:
awk -vFS='.' -vOFS=';' '{a=$1;sub("[^"FS"]+["FS"]+",""); print $0,a;}' infile.txt
The output will be (still preserving delimiters):
United....Arab....Emirates;AE
Antigua....&...Barbuda;AG
Netherlands...Antilles;AN
American...Samoa;AS
Bosnia...and...Herzegovina;BA
Burkina...Faso;BF
Brunei...Darussalam;BN
The command could be expanded to several fields, but only with modern awks and with --re-interval option active. This command on the original file:
awk -vn=2 '{a=$1;b=$2;sub("([^"FS"]+["FS"]+){"n"}","");print $0,a,b;}' infile.txt
Will output this:
Arab Emirates AE United
& Barbuda AG Antigua
Antilles AN Netherlands
Samoa AS American
and Herzegovina BA Bosnia
Faso BF Burkina
Darussalam BN Brunei
One more time, building off of @RalphyZ
This one doesn't break the exposed API.
from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
# Add back help
optional.add_argument(
'-h',
'--help',
action='help',
default=SUPPRESS,
help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
Which will show the same as above and should survive future versions:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
-h, --help show this help message and exit
--optional_arg OPTIONAL_ARG
If you are using JPA with EclipseLink, you'll have to set the @PrivateOwned annotation.
Documentation: Eclipse Wiki - Using EclipseLink JPA Extensions - Chapter 1.4 How to Use the @PrivateOwned Annotation
Try replaceAll()
method of the String
class.
BTW here is the method, return type and parameters.
public String replaceAll(String regex,
String replacement)
Example:
String str = "Hello +-^ my + - friends ^ ^^-- ^^^ +!";
str = str.replaceAll("[-+^]*", "");
It should remove all the {'^', '+', '-'} chars that you wanted to remove!
Nobody mentioned this, but IETester is a great tool. It supports Internet Explorer 5.5, 6, 7 and 8RC1. The rendering matches the corresponding browsers. At least I haven't found any discrepancies yet.
I normally use it to do a basic check of the layout. I still need VMs to debug JavaScript or to use the Developer Toolbar with a specific Internet Explorer version.
Using Jquery, simply use this function:
<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
}
</script>
Your print button will look like this:
<button id="print" onclick="printContent('id name of your div');" >Print</button>
Edit: If you DO have form data that you need to keep, clone won't copy that, so you'll just need to grab all the form data and replace it after restore as so:
<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
var enteredtext = $('#text').val();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
$('#text').html(enteredtext);
}
</script>
<textarea id="text"></textarea>
That depends on where exactly the XML file is. Is it in the sources folder (in the "default package" or the "root") or in the same folder as the class?
In for former case, you must use "/file.xml
" (note the leading slash) to find the file and it doesn't matter which class you use to try to locate it.
If the XML file is next to some class, SomeClass.class.getResourceAsStream()
with just the filename is the way to go.
In addition to the previous answers, you can also do Ctrl + A, and then enter colon (:), and you will notice a little input box at the bottom left. Type 'quit' and Enter to leave the current screen session. Note that this will remove your screen session.
Ctrl + A and then K will only kill the current window in the current session, not the whole session. A screen session consists of windows, which can be created using subsequent Ctrl + A followed by C. These windows can be viewed in a list using Ctrl + A + ".
I see my problem is a little bit different from yours, but I'll post this answer in case it helps someone else. I was using MB
as shorthand instead of M
when defining my memory_limit, and php was silently ignoring it. I changed it to an integer (in bytes) and the problem was solved.
My php.ini changed as follows: memory_limit = 512MB
to memory_limit = 536870912
. This fixed my problem. Hope it helps with someone else's! You can read up on php's shorthand here.
Good luck!
Edit
As Yaodong points out, you can just as easily use the correct shorthand, "M", instead of using byte values. I changed mine to byte values for debugging purposes and then didn't bother to change it back.
To get current directory (where you execute your target program), you can use the following example code, which works for both Visual Studio and Linux/MacOS(gcc/clang), both C and C++:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(_MSC_VER)
#include <direct.h>
#define getcwd _getcwd
#elif defined(__GNUC__)
#include <unistd.h>
#endif
int main() {
char* buffer;
if( (buffer=getcwd(NULL, 0)) == NULL) {
perror("failed to get current directory\n");
} else {
printf("%s \nLength: %zu\n", buffer, strlen(buffer));
free(buffer);
}
return 0;
}
The short answer is:
The AngularJS way of calling $http would look like:
$http({
url: "http://example.appspot.com/rest/app",
method: "POST",
data: {"foo":"bar"}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.data = response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.error = response.statusText;
});
or could be written even simpler using shortcut methods:
$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);
There are number of things to notice:
success
and error
respectively (also please note parameters of each callback) - Deprecated in angular v1.5then
function instead. then
usage can be found here The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http
.joins
will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again
:includes
will eager load the included associations and add them in memory. :includes
loads all the included tables attributes. If you call associations on include query result, it will not fire any queries
Since Rails 5 you can also create a new class with ::API instead of ::Base:
class ApiController < ActionController::API
end
Typically for dynamic lists of items, you use a std::vector
.
Generally I use memset or a loop for raw memory dynamic allocation, depending on how variable I anticipate that area of code to be in the future.
Use the Text-finder plugin.
Instead of exiting with status 1 (which would fail the build), do:
if ($build_error) print("TESTS FAILED!");
Than in the post-build actions enable the Text Finder, set the regular expression to match the message you printed (TESTS FAILED!
) and check the "Unstable if found" checkbox under that entry.
From the blog Managing Hierarchical Data in MySQL
Table structure
+-------------+----------------------+--------+
| category_id | name | parent |
+-------------+----------------------+--------+
| 1 | ELECTRONICS | NULL |
| 2 | TELEVISIONS | 1 |
| 3 | TUBE | 2 |
| 4 | LCD | 2 |
| 5 | PLASMA | 2 |
| 6 | PORTABLE ELECTRONICS | 1 |
| 7 | MP3 PLAYERS | 6 |
| 8 | FLASH | 7 |
| 9 | CD PLAYERS | 6 |
| 10 | 2 WAY RADIOS | 6 |
+-------------+----------------------+--------+
Query:
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = 'ELECTRONICS';
Output
+-------------+----------------------+--------------+-------+
| lev1 | lev2 | lev3 | lev4 |
+-------------+----------------------+--------------+-------+
| ELECTRONICS | TELEVISIONS | TUBE | NULL |
| ELECTRONICS | TELEVISIONS | LCD | NULL |
| ELECTRONICS | TELEVISIONS | PLASMA | NULL |
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS | FLASH |
| ELECTRONICS | PORTABLE ELECTRONICS | CD PLAYERS | NULL |
| ELECTRONICS | PORTABLE ELECTRONICS | 2 WAY RADIOS | NULL |
+-------------+----------------------+--------------+-------+
Most users at one time or another have dealt with hierarchical data in a SQL database and no doubt learned that the management of hierarchical data is not what a relational database is intended for. The tables of a relational database are not hierarchical (like XML), but are simply a flat list. Hierarchical data has a parent-child relationship that is not naturally represented in a relational database table. Read more
Refer the blog for more details.
EDIT:
select @pv:=category_id as category_id, name, parent from category
join
(select @pv:=19)tmp
where parent=@pv
Output:
category_id name parent
19 category1 0
20 category2 19
21 category3 20
22 category4 21
I think the cleanest approach is something like:
var SingletonFactory = (function(){
function SingletonClass() {
//do stuff
}
var instance;
return {
getInstance: function(){
if (instance == null) {
instance = new SingletonClass();
// Hide the constructor so the returned object can't be new'd...
instance.constructor = null;
}
return instance;
}
};
})();
Afterwards, you can invoke the function as
var test = SingletonFactory.getInstance();
In PHP you can get complete list of AWS-S3 objects inside specific bucket using following call
$S3 = \Aws\S3\S3Client::factory(array('region' => $region,));
$iterator = $S3->getIterator('ListObjects', array('Bucket' => $bucket));
foreach ($iterator as $obj) {
echo $obj['Key'];
}
You can redirect output of the above code in to a file to get list of keys.