In Simple Terms,
1.INNER JOIN OR EQUI JOIN : Returns the resultset that matches only the condition in both the tables.
2.OUTER JOIN : Returns the resultset of all the values from both the tables even if there is condition match or not.
3.LEFT JOIN : Returns the resultset of all the values from left table and only rows that match the condition in right table.
4.RIGHT JOIN : Returns the resultset of all the values from right table and only rows that match the condition in left table.
5.FULL JOIN : Full Join and Full outer Join are same.
INNER JOIN = JOIN
INNER JOIN is the default if you don't specify the type when you use the word JOIN.
You can also use LEFT OUTER JOIN or RIGHT OUTER JOIN, in which case the word OUTER is optional, or you can specify CROSS JOIN.
OR
For an inner join, the syntax is:
SELECT ...
FROM TableA
[INNER] JOIN TableB(in other words, the "INNER" keyword is optional - results are the same with or without it)
I tried to do this in next way
public static DataTable JoinTwoTables(DataTable innerTable, DataTable outerTable)
{
DataTable resultTable = new DataTable();
var innerTableColumns = new List<string>();
foreach (DataColumn column in innerTable.Columns)
{
innerTableColumns.Add(column.ColumnName);
resultTable.Columns.Add(column.ColumnName);
}
var outerTableColumns = new List<string>();
foreach (DataColumn column in outerTable.Columns)
{
if (!innerTableColumns.Contains(column.ColumnName))
{
outerTableColumns.Add(column.ColumnName);
resultTable.Columns.Add(column.ColumnName);
}
}
for (int i = 0; i < innerTable.Rows.Count; i++)
{
var row = resultTable.NewRow();
innerTableColumns.ForEach(x =>
{
row[x] = innerTable.Rows[i][x];
});
outerTableColumns.ForEach(x =>
{
row[x] = outerTable.Rows[i][x];
});
resultTable.Rows.Add(row);
}
return resultTable;
}
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
There are different types of joins available in SQL:
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: It combines the results of both left and right outer joins.
The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.
SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
WE can take each first four joins in Details :
We have two tables with the following values.
TableA
id firstName lastName
.......................................
1 arun prasanth
2 ann antony
3 sruthy abc
6 new abc
TableB
id2 age Place
................
1 24 kerala
2 24 usa
3 25 ekm
5 24 chennai
....................................................................
INNER JOIN
Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB
Syntax
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
INNER JOIN TableB
ON TableA.id = TableB.id2;
Result Will Be
firstName lastName age Place
..............................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
LEFT JOIN
Note : will give all selected rows in TableA, plus any common selected rows in TableB.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
LEFT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
RIGHT JOIN
Note : will give all selected rows in TableB, plus any common selected rows in TableA.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
RIGHT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
NULL NULL 24 chennai
FULL JOIN
Note :It will return all selected values from both tables.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
FULL JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
NULL NULL 24 chennai
Interesting Fact
For INNER joins the order doesn't matter
For (LEFT, RIGHT or FULL) OUTER joins,the order matter
Better to go check this Link it will give you interesting details about join order
Try this:
select distinct a.FirstName, a.LastName, v.District
from AddTbl a
inner join ValTbl v
on a.LastName = v.LastName
order by a.FirstName;
Or this (it does the same, but the syntax is different):
select distinct a.FirstName, a.LastName, v.District
from AddTbl a, ValTbl v
where a.LastName = v.LastName
order by a.FirstName;
You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)
You should join T1 and T2 tables using sql joins in order to analyze from two tables. Link for learn joins : https://www.w3schools.com/sql/sql_join.asp
SELECT eb.n_EmpId,
em.s_EmpName,
deg.s_DesignationName,
dm.s_DeptName
FROM tbl_EmployeeMaster em
INNER JOIN tbl_DesignationMaster deg ON em.n_DesignationId=deg.n_DesignationId
INNER JOIN tbl_DepartmentMaster dm ON dm.n_DeptId = em.n_DepartmentId
INNER JOIN tbl_EmployeeBranch eb ON eb.n_BranchId = em.n_BranchId;
Almost correctly.. Look at the joins, you are referring the wrong fields
SELECT student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student ON student.studentId = grade.fk_studentId
INNER JOIN exam ON exam.examId = grade.fk_examId
ORDER BY exam.date
MySQL documentation covers this topic.
Here is a synopsis. When using join
or inner join
, the on
condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join
. Similarly, you can use an on
clause with cross join
, which also differs from standard SQL.
A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.
In practice, if you want to do a cross join, then use cross join
:
from A cross join B
is much better than:
from A, B
and:
from A join B -- with no on clause
The on
clause is required for a right or left outer join, so the discussion is not relevant for them.
If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.
if the database is InnoDB you dont need to do joins in deletion. only
DELETE FROM spawnlist WHERE spawnlist.type = "monster";
can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.
CREATE TABLE IF NOT EXIST spawnlist (
npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXIST npc (
idTemplate VARCHAR(20) NOT NULL,
FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE
)ENGINE=InnoDB;
if you uses MyISAM you can delete records joining like this
DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';
in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.
Thanks HansUp for your answer, it is very helpful and it works!
I found three patterns working in Access, yours is the best, because it works in all cases.
INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM
((class
INNER JOIN person AS cr
ON class.C_P_ClassRep=cr.P_Nr
)
INNER JOIN person AS cr2
ON class.C_P_ClassRep2nd=cr2.P_Nr
)
;
INNER JOIN "chained-set pattern"
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM person AS cr
INNER JOIN ( class
INNER JOIN ( person AS cr2
) ON class.C_P_ClassRep2nd=cr2.P_Nr
) ON class.C_P_ClassRep=cr.P_Nr
;
CROSS JOIN with WHERE
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM class, person AS cr, person AS cr2
WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
;
SELECT u.*
FROM users AS u
INNER JOIN (
SELECT p.*,
@num := if(@id = user_id, @num + 1, 1) as row_number,
@id := user_id as tmp
FROM payments AS p,
(SELECT @num := 0) x,
(SELECT @id := 0) y
ORDER BY p.user_id ASC, date DESC)
ON (p.user_id = u.id) and (p.row_number=1)
WHERE u.package = 1
SELECT column_Name1,column_name2,......
From tbl_name1,tbl_name2,tbl_name3
where tbl_name1.column_name = tbl_name2.column_name
and tbl_name2.column_name = tbl_name3.column_name
UPDATE (SELECT T.FIELD A, S.FIELD B
FROM TABLE_T T INNER JOIN TABLE_S S
ON T.ID = S.ID)
SET B = A;
A and B are alias fields, you do not need to point the table.
They have a different human-readable meaning.
However, depending on the query optimizer, they may have the same meaning to the machine.
You should always code to be readable.
That is to say, if this is a built-in relationship, use the explicit join. if you are matching on weakly related data, use the where clause.
you can't use VALUES
clause when inserting data using another SELECT
query. see INSERT SYNTAX
INSERT INTO user
(
id, name, username, email, opted_in
)
(
SELECT id, name, username, email, opted_in
FROM user
LEFT JOIN user_permission AS userPerm
ON user.id = userPerm.user_id
);
Avoid SELECT *
in your main query.
Avoid duplicate columns: the JOIN
condition ensures One.One_Name
and two.One_Name
will be equal therefore you don't need to return both in the SELECT
clause.
Avoid duplicate column names: rename One.ID
and Two.ID
using 'aliases'.
Add an ORDER BY
clause using the column names ('alises' where applicable) from the SELECT
clause.
Suggested re-write:
SELECT T1.ID AS One_ID, T1.One_Name,
T2.ID AS Two_ID, T2.Two_name
FROM One AS T1
INNER JOIN two AS T2
ON T1.One_Name = T2.One_Name
ORDER
BY One_ID;
I solve such queries using this pattern:
SELECT *
FROM t
WHERE t.field=(
SELECT MAX(t.field)
FROM t AS t0
WHERE t.group_column1=t0.group_column1
AND t.group_column2=t0.group_column2 ...)
That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:
WITH site_history AS (
SELECT sites.siteName, sites.siteIP, history.date
FROM sites
JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
SELECT MAX(date)
FROM site_history h0
WHERE h.siteName=h0.siteName)
ORDER BY siteName
It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date
field should be unique for each siteName
, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history
table has an unique index for (site, date)
, this query is also very fast, index range scan on the history
table scanning just the first item can be used.
Update one table using Inner Join
UPDATE Table1 SET name=ml.name
FROM table1 t inner JOIN
Table2 ml ON t.ID= ml.ID
I use following code for get different result from condition That worked for me.
Select A.column, B.column
FROM TABLE1 A
INNER JOIN
TABLE2 B
ON A.Id = (case when (your condition) then b.Id else (something) END)
Use subquery
SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]
Try this:
DELETE FROM WorkRecord2
FROM Employee
Where EmployeeRun=EmployeeNo
And Company = '1'
AND Date = '2013-05-06'
Try this :
SELECT
(
SELECT
`NAME`
FROM
locations
WHERE
ID = school_locations.LOCATION_ID
) as `NAME`
FROM
school_locations
WHERE
(
SELECT
`TYPE`
FROM
locations
WHERE
ID = school_locations.LOCATION_ID
) = 'coun';
Is this what you mean?
SELECT DISTINCT C.valueC
FROM
C
INNER JOIN B ON C.id = B.lookupC
INNER JOIN A ON B.id = A.lookupB
This should do it:
UPDATE ProductReviews
SET ProductReviews.status = '0'
FROM ProductReviews
INNER JOIN products
ON ProductReviews.pid = products.id
WHERE ProductReviews.id = '17190'
AND products.shopkeeper = '89137'
SELECT * FROM employees e1, employees e2
WHERE e1.phoneNumber = e2.phoneNumber
AND e1.id != e2.id;
Update : for better performance and faster query its good to add e1
before *
SELECT e1.* FROM employees e1, employees e2
WHERE e1.phoneNumber = e2.phoneNumber
AND e1.id != e2.id;
Json.NET - Documentation
http://james.newtonking.com/json/help/index.html?topic=html/SelectToken.htm
Interpretation for the author
var o = JObject.Parse(response);
var a = o.SelectToken("data").Select(jt => jt.ToObject<TheUser>()).ToList();
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
import android.content.Context;
public class Util {
// ===========================================================
//
// ===========================================================
private static final String INSTALLATION = "INSTALLATION";
public synchronized static boolean isFirstLaunch(Context context) {
String sID = null;
boolean launchFlag = false;
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists()) {
launchFlag = true;
writeInstallationFile(installation);
}
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return launchFlag;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");// read only mode
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
> Usage (in class extending android.app.Activity)
Util.isFirstLaunch(this);
Ctrl+] - go to definition
Ctrl+T - Jump back from the definition.
Ctrl+W Ctrl+] - Open the definition in a horizontal split
Add these lines in vimrc
map <C-\> :tab split<CR>:exec("tag ".expand("<cword>"))<CR>
map <A-]> :vsp <CR>:exec("tag ".expand("<cword>"))<CR>
Ctrl+\ - Open the definition in a new tab
Alt+] - Open the definition in a vertical split
After the tags are generated. You can use the following keys to tag into and tag out of functions:
Ctrl+Left MouseClick
- Go to definition
Ctrl+Right MouseClick
- Jump back from definition
To share personal experience I encountered with this error that eventually fix both. Might not necessarily be related to your issue but it appears this error is so generic that it can be attributed to gazillion things.
Database instance open in another application. My DB appeared to have been in a "locked" state so it transition to read only mode. I was able to track it down by stopping the a 2nd instance of the application sharing the DB.
Directory tree permission - please be sure to ensure user account has permission not just at the file level but at the entire upper directory level all the way to / level.
Thanks
CASE
is more like a switch statement. It has two syntaxes you can use. The first lets you use any compare statements you want:
CASE
WHEN user_role = 'Manager' then 4
WHEN user_name = 'Tom' then 27
WHEN columnA <> columnB then 99
ELSE -1 --unknown
END
The second style is for when you are only examining one value, and is a little more succinct:
CASE user_role
WHEN 'Manager' then 4
WHEN 'Part Time' then 7
ELSE -1 --unknown
END
It's simple:
array = []
will set array
to be an empty list. (They're called lists in Python, by the way, not arrays)
If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.
take a look at generic method to print all elements in an array
but in short, the Arrays.toString(arr) is just a easy way of printing the content of a primative array.
This is slighly more OS independent way:
# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)
# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))
@Min
and @Max
are used for validating numeric fields which could be String
(representing number), int
, short
, byte
etc and their respective primitive wrappers.
@Size
is used to check the length constraints on the fields.
As per documentation @Size
supports String
, Collection
, Map
and arrays
while @Min
and @Max
supports primitives and their wrappers. See the documentation.
child_process.spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.
so you can solve your problem using child_process.spawn as used below.
var spawn = require('child_process').spawn,
ls = spawn('coffee -cw my_file.coffee');
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('code ' + code.toString());
});
For exporting the instances of the classes you can use this syntax:
// export index.js
const Foo = require('./my/module/foo');
const Bar = require('./my/module/bar');
module.exports = {
Foo : new Foo(),
Bar : new Bar()
};
// import and run method
const {Foo,Bar} = require('module_name');
Foo.test();
You can replace nan
with None
in your numpy array:
>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>
For squashing two commits, one of which was already pushed, on a single branch the following worked:
git rebase -i HEAD~2
[ pick older-commit ]
[ squash newest-commit ]
git push --force
By default, this will include the commit message of the newest commit as a comment on the older commit.
Check the encoding in which you are generating the file, to make excel display the file correctly you must use the system default codepage.
Wich language are you using? if it's .Net you only need to use Encoding.Default while generating the file.
Try to use classpath*:
prefix instead.
Also please try to deploy exploded war, to ensure that all files are there.
public class Add {
static int add(int a, int b){
return (a+b);
}
}
In the above example, 'add' is a static method that takes two integers as arguments.
Following snippet is used to call 'add' method with input 1 and 2.
Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);
Reference link.
Using docker-compose
, services are exposed to each other by name by default. Docs.
You could also specify an alias like;
version: '2.1'
services:
mongo:
image: mongo:3.2.11
redis:
image: redis:3.2.10
api:
image: some-image
depends_on:
- mongo
- solr
links:
- "mongo:mongo.openconceptlab.org"
- "solr:solr.openconceptlab.org"
- "some-service:some-alias"
And then access the service using the specified alias as a host name, e.g mongo.openconceptlab.org
for mongo
in this case.
The main method of the runtime engine looks something like int main(int argc, char *argv[])
, where argc is a count of the number of arguments and argv is an array of pointers to each. The runtime engine converts this into a form that is more natural to c#.
Prior to that main method being called, everything is in assembly language. It has access to the command line arguments (because the operating system makes that available to every process that starts), but that assembly language needs to convert a single string of the full command line into multiple substrings (using whitespace to separate them) before it's ready to pass them into main().
If this is from a SQL Server datebase you could issue this kind of query...
Select Top 1 DepartureTime From TrainSchedule where DepartureTime >
GetUTCDate()
Order By DepartureTime ASC
GetDate()
could also be used, not sure how dates are being stored.
I am not sure how the data is being stored and/or read.
Use Firefox with Firebug. Open the 'Console' tab while firing the ajax request. With DEBUG=True
you get the nice django error page as response and you can even see the rendered html of the ajax response in the console tab.
Then you will know what the error is.
I researched the same thing several months ago looking at dozens of the most popular Android devices. I found that every Android device had one of the following aspect ratios (from most square to most rectangular):
And if you consider portrait devices separate from landscape devices you'll also find the inverse of those ratios (3:4, 2:3, 5:8, 3:5, and 9:16)
Before each of your conditional statements, you could do something like this:
var pagetype = pagetype || false;
if (pagetype === 'something') {
//do stuff
}
function checkIfDuplicateExists(w){
return new Set(w).size !== w.length
}
console.log(
checkIfDuplicateExists(["a", "b", "c", "a"])
// true
);
console.log(
checkIfDuplicateExists(["a", "b", "c"]))
//false
I use these two methods depending on the usage. FIDDLE
<div class="img-div">
<img src="http://placekitten.com/g/400/200" />
</div>
<div class="circle-image"></div>
div.img-div{
height:200px;
width:200px;
overflow:hidden;
border-radius:50%;
}
.img-div img{
-webkit-transform:translate(-50%);
margin-left:100px;
}
.circle-image{
width:200px;
height:200px;
border-radius:50%;
background-image:url("http://placekitten.com/g/200/400");
display:block;
background-position-y:25%
}
It seems that your action needs k
but ModelBinder can not find it (from form, or request or view data or ..)
Change your action to this:
public ActionResult DetailsData(int? k)
{
EmployeeContext Ec = new EmployeeContext();
if (k != null)
{
Employee emp = Ec.Employees.Single(X => X.EmpId == k.Value);
return View(emp);
}
return View();
}
Using Comparator
For Example:
class Score {
private String name;
private List<Integer> scores;
// +accessor methods
}
Collections.sort(scores, new Comparator<Score>() {
public int compare(Score o1, Score o2) {
// compare two instance of `Score` and return `int` as result.
return o2.getScores().get(0).compareTo(o1.getScores().get(0));
}
});
With Java 8 onwards, you can simply use lambda expression to represent Comparator instance.
Collections.sort(scores, (s1, s2) -> { /* compute and return int */ });
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
Try using display() function. This would automatically use Horizontal and vertical scroll bars and with this you can display different datasets easily instead of using print().
display(dataframe)
display() supports proper alignment also.
However if you want to make the dataset more beautiful you can check pd.option_context()
. It has lot of options to clearly show the dataframe.
Note - I am using Jupyter Notebooks.
I would recommend a little research on Money Pattern. Martin Fowler in his book Analysis pattern has covered this in more detail.
public class Money {
private static final Currency USD = Currency.getInstance("USD");
private static final RoundingMode DEFAULT_ROUNDING = RoundingMode.HALF_EVEN;
private final BigDecimal amount;
private final Currency currency;
public static Money dollars(BigDecimal amount) {
return new Money(amount, USD);
}
Money(BigDecimal amount, Currency currency) {
this(amount, currency, DEFAULT_ROUNDING);
}
Money(BigDecimal amount, Currency currency, RoundingMode rounding) {
this.currency = currency;
this.amount = amount.setScale(currency.getDefaultFractionDigits(), rounding);
}
public BigDecimal getAmount() {
return amount;
}
public Currency getCurrency() {
return currency;
}
@Override
public String toString() {
return getCurrency().getSymbol() + " " + getAmount();
}
public String toString(Locale locale) {
return getCurrency().getSymbol(locale) + " " + getAmount();
}
}
Coming to the usage:
You would represent all monies using Money
object as opposed to BigDecimal
. Representing money as big decimal will mean that you will have the to format the money every where you display it. Just imagine if the display standard changes. You will have to make the edits all over the place. Instead using the Money
pattern you centralize the formatting of money to a single location.
Money price = Money.dollars(38.28);
System.out.println(price);
The best thing is probably to create a variable that holds your binaries:
binaries=code1 code2
Then use that in the all
-target, to avoid repeating:
all: clean $(binaries)
Now, you can use this with the clean
-target, too, and just add some globs to catch object files and stuff:
.PHONY: clean
clean:
rm -f $(binaries) *.o
Note use of the .PHONY
to make clean
a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.
while the above answers didn't solve my problem. I finally solved it by specifically going to this link https://www.microsoft.com/net/download/visual-studio-sdks and download the required sdk for Visual Studio. It was really confusing and i don't understand why but that solved my problem
The first thing you should do is to determine whether you want to keep the local changes before you delete the commit message.
Use git log
to show current commit messages, then find the commit_id
before the commit that you want to delete, not the commit you want to delete.
git reset --soft commit_id
git reset --hard commit_id
That's the difference of soft and hard
Remove a determinated string from start and end from a string.
s = '""Hello World""'
s.strip('""')
> 'Hello World'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>_x000D_
<script>_x000D_
var ExcelToJSON = function() {_x000D_
_x000D_
this.parseExcel = function(file) {_x000D_
var reader = new FileReader();_x000D_
_x000D_
reader.onload = function(e) {_x000D_
var data = e.target.result;_x000D_
var workbook = XLSX.read(data, {_x000D_
type: 'binary'_x000D_
});_x000D_
workbook.SheetNames.forEach(function(sheetName) {_x000D_
// Here is your object_x000D_
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);_x000D_
var json_object = JSON.stringify(XL_row_object);_x000D_
console.log(JSON.parse(json_object));_x000D_
jQuery( '#xlx_json' ).val( json_object );_x000D_
})_x000D_
};_x000D_
_x000D_
reader.onerror = function(ex) {_x000D_
console.log(ex);_x000D_
};_x000D_
_x000D_
reader.readAsBinaryString(file);_x000D_
};_x000D_
};_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
_x000D_
var files = evt.target.files; // FileList object_x000D_
var xl2json = new ExcelToJSON();_x000D_
xl2json.parseExcel(files[0]);_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
</script>_x000D_
_x000D_
<form enctype="multipart/form-data">_x000D_
<input id="upload" type=file name="files[]">_x000D_
</form>_x000D_
_x000D_
<textarea class="form-control" rows=35 cols=120 id="xlx_json"></textarea>_x000D_
_x000D_
<script>_x000D_
document.getElementById('upload').addEventListener('change', handleFileSelect, false);_x000D_
_x000D_
</script>
_x000D_
You can discover those things easily by yourself:
def hello(*args, **kwargs):
print kwargs
print type(kwargs)
print dir(kwargs)
hello(what="world")
The parseInt
function converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:
var digit = parseInt(binary, 2);
It is possible to hide a button in place without changing its width or removing it from the bar. If you set the style to plain, remove the title, and disable the button, it will disappear. To restore it, just reverse your changes.
-(void)toggleBarButton:(bool)show
{
if (show) {
btn.style = UIBarButtonItemStyleBordered;
btn.enabled = true;
btn.title = @"MyTitle";
} else {
btn.style = UIBarButtonItemStylePlain;
btn.enabled = false;
btn.title = nil;
}
}
You can use the strip()
function to remove trailing (and leading) whitespace; passing it an argument will let you specify which whitespace:
for i in range(len(lists)):
grades.append(lists[i].strip('\n'))
It looks like you can just simplify the whole block though, since if your file stores one ID per line grades
is just lists
with newlines stripped:
lists = files.readlines()
grades = []
for i in range(len(lists)):
grades.append(lists[i].split(","))
grades = [x.strip() for x in files.readlines()]
(the above is a list comprehension)
Finally, you can loop over a list directly, instead of using an index:
for i in range(len(grades)):
# do something with grades[i]
for thisGrade in grades:
# do something with thisGrade
An extension of juba's method is to use reformulate
, a function which is explicitly designed for such a task.
## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
reformulate(xnam, "y")
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 +
x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 +
x22 + x23 + x24 + x25
For the example in the OP, the easiest solution here would be
# add y variable to data.frame d
d <- cbind(y, d)
reformulate(names(d)[-1], names(d[1]))
y ~ x1 + x2 + x3
or
mod <- lm(reformulate(names(d)[-1], names(d[1])), data=d)
Note that adding the dependent variable to the data.frame in d <- cbind(y, d)
is preferred not only because it allows for the use of reformulate
, but also because it allows for future use of the lm
object in functions like predict
.
A slight change to Thangamani Palanisamy answer, which allows the Binary reader to be disposed and corrects the input length issue in his comments.
string result = string.Empty;
using (BinaryReader b = new BinaryReader(file.InputStream))
{
byte[] binData = b.ReadBytes(file.ContentLength);
result = System.Text.Encoding.UTF8.GetString(binData);
}
None of the solutions above worked for me. This one works for me:
$(document).ready(function()
{
$('body').tooltip({
selector: '[data-toggle="tooltip"]',
html: true
});
});
I am late in answer, but posting with hope that it will help others.
In terms of Speed, Parcelable > Serializable
. But, Custom Serializable is exception. It is almost in range of Parcelable or even more faster.
Reference : https://www.geeksforgeeks.org/customized-serialization-and-deserialization-in-java/
Example :
Custom Class to be serialized
class MySerialized implements Serializable {
String deviceAddress = "MyAndroid-04";
transient String token = "AABCDS"; // sensitive information which I do not want to serialize
private void writeObject(ObjectOutputStream oos) throws Exception {
oos.defaultWriteObject();
oos.writeObject("111111" + token); // Encrypted token to be serialized
}
private void readObject(ObjectInputStream ois) throws Exception {
ois.defaultReadObject();
token = ((String) ois.readObject()).subString(6); // Decrypting token
}
}
Those commands use different output streams. By default both messages will be printed on console but it's possible for example to redirect one or both of these to a file.
java MyApp 2>errors.txt
This will redirect System.err
to errors.txt
file.
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
First add HTML code:
<form action="" method="post">
<input type="text" name="search">
<input type="submit" name="submit" value="Search">
</form>
Now added PHP code:
<?php
$search_value=$_POST["search"];
$con=new mysqli($servername,$username,$password,$dbname);
if($con->connect_error){
echo 'Connection Faild: '.$con->connect_error;
}else{
$sql="select * from information where First_Name like '%$search_value%'";
$res=$con->query($sql);
while($row=$res->fetch_assoc()){
echo 'First_name: '.$row["First_Name"];
}
}
?>
<input :required="condition">
You don't need <input :required="test ? true : false">
because if test is truthy you'll already get the required
attribute, and if test is falsy you won't get the attribute. The true : false
part is redundant, much like this...
if (condition) {
return true;
} else {
return false;
}
// or this...
return condition ? true : false;
// can *always* be replaced by...
return (condition); // parentheses generally not needed
The simplest way of doing this binding, then, is <input :required="condition">
Only if the test (or condition) can be misinterpreted would you need to do something else; in that case Syed's use of !!
does the trick.
<input :required="!!condition">
generator = myfunct()
while True:
my_element = generator.next()
make sure to catch the exception thrown after the last element is taken
On Windows this should work (note the forwardslash and that the whole path is not quoted and that spaces are allowed)
USE yourdb;
SOURCE D:/My Folder with spaces/Folder/filetoimport.sql;
No, it doesn't mean it's taking 0ms - it shows it's taking a smaller amount of time than you can measure with currentTimeMillis()
. That may well be 10ms or 15ms. It's not a good method to call for timing; it's more appropriate for getting the current time.
To measure how long something takes, consider using System.nanoTime
instead. The important point here isn't that the precision is greater, but that the resolution will be greater... but only when used to measure the time between two calls. It must not be used as a "wall clock".
Note that even System.nanoTime
just uses "the most accurate timer on your system" - it's worth measuring how fine-grained that is. You can do that like this:
public class Test {
public static void main(String[] args) throws Exception {
long[] differences = new long[5];
long previous = System.nanoTime();
for (int i = 0; i < 5; i++) {
long current;
while ((current = System.nanoTime()) == previous) {
// Do nothing...
}
differences[i] = current - previous;
previous = current;
}
for (long difference : differences) {
System.out.println(difference);
}
}
}
On my machine that shows differences of about 466 nanoseconds... so I can't possibly expect to measure the time taken for something quicker than that. (And other times may well be roughly multiples of that amount of time.)
The string
class has a constructor that takes a NULL-terminated C-string:
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
// or
str = arr;
Use the following code fragment to hide the form on button click.
document.getElementById("your form id").style.display="none";
And the following code to display it:
document.getElementById("your form id").style.display="block";
Or you can use the same function for both purposes:
function asd(a)
{
if(a==1)
document.getElementById("asd").style.display="none";
else
document.getElementById("asd").style.display="block";
}
And the HTML:
<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>
The commands for what specific codes to run are listed inside your package.json file under scripts. Here is an example of mine:
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
If you are looking to run your site locally, you can test it with
npm serve
If you are looking to prep your site for production, you would use
npm build
This command will generate a dist folder that has a compressed version of your site.
SQL Logins are defined at the server level, and must be mapped to Users in specific databases.
In SSMS object explorer, under the server you want to modify, expand Security > Logins, then double-click the appropriate user which will bring up the "Login Properties" dialog.
Select User Mapping, which will show all databases on the server, with the ones having an existing mapping selected. From here you can select additional databases (and be sure to select which roles in each database that user should belong to), then click OK to add the mappings.
These mappings can become disconnected after a restore or similar operation. In this case, the user may still exist in the database but is not actually mapped to a login. If that happens, you can run the following to restore the login:
USE {database};
ALTER USER {user} WITH login = {login}
You can also delete the DB user and recreate it from the Login Properties dialog, but any role memberships or other settings would need to be recreated.
Simply drag and drop your new class file to the JAR using 7-Zip or Winzip. You can even modify a JAR file that is included in a WAR file using the parent folder icon, and click Ok when 7zip detects that the inside file has been modified
If you want to check via command line , then use command "net user username /DOMAIN"
you should use fmod(a,b)
While abs(x%y) < abs(y) is true
mathematically, for floats
it may not be true numerically due to roundoff
.
For example, and assuming a platform on which a Python float
is an IEEE 754
double-precision number, in order that -1e-100 % 1e100
have the same sign as 1e100
, the computed result is -1e-100 + 1e100
, which is numerically exactly equal to 1e100
.
Function fmod()
in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100
in this case. Which approach is more appropriate depends on the application.
where x = a%b
is used for integer modulo
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
I had this same issue when trying to handle popping alerts and fading them. I searched around various places and found this to be my solution. Adding and removing the 'in' class fixed my issue.
window.setTimeout(function() { // hide alert message
$("#alert_message").removeClass('in');
}, 5000);
When using .remove() and similarly the .alert('close') solution I seemed to hit an issue with the alert being removed from the document, so if I wanted to use the same alert div again I was unable to. This solution means the alert is reusable without refreshing the page. (I was using aJax to submit a form and present feedback to the user)
$('#Some_Button_Or_Event_Here').click(function () { // Show alert message
$('#alert_message').addClass('in');
});
Easiest solution that I might have found is to create a table from the data you get from the SP. Then create a view from that:
Insert this at the last step when selecting data from the SP. SELECT * into table1 FROM #Temp
create view vw_view1 as select * from table1
Integer.parseInt
will take a string and return a int.
There's no easy way of doing this, other than doing something like class="lastCell" on the last td in each tr, and then setting your css up like this:
#table td {
border-right: 5px solid red
}
.lastCell {
border-right: none;
}
Even i was facing the same problem ,but solved it by
conda install -c conda-forge pysoundfile
while importing it
import soundfile
So many good answers, her are my 2 cents
i prefer to use inline function and old style of put and get value
object PreferenceHelper {
private const val PREFERENCES_KEY = "MyLocalPreference"
private fun getPreference(context: Context): SharedPreferences {
return context.getSharedPreferences(
PREFERENCES_KEY,
Context.MODE_PRIVATE
)
}
fun setBoolean(appContext: Context, key: String?, value: Boolean?) =
getPreference(appContext).edit().putBoolean(key, value!!).apply()
fun setInteger(appContext: Context, key: String?, value: Int) =
getPreference(appContext).edit().putInt(key, value).apply()
fun setFloat(appContext: Context, key: String?, value: Float) =
getPreference(appContext).edit().putFloat(key, value).apply()
fun setString(appContext: Context, key: String?, value: String?) =
getPreference(appContext).edit().putString(key, value).apply()
// To retrieve values from shared preferences:
fun getBoolean(appContext: Context, key: String?, defaultValue: Boolean?): Boolean =
getPreference(appContext).getBoolean(key, defaultValue!!)
fun getInteger(appContext: Context, key: String?, defaultValue: Int): Int =
getPreference(appContext)
.getInt(key, defaultValue)
fun getString(appContext: Context, key: String?, defaultValue: String?): String? =
getPreference(appContext)
.getString(key, defaultValue)
}
Usage
PreferenceHelper.setString(context,"CUSTOMER_NAME", "HITESH")
Toast.makeText(context, "Hello " + PreferenceHelper.getString(context,"CUSTOMER_NAME", "User"), Toast.LENGTH_LONG).show()
Look at the Subfloats section of http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions.
\begin{figure}[htp]
\centering
\label{figur}\caption{equation...}
\subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
\subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
\\
\subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
\subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
\\
\subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
\subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}
\end{figure}
Sometimes you will need this :
/*<![CDATA[*/
/*]]>*/
and not only this :
<![CDATA[
]]>
Pointer helps to create user defined scope to a variable, which is called Dynamic variable. Dynamic Variable can be single variable or group of variable of same type (array
) or group of variable of different types (struct
). Default local variable scope starts when control enters into a function and ends when control comes out of that function. Default global vairable scope starts at program execution and ends once program finishes.
But scope of a dynamic variable which holds by a pointer can start and end at any point in a program execution, which has to be decided by a programmer. Dangling and memory leak comes into picture only if a programmer doesnt handle the end of scope.
Memory leak will occur if a programmer, doesnt write the code (free
of pointer) for end of scope for dynamic variables. Any way once program exits complete process memory will be freed, at that time this leaked memory also will get freed. But it will cause a very serious problem for a process which is running long time.
Once scope of dynamic variable comes to end(freed), NULL
should be assigned to pointer variable. Otherwise if the code wrongly accesses it undefined behaviour will happen. So dangling pointer is nothing but a pointer which is pointing a dynamic variable whose scope is already finished.
Difference between count(*) and count(1) in oracle?
count(*) means it will count all records i.e each and every cell BUT
count(1) means it will add one pseudo column with value 1 and returns count of all records
css:
img.modal-img {
cursor: pointer;
transition: 0.3s;
}
img.modal-img:hover {
opacity: 0.7;
}
.img-modal {
display: none;
position: fixed;
z-index: 99999;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.9);
}
.img-modal img {
margin: auto;
display: block;
width: 80%;
max-width: 700%;
}
.img-modal div {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}
.img-modal img, .img-modal div {
animation: zoom 0.6s;
}
.img-modal span {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
cursor: pointer;
}
@media only screen and (max-width: 700px) {
.img-modal img {
width: 100%;
}
}
@keyframes zoom {
0% {
transform: scale(0);
}
100% {
transform: scale(1);
}
}
Javascript:
$('img.modal-img').each(function() {_x000D_
var modal = $('<div class="img-modal"><span>×</span><img /><div></div></div>');_x000D_
modal.find('img').attr('src', $(this).attr('src'));_x000D_
if($(this).attr('alt'))_x000D_
modal.find('div').text($(this).attr('alt'));_x000D_
$(this).after(modal);_x000D_
modal = $(this).next();_x000D_
$(this).click(function(event) {_x000D_
modal.show(300);_x000D_
modal.find('span').show(0.3);_x000D_
});_x000D_
modal.find('span').click(function(event) {_x000D_
modal.hide(300);_x000D_
});_x000D_
});_x000D_
$(document).keyup(function(event) {_x000D_
if(event.which==27)_x000D_
$('.img-modal>span').click();_x000D_
});
_x000D_
img.modal-img {_x000D_
cursor: pointer;_x000D_
transition: 0.3s;_x000D_
}_x000D_
img.modal-img:hover {_x000D_
opacity: 0.7;_x000D_
}_x000D_
.img-modal {_x000D_
display: none;_x000D_
position: fixed;_x000D_
z-index: 99999;_x000D_
padding-top: 100px;_x000D_
left: 0;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow: auto;_x000D_
background-color: rgba(0,0,0,0.9);_x000D_
}_x000D_
.img-modal img {_x000D_
margin: auto;_x000D_
display: block;_x000D_
width: 80%;_x000D_
max-width: 700%;_x000D_
}_x000D_
.img-modal div {_x000D_
margin: auto;_x000D_
display: block;_x000D_
width: 80%;_x000D_
max-width: 700px;_x000D_
text-align: center;_x000D_
color: #ccc;_x000D_
padding: 10px 0;_x000D_
height: 150px;_x000D_
}_x000D_
.img-modal img, .img-modal div {_x000D_
animation: zoom 0.6s;_x000D_
}_x000D_
.img-modal span {_x000D_
position: absolute;_x000D_
top: 15px;_x000D_
right: 35px;_x000D_
color: #f1f1f1;_x000D_
font-size: 40px;_x000D_
font-weight: bold;_x000D_
transition: 0.3s;_x000D_
cursor: pointer;_x000D_
}_x000D_
@media only screen and (max-width: 700px) {_x000D_
.img-modal img {_x000D_
width: 100%;_x000D_
}_x000D_
}_x000D_
@keyframes zoom {_x000D_
0% {_x000D_
transform: scale(0);_x000D_
}_x000D_
100% {_x000D_
transform: scale(1);_x000D_
}_x000D_
}_x000D_
Javascript:_x000D_
_x000D_
$('img.modal-img').each(function() {_x000D_
var modal = $('<div class="img-modal"><span>×</span><img /><div></div></div>');_x000D_
modal.find('img').attr('src', $(this).attr('src'));_x000D_
if($(this).attr('alt'))_x000D_
modal.find('div').text($(this).attr('alt'));_x000D_
$(this).after(modal);_x000D_
modal = $(this).next();_x000D_
$(this).click(function(event) {_x000D_
modal.show(300);_x000D_
modal.find('span').show(0.3);_x000D_
});_x000D_
modal.find('span').click(function(event) {_x000D_
modal.hide(300);_x000D_
});_x000D_
});_x000D_
$(document).keyup(function(event) {_x000D_
if(event.which==27)_x000D_
$('.img-modal>span').click();_x000D_
});_x000D_
_x000D_
HTML:
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<img src="http://www.google.com/favicon.ico" class="modal-img">
_x000D_
You may wonder how to interpret your probability in the context of looking for a correlation in a particular direction (negative or positive correlation.) Here is a function I wrote to help with that. It might even be right!
It's based on info I gleaned from http://www.vassarstats.net/rsig.html and http://en.wikipedia.org/wiki/Student%27s_t_distribution, thanks to other answers posted here.
# Given (possibly random) variables, X and Y, and a correlation direction,
# returns:
# (r, p),
# where r is the Pearson correlation coefficient, and p is the probability
# that there is no correlation in the given direction.
#
# direction:
# if positive, p is the probability that there is no positive correlation in
# the population sampled by X and Y
# if negative, p is the probability that there is no negative correlation
# if 0, p is the probability that there is no correlation in either direction
def probabilityNotCorrelated(X, Y, direction=0):
x = len(X)
if x != len(Y):
raise ValueError("variables not same len: " + str(x) + ", and " + \
str(len(Y)))
if x < 6:
raise ValueError("must have at least 6 samples, but have " + str(x))
(corr, prb_2_tail) = stats.pearsonr(X, Y)
if not direction:
return (corr, prb_2_tail)
prb_1_tail = prb_2_tail / 2
if corr * direction > 0:
return (corr, prb_1_tail)
return (corr, 1 - prb_1_tail)
Yes you can sort the options by its text and append it back to the select box.
function NASort(a, b) {
if (a.innerHTML == 'NA') {
return 1;
}
else if (b.innerHTML == 'NA') {
return -1;
}
return (a.innerHTML > b.innerHTML) ? 1 : -1;
};
Save the Excel file to CSV, and read the resulting file with C# using a CSV reader library like FileHelpers.
For a Swift 3 & 4 version of nevyn's answer:
UIApplication.shared.sendAction(#selector(UIView.resignFirstResponder), to: nil, from: nil, for: nil)
Spring source code to explain how ApplicationContextAware work
when you use ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
In AbstractApplicationContext
class,the refresh()
method have the following code:
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
enter this method,beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
will add ApplicationContextAwareProcessor to AbstractrBeanFactory.
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
...........
When spring initialize bean in AbstractAutowireCapableBeanFactory
,
in method initializeBean
,call applyBeanPostProcessorsBeforeInitialization
to implement the bean post process. the process include inject the applicationContext.
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
when BeanPostProcessor implement Objectto execute the postProcessBeforeInitialization method,for example ApplicationContextAwareProcessor
that added before.
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(
new EmbeddedValueResolver(this.applicationContext.getBeanFactory()));
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
Install terminal emulator app, then to see routing table run iproute
from the command prompt. Does not require root permissions. I don't know how to get the DNS server. There's no /etc/resolv.conf
file. You can try nslookup www.google.com
and see what it reports for your server, but on my phone it reports 0.0.0.0
which isn't too helpful.
<iframe src="http://youraddress.com" style="width: 100%; height: 100vh;">
</iframe>
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
realloc is a pretty expensive action... here's my way of receiving a string, the realloc ratio is not 1:1 :
char* getAString()
{
//define two indexes, one for logical size, other for physical
int logSize = 0, phySize = 1;
char *res, c;
res = (char *)malloc(sizeof(char));
//get a char from user, first time outside the loop
c = getchar();
//define the condition to stop receiving data
while(c != '\n')
{
if(logSize == phySize)
{
phySize *= 2;
res = (char *)realloc(res, sizeof(char) * phySize);
}
res[logSize++] = c;
c = getchar();
}
//here we diminish string to actual logical size, plus one for \0
res = (char *)realloc(res, sizeof(char *) * (logSize + 1));
res[logSize] = '\0';
return res;
}
Noneof the answers worked for me, I was getting "'HttpRequestBase' does not contain a definition for 'Query'", but this did work:
HttpContext.Current.Request.QueryString["index"]
I will go for Inner Join in this context. If I would have used contains, it would iterate 6 times despite if the fact that there are just one match.
var desiredNames = new[] { "Pankaj", "Garg" };
var people = new[]
{
new { FirstName="Pankaj", Surname="Garg" },
new { FirstName="Marc", Surname="Gravell" },
new { FirstName="Jeff", Surname="Atwood" }
};
var records = (from p in people join filtered in desiredNames on p.FirstName equals filtered select p.FirstName).ToList();
Suppose I have two list objects.
List 1 List 2
1 12
2 7
3 8
4 98
5 9
6 10
7 6
Using Contains, it will search for each List 1 item in List 2 that means iteration will happen 49 times !!!
You can use nonzero function. it returns the nonzero indices of the given input.
Easy Way
>>> (e > 15).nonzero()
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
to see the indices more cleaner, use transpose
method:
>>> numpy.transpose((e>15).nonzero())
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Not Bad Way
>>> numpy.nonzero(e > 15)
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
or the clean way:
>>> numpy.transpose(numpy.nonzero(e > 15))
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
You can generate INSERT or MERGE statement with this simple and free application I wrote a few years ago:
Data Script Writer (Desktop Application for Windows)
Also, I wrote a blog post about these tools recently and approach to leveraging SSDT for a deployment database with data. Find out more:
Script and deploy the data for database from SSDT project
Call visudo
and add this:
user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh
The command paths must be absolute! Then call sudo -u user2 /home/user2/bin/test.sh
from a user1
shell. Done.
This is another way for disabling constraints (it came from https://asktom.oracle.com/pls/asktom/f?p=100:11:2402577774283132::::P11_QUESTION_ID:399218963817)
WITH qry0 AS
(SELECT 'ALTER TABLE '
|| child_tname
|| ' DISABLE CONSTRAINT '
|| child_cons_name
disable_fk
, 'ALTER TABLE '
|| parent_tname
|| ' DISABLE CONSTRAINT '
|| parent.parent_cons_name
disable_pk
FROM (SELECT a.table_name child_tname
,a.constraint_name child_cons_name
,b.r_constraint_name parent_cons_name
,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) child_columns
FROM user_cons_columns a
,user_constraints b
WHERE a.constraint_name = b.constraint_name AND b.constraint_type = 'R'
GROUP BY a.table_name, a.constraint_name
,b.r_constraint_name) child
,(SELECT a.constraint_name parent_cons_name
,a.table_name parent_tname
,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) parent_columns
FROM user_cons_columns a
,user_constraints b
WHERE a.constraint_name = b.constraint_name AND b.constraint_type IN ('P', 'U')
GROUP BY a.table_name, a.constraint_name) parent
WHERE child.parent_cons_name = parent.parent_cons_name
AND (parent.parent_tname LIKE 'V2_%' OR child.child_tname LIKE 'V2_%'))
SELECT DISTINCT disable_pk
FROM qry0
UNION
SELECT DISTINCT disable_fk
FROM qry0;
works like a charm
The closest thing to Win32 in linux would be the libc, as you mention not only the UI but events and "other os stuff"
You have an array that is the "hash table".
In Open Hashing each cell in the array points to a list containg the collisions. The hashing has produced the same index for all items in the linked list.
In Closed Hashing you use only one array for everything. You store the collisions in the same array. The trick is to use some smart way to jump from collision to collision unitl you find what you want. And do this in a reproducible / deterministic way.
Read about request objects that your views receive: https://docs.djangoproject.com/en/dev/ref/request-response/#httprequest-objects
Also your hidden field needs a reliable name and then a value:
<input type="hidden" name="title" value="{{ source.title }}">
Then in a view:
request.POST.get("title", "")
Combining these lines of code around a file_get_contents()
call to an external url helped me handle warnings like "failed to open stream: Connection timed out" much better:
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
}, E_WARNING);
try {
$iResult = file_get_contents($sUrl);
} catch (Exception $e) {
$this->sErrorMsg = $e->getMessage();
}
restore_error_handler();
This solution works within object context, too. You could use it in a function:
public function myContentGetter($sUrl)
{
... code above ...
return $iResult;
}
You can use a single line to add and remove class on a div. Please remove a class first to add a new class.
$('div').on('click',function(){
$('div').removeClass('active').addClass('active');
});
Below is the end-to-end solution that I use to export Hive table data to HDFS as a single named CSV file with a header.
(it is unfortunate that it's not possible to do with one HQL statement)
It consists of several commands, but it's quite intuitive, I think, and it does not rely on the internal representation of Hive tables, which may change from time to time.
Replace "DIRECTORY" with "LOCAL DIRECTORY" if you want to export the data to a local filesystem versus HDFS.
# cleanup the existing target HDFS directory, if it exists
sudo -u hdfs hdfs dfs -rm -f -r /tmp/data/my_exported_table_name/*
# export the data using Beeline CLI (it will create a data file with a surrogate name in the target HDFS directory)
beeline -u jdbc:hive2://my_hostname:10000 -n hive -e "INSERT OVERWRITE DIRECTORY '/tmp/data/my_exported_table_name' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' SELECT * FROM my_exported_table_name"
# set the owner of the target HDFS directory to whatever UID you'll be using to run the subsequent commands (root in this case)
sudo -u hdfs hdfs dfs -chown -R root:hdfs /tmp/data/my_exported_table_name
# write the CSV header record to a separate file (make sure that its name is higher in the sort order than for the data file in the target HDFS directory)
# also, obviously, make sure that the number and the order of fields is the same as in the data file
echo 'field_name_1,field_name_2,field_name_3,field_name_4,field_name_5' | hadoop fs -put - /tmp/data/my_exported_table_name/.header.csv
# concatenate all (2) files in the target HDFS directory into the final CSV data file with a header
# (this is where the sort order of the file names is important)
hadoop fs -cat /tmp/data/my_exported_table_name/* | hadoop fs -put - /tmp/data/my_exported_table_name/my_exported_table_name.csv
# give the permissions for the exported data to other users as necessary
sudo -u hdfs hdfs dfs -chmod -R 777 /tmp/data/hive_extr/drivers
SELECT username, salary
FROM tblname
GROUP by salary
ORDER by salary desc
LIMIT 0,1 ;
You are trying to call DeckOfCards::shuffle
with a deckOfCards
parameter:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck
But the method takes a vector<Card>&
:
void deckOfCards::shuffle(vector<Card>& deck)
The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.
Error:
[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'
Paraphrased:
Hey, pal. You're trying to call a function called
shuffle
which apparently takes a single parameter of type reference-to-deckOfCards
, but there is no such function.
Error:
[Note] candidate is:
In file included from main.cpp
[Note] void deckOfCards::shuffle(std::vector&)
Paraphrased:
I mean, maybe you meant this other function called
shuffle
, but that one takes a reference-tovector<something>
.
Error:
[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'
Which I'd be happy to call if I knew how to convert from a
deckOfCards
to avector
; but I don't. So I won't.
In your Dockerfile use this command:
CMD ["sh", "-c", "tail -f /dev/null"]
Build your docker image.
kubectl run debug-container -it --image=<your-image>
I got such a problem after I upgraded my node version with brew. To fix the problem
1)run $brew doctor
to check out if it is successfully installed or not
2) In case you missed clearing any node-related file before, such error log might pop up:
Warning: You have unlinked kegs in your Cellar
Leaving kegs unlinked can lead to build-trouble and cause brews that depend on
those kegs to fail to run properly once built.
node
3) Now you are recommended to run brew link command to delete the original node-related files and overwrite new files - $ brew link node
.
And that's it - everything works again !!!
Update: Thanks to Germán Rodríguez Herrera!
In javascript try: /123-(apple(?=-)|banana(?=-)|(?!-))-?456/
Remember that the result is in group 1
If you're using a Storyboard and you're coming from a push segue, you could also just override shouldPerformSegueWithIdentifier:sender:
.
There's lots of FTP sites you can get into with the 'anonymous' account and download, but a 'public' site that allows anonymous uploads would be utterly swamped with pr0n and warez in short order.
It's easy enough to set up your own FTP server for testing uploads. There's plenty of them for most any desktop OS. There's one built into IIS, for instance.
Last revision merged from trunk to branch can be found by running this command inside the working copy directory:
svn log -v --stop-on-copy
The FindBugs initial approach involves XML configuration files aka filters. This is really less convenient than the PMD solution but FindBugs works on bytecode, not on the source code, so comments are obviously not an option. Example:
<Match>
<Class name="com.mycompany.Foo" />
<Method name="bar" />
<Bug pattern="DLS_DEAD_STORE_OF_CLASS_LITERAL" />
</Match>
However, to solve this issue, FindBugs later introduced another solution based on annotations (see SuppressFBWarnings
) that you can use at the class or at the method level (more convenient than XML in my opinion). Example (maybe not the best one but, well, it's just an example):
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
value="HE_EQUALS_USE_HASHCODE",
justification="I know what I'm doing")
Note that since FindBugs 3.0.0 SuppressWarnings
has been deprecated in favor of @SuppressFBWarnings
because of the name clash with Java's SuppressWarnings
.
Another way is to simply pass the json string as a dict to the constructor of your object. For example your object is:
class Payload(object):
def __init__(self, action, method, data, *args, **kwargs):
self.action = action
self.method = method
self.data = data
And the following two lines of python code will construct it:
j = json.loads(yourJsonString)
payload = Payload(**j)
Basically, we first create a generic json object from the json string. Then, we pass the generic json object as a dict to the constructor of the Payload class. The constructor of Payload class interprets the dict as keyword arguments and sets all the appropriate fields.
In version 1.1.1:
.*
><
>\n<
For users of SQL 2000, the actual command that will provide this information is:
select c.text
from sysobjects o
join syscomments c on c.id = o.id
where o.name = '<view_name_here>'
and o.type = 'V'
You can also use the following syntax for the strongly typed version:
<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(),
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{ %>
Maybe this page helps:
Scenario Two: The Microsoft Visual Studio 2010 IDE crashes while creating OR debugging a web application project. This above error occurs because of corrupted Cache of Visual Studio 2010. In order to resolve the issue just delete the project Cache from the below location:
C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplatesCache
C:\Program Files(x86)\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplatesCache
Then run
devenv.exe /setup
to re-build the cache.
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static
keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
If you need to speed up the process (for example counting 30k or more files) then I would go with something like this..
$filepath = "c:\MyFolder"
$filetype = "*.txt"
$file_count = [System.IO.Directory]::GetFiles("$filepath", "$filetype").Count
This is only a warning: your code still works, but probably won't work in the future as the method is deprecated. See the relevant source of Chromium and corresponding patch.
This has already been recognised and fixed in jQuery 1.11 (see here and here).
I know this is old, but I had a similar issue with no real answers, where I wanted to remove all keydown
event listeners from the document. Instead of removing them, I override the addEventListener
to ignore them before they were even added, similar to Toms answer above, by adding this before any other scripts are loaded:
<script type="text/javascript">
var current = document.addEventListener;
document.addEventListener = function (type, listener) {
if(type =="keydown")
{
//do nothing
}
else
{
var args = [];
args[0] = type;
args[1] = listener;
current.apply(this, args);
}
};
</script>
Ensure the below folders in storage directory:
Below is a command-line snippet that does for you
cd storage
mkdir logs
mkdir framework
mkdir framework/cache && framework/cache/data
mkdir framework/sessions
mkdir framework/testing
mkdir framework/views
chgrp -R www-data ../storage
chown -R www-data ../storage
What is JNDI ?
It stands for Java Naming and Directory Interface.
What is its basic use?
JNDI allows distributed applications to look up services in an abstract, resource-independent way.
When it is used?
The most common use case is to set up a database connection pool on a Java EE application server. Any application that's deployed on that server can gain access to the connections they need using the JNDI name java:comp/env/FooBarPool
without having to know the details about the connection.
This has several advantages:
devl->int->test->prod
environments, you can use the same JNDI name in each environment and hide the actual database being used. Applications don't have to change as they migrate between environments.index
and find
Next to the find
method there is as well index
. find
and index
both yield the same result: returning the position of the first occurrence, but if nothing is found index
will raise a ValueError
whereas find
returns -1
. Speedwise, both have the same benchmark results.
s.find(t) #returns: -1, or index where t starts in s
s.index(t) #returns: Same as find, but raises ValueError if t is not in s
rfind
and rindex
:In general, find and index return the smallest index where the passed-in string starts, and
rfind
andrindex
return the largest index where it starts Most of the string searching algorithms search from left to right, so functions starting withr
indicate that the search happens from right to left.
So in case that the likelihood of the element you are searching is close to the end than to the start of the list, rfind
or rindex
would be faster.
s.rfind(t) #returns: Same as find, but searched right to left
s.rindex(t) #returns: Same as index, but searches right to left
Source: Python: Visual QuickStart Guide, Toby Donaldson
If you ever want to know exactly what a reserved function does in python, type in help(enter_keyword)
Make sure if you are entering a reserved keyword that you enter it as a string.
I have the same problem when trying to update record using Attach() and then SaveChanges() combination, but I am using SQLite DB and its EF provider (the same code works in SQLServer DB without problem).
I found out, when your DB column has GUID (or UniqueIdentity) in SQLite and your model is nvarchar, SQLIte EF treats it as Binary(i.e., byte[]) by default. So when SQLite EF provider tries to convert GUID into the model (string in my case) it will fail as it will convert to byte[]. The fix is to tell the SQLite EF to treat GUID as TEXT (and therefore conversion is into strings, not byte[]) by defining "BinaryGUID=false;" in the connectionstring (or metadata, if you're using database first) like so:
<connectionStrings>
<add name="Entities" connectionString="metadata=res://savetyping...=System.Data.SQLite.EF6;provider connection string="data source=C:\...\db.sqlite3;Version=3;BinaryGUID=false;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Link to the solution that worked for me: How does the SQLite Entity Framework 6 provider handle Guids?
Here's the complete process in Kotlin:
the spinner adapter class:
class CustomSpinnerAdapter(
context: Context,
textViewResourceId: Int,
val list: List<User>
) : ArrayAdapter<User>(
context,
textViewResourceId,
list
) {
override fun getCount() = list.size
override fun getItem(position: Int) = list[position]
override fun getItemId(position: Int) = list[position].report.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
return (super.getDropDownView(position, convertView, parent) as TextView).apply {
text = list[position].name
}
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
return (super.getDropDownView(position, convertView, parent) as TextView).apply {
text = list[position].name
}
}
}
and use it in your activity/fragment like this:
spinner.adapter = CustomerSalesSpinnerAdapter(
context,
R.layout.cuser_spinner_item,
userList
)
The easiest solution is to just run your own counter thus:
int i = 0;
for (String s : stringArray) {
doSomethingWith(s, i);
i++;
}
The reason for this is because there's no actual guarantee that items in a collection (which that variant of for
iterates over) even have an index, or even have a defined order (some collections may change the order when you add or remove elements).
See for example, the following code:
import java.util.*;
public class TestApp {
public static void AddAndDump(AbstractSet<String> set, String str) {
System.out.println("Adding [" + str + "]");
set.add(str);
int i = 0;
for(String s : set) {
System.out.println(" " + i + ": " + s);
i++;
}
}
public static void main(String[] args) {
AbstractSet<String> coll = new HashSet<String>();
AddAndDump(coll, "Hello");
AddAndDump(coll, "My");
AddAndDump(coll, "Name");
AddAndDump(coll, "Is");
AddAndDump(coll, "Pax");
}
}
When you run that, you can see something like:
Adding [Hello]
0: Hello
Adding [My]
0: Hello
1: My
Adding [Name]
0: Hello
1: My
2: Name
Adding [Is]
0: Hello
1: Is
2: My
3: Name
Adding [Pax]
0: Hello
1: Pax
2: Is
3: My
4: Name
indicating that, rightly so, order is not considered a salient feature of a set.
There are other ways to do it without a manual counter but it's a fair bit of work for dubious benefit.
Here is another possible workaround:
if exists (select * from master..sysservers where srvname = 'loopback')
exec sp_dropserver 'loopback'
go
exec sp_addlinkedserver @server = N'loopback', @srvproduct = N'', @provider = N'SQLOLEDB', @datasrc = @@servername
go
create function testit()
returns int
as
begin
declare @res int;
select @res=count(*) from openquery(loopback, 'exec sp_who');
return @res
end
go
select dbo.testit()
It's not so scary as xp_cmdshell
but also has too many implications for practical use.
Yes. There is a simple way to remove everything in iPython. In iPython console, just type:
%reset
Then system will ask you to confirm. Press y. If you don't want to see this prompt, simply type:
%reset -f
This should work..
In real life where you encounter systems already written and adding indexes to tables then drastically slows down the data loading of a 14gig data table, you are sometime forced to used WITH NOLOCK on your reports and end of month proessing so that the aggregate funtions (sum, count etc) do not do row, page, table locking and deteriate the overall performance. Easy to say in a new system never use WITH NOLOCK and use indexes - but adding indexes severly downgrades data loading, and when I'm then told, well, alter the code base to delete indexes, then bulk load then recreate the indexes - which is all well and good, if you are developing a new system. But Not when you have a system already in place.
I always just convert a matrix:
x <- as.data.frame(matrix(nrow = 100, ncol = 10))
Following one is working fine with moments js 2.10 and above
$.fn.dataTableExt.afnFiltering.push(
function( settings, data, dataIndex ) {
var min = $('#min-date').val()
var max = $('#max-date').val()
var createdAt = data[0] || 0; // Our date column in the table
//createdAt=createdAt.split(" ");
var startDate = moment(min, "DD/MM/YYYY");
var endDate = moment(max, "DD/MM/YYYY");
var diffDate = moment(createdAt, "DD/MM/YYYY");
//console.log(startDate);
if (
(min == "" || max == "") ||
(diffDate.isBetween(startDate, endDate))
) { return true; }
return false;
}
);
If you need a function that behaves as a nop, try
nop = lambda *a, **k: None
nop()
Sometimes I do stuff like this when I'm making dependencies optional:
try:
import foo
bar=foo.bar
baz=foo.baz
except:
bar=nop
baz=nop
# Doesn't break when foo is missing:
bar()
baz()
Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it. If you really need something like an add method you need a mutable collection, e.g. http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html which has a += method.
Not sure if it will do for Greek, but I had the same issue for Brazilian Portuguese characters and my solution was to use html entities. I had basically two cases:
For these, I first encoded it to html entities with htmlentities()
and then decoded them to iso-8859-1
. Example:
$s = html_entity_decode(htmlentities($my_variable_text), ENT_COMPAT | ENT_HTML401, 'iso-8859-1');
For these, I just left htmlentities()
call out. Example:
$s = html_entity_decode("Treasurer/Trésorier", ENT_COMPAT | ENT_HTML401, 'iso-8859-1');
Then I passed $s
to FPDF, like in this example:
$pdf->Cell(100, 20, $s, 0, 0, 'L');
Note: ENT_COMPAT | ENT_HTML401
is the standard value for parameter #2, as in http://php.net/manual/en/function.html-entity-decode.php
Hope that helps.
If the wrong type of parameter is passed to a function – and PHP cannot convert it automatically – a warning is thrown. This warning identifies which parameter is the problem, and what data type is expected. The solution: change the indicated parameter to the correct data type.
For example this code:
echo substr(["foo"], 23);
Results in this output:
PHP Warning: substr() expects parameter 1 to be string, array given
You asked of Function but there is an easier way too. When you will upload the image, copy it's URL which is at the top right part of the window (View Screenshot) and paste it in the src='[link you copied]'
. Hope this will help if someone is looking for similar problem.
I solved this just now, in the system tray (bottom right) you can click ion the IIS icon and stop the current site, then it allowed me to run.
It is easy to check for removable devices. However, there's no guarantee that it is a USB device:
var drives = DriveInfo.GetDrives()
.Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);
This will return a list of all removable devices that are currently accessible. More information:
DriveInfo
class (msdn documentation)DriveType
enumeration (msdn documentation)Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
In my case, I use
$.getJSON(url, function(json) { ... });
to make the request (to Flickr's API), and I got the same MIME error. Like the answer above suggested, adding the following code:
$.ajaxSetup({ dataType: "jsonp" });
Fixed the issue and I no longer see the MIME type error in Chrome's console.
Hoisted from the comments
2020 comment: rather than using regex, we now have
URLSearchParams
, which does all of this for us, so no custom code, let alone regex, are necessary anymore.
Browser support is listed here https://caniuse.com/#feat=urlsearchparams
I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually and re.exec()
:
function getUrlParams(url) {
var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
match, params = {},
decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};
if (typeof url == "undefined") url = document.location.href;
while (match = re.exec(url)) {
params[decode(match[1])] = decode(match[2]);
}
return params;
}
var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr");
result
is an object:
{ f: "q" geocode: "" hl: "de" ie: "UTF8" iwloc: "addr" ll: "50.116616,8.680573" q: "Frankfurt am Main" sll: "50.106047,8.679886" source: "s_q" spn: "0.35972,0.833588" sspn: "0.370369,0.833588" z: "11" }
The regex breaks down as follows:
(?: # non-capturing group \?|& # "?" or "&" (?:amp;)? # (allow "&", for wrongly HTML-encoded URLs) ) # end non-capturing group ( # group 1 [^=]+ # any character except "=", "&" or "#"; at least once ) # end group 1 - this will be the parameter's name (?: # non-capturing group =? # an "=", optional ( # group 2 [^]* # any character except "&" or "#"; any number of times ) # end group 2 - this will be the parameter's value ) # end non-capturing group
i faced the same issue while using eclipse kepler and maven version 3.2,
while building the project, it showed me the same error in eclipse
there are two versions (2.5 and 2.6) of plugin under
.m2/repository/org/apache/maven/plugins/maven-resources-plugin/
i removed 2.5 version then it worked for me
As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done.
In addition to the three parameters for lookup_value, table_range to be searched, and the column_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range_lookup".
Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found.
If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.)
However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value.
Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the left of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria.
Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be:
=VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE)
If you use ES6 anon functions, it will conflict with $(this)
This works:
$('.dna-list').on('click', '.card', function(e) {
console.log($(this));
});
This doesn't work:
$('.dna-list').on('click', '.card', (e) => {
console.log($(this));
});
You can try this:
$ brew search jdk
$ brew cask install homebrew/cask-versions/adoptopenjdk8
$ /usr/libexec/java_home
You can use following approach:
import org.apache.commons.codec.binary.Base64;
// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));
// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));
Hope this answers your doubt.
This will work and store the result in test.txt file which will be present in the same directory
fs.readdirSync(__dirname).forEach(file => {
fs.appendFileSync("test.txt", file+"\n", function(err){
})
})
This is just a suggestion, it might not work and I'm prepared to be called on this.
This will generate false positives, but hopefully not false negatives.
Resize both of the images so that they are the same size (I assume that the ratios of widths to lengths are the same in both images).
Compress a bitmap of both images with a lossless compression algorithm (e.g. gzip).
Find pairs of files that have similar file sizes. For instance, you could just sort every pair of files you have by how similar the file sizes are and retrieve the top X.
As I said, this will definitely generate false positives, but hopefully not false negatives. You can implement this in five minutes, whereas the Porikil et. al. would probably require extensive work.
Put file inside while True
like so
while True:
f = open('torecv.png','wb')
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
print "Receiving..."
l = c.recv(1024)
while (l):
print "Receiving..."
f.write(l)
l = c.recv(1024)
f.close()
print "Done Receiving"
c.send('Thank you for connecting')
c.close()
Using something like selection.node().getBBox()
you get values like
{
height: 5,
width: 5,
y: 50,
x: 20
}
Use selection.node().getBoundingClientRect()
The thing is that decimal numbers defaults to double. And since double doesn't fit into float you have to tell explicitely you intentionally define a float. So go with:
float b = 3.6f;
The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState
method when using React.createClass
.
See the official React doc on the subject of ES6 classes.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { /* initial state */ };
}
}
is equivalent to
var MyComponent = React.createClass({
getInitialState() {
return { /* initial state */ };
},
});
For Next button you can use xpath or cssSelector as below:
xpath for Next button: //input[@value='Next']
cssPath for Next button: input[value=Next]
You don't need to run Xcode 10.2 for iOS 12.2 support. You just need access to the appropriate folder in DeviceSupport.
A possible solution is
/Applications
. It's possible to have multiple Xcode versions in the same directory.Create a symbolic link in Terminal.app to have access to the 12.2 device support folder in Xcode 10.2
ln -s /Applications/Xcode102.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/12.2\ \(16E226\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
You can move Xcode 10.2 to somewhere else but then you have to adjust the path.
Now Xcode 10.1 supports devices running iOS 12.2
Use the .text()
function:
var text = $("<p> example ive got a string</P>").text();
Update: As Brilliand points out below, if the input string does not contain any tags and you are unlucky enough, it might be treated as a CSS selector. So this version is more robust:
var text = $("<div/>").html("<p> example ive got a string</P>").text();
Another possibility: When you created the user, you may have accidentally been use
ing a database other than admin
, or other than the one you wanted. You need to set --authenticationDatabase
to the database that the user was actually created under.
mongodb
seems to put you in the test
database by default when you open the shell, so you'd need to write --authenticationDatabase test
rather than --authenticationDatabase admin
if you accidentally were use
ing test
when you ran db.createUser(...)
.
Assuming you have access to the machine that's running the mongodb instance, y could disable authorization in /etc/mongod.conf
(comment out authorization
which is nested under security), and then restart your server, and then run:
mongo
show users
And you might get something like this:
{
"_id" : "test.myusername",
"user" : "myusername",
"db" : "test",
"roles" : [
{
"role" : "dbOwner",
"db" : "mydatabasename"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
Notice that the db
value equals test
. That's because when I created the user, I didn't first run use admin
or use desiredDatabaseName
. So you can delete the user with db.dropUser("myusername")
and then create another user under your desired database like so:
use desiredDatabaseName
db.createUser(...)
Hopefully that helps someone who was in my position as a noob with this stuff.
The WebClient class should be more than capable of handling the functionality you describe, for example:
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData("http://www.yoursite.com/resource/file.htm");
string webData = System.Text.Encoding.UTF8.GetString(raw);
or (further to suggestion from Fredrick in comments)
System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString("http://www.yoursite.com/resource/file.htm");
When you say it took 30 seconds, can you expand on that a little more? There are many reasons as to why that could have happened. Slow servers, internet connections, dodgy implementation etc etc.
You could go a level lower and implement something like this:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.yoursite.com/resource/file.htm");
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
{
streamWriter.Write(requestData);
}
string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
However, at the end of the day the WebClient class wraps up this functionality for you. So I would suggest that you use WebClient and investigate the causes of the 30 second delay.
Add border-collapse: collapse
into the style
attribute value of the inner table
element. You could alternatively add the attribute cellspacing=0
there, but then you would have a double border between the cells.
I.e.:
<table class="main-story-image" style="float: left; width: 180px; margin: 0 25px 25px 25px; border-collapse: collapse">
If you want, you can deactivate this feature in your git core config using
git config core.autocrlf false
But it would be better to just get rid of the warnings using
git config core.autocrlf true
You must wrap your element in a table-cell
, within a table
using display
.
Like this:
<div>
<span class='twoline'>Two line text</span>
<span class='float'>Float right</span>
</div>
and
.float {
display: table-cell;
vertical-align: middle;
text-align: right;
}
.twoline {
width: 50px;
display: table-cell;
}
div {
display: table;
border: solid 1px blue;
width: 500px;
height: 100px;
}
Shown here: http://jsfiddle.net/e8ESb/7/
i wrote a helper method to help me go through all my selected elements and remove the active class.
function removeClassFromElem(classSelect, classToRemove){
$(classSelect).each(function(){
var currElem=$(this);
if(currElem.hasClass(classToRemove)){
currElem.removeClass(classToRemove);
}
});
}
//usage
removeClassFromElem('.someclass', 'active');
In our case the problem was that we change the default root namespace name.
This is the Project Configuration screen
We finally decided to back to the original name and the problem was solved.
The problem actually was the dots in the Root namespace. With two dots (Name.Child.Child) it doesnt work. But with one (Name.ChidChild) works.
As others have mentioned, you can use document.title = 'My new title'
and React Helmet to update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.
If you are using create-react-app
the initial document title is set in the <title>
tag /public/index.html
file.
You can edit this directly or use a placeholder which will be filled from environmental variables:
/.env
:
REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...
If for some reason I wanted a different title in my development environment -
/.env.development
:
REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...
/public/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
...
<title>%REACT_APP_SITE_TITLE%</title>
...
</head>
<body>
...
</body>
</html>
This approach also means that I can read the site title environmental variable from my application using the global process.env
object, which is nice:
console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!
I just published react-delta which solves this exact sort of scenario. In my opinion, useEffect
has too many responsibilities.
Object.is
react-delta
breaks useEffect
's responsibilities into several smaller hooks.
Responsibility #1
usePrevious(value)
useLatest(value)
useDelta(value, options)
useDeltaArray(valueArray, options)
useDeltaObject(valueObject, options)
some(deltaArray)
every(deltaArray)
Responsibility #2
In my experience, this approach is more flexible, clean, and concise than useEffect
/useRef
solutions.
In Intellij 13 the layout has changed, the Settings button can only be found in File -> Settings and not in the toolbars, and from there you follow the same steps: Editor -> Appearance -> Show line numbers, or search for Line numbers in the Settings search input.
That also resolved my issue.
@ViewChild('map', {static: false}) googleMap;
Ok, to remove all variables, maybe the prettiest is
$url = strtok($url, '?');
See about strtok
here.
Its the fastest (see below), and handles urls without a '?' properly.
To take a url+querystring and remove just one variable (without using a regex replace, which may be faster in some cases), you might do something like:
function removeqsvar($url, $varname) {
list($urlpart, $qspart) = array_pad(explode('?', $url), 2, '');
parse_str($qspart, $qsvars);
unset($qsvars[$varname]);
$newqs = http_build_query($qsvars);
return $urlpart . '?' . $newqs;
}
A regex replace to remove a single var might look like:
function removeqsvar($url, $varname) {
return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}
Heres the timings of a few different methods, ensuring timing is reset inbetween runs.
<?php
$number_of_tests = 40000;
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
preg_replace('/\\?.*/', '', $str);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "regexp execution time: ".$totaltime." seconds; ";
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$str = explode('?', $str);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "explode execution time: ".$totaltime." seconds; ";
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$qPos = strpos($str, "?");
$url_without_query_string = substr($str, 0, $qPos);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "strpos execution time: ".$totaltime." seconds; ";
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$url_without_query_string = strtok($str, '?');
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "tok execution time: ".$totaltime." seconds; ";
shows
regexp execution time: 0.14604902267456 seconds; explode execution time: 0.068033933639526 seconds; strpos execution time: 0.064775943756104 seconds; tok execution time: 0.045819044113159 seconds;
regexp execution time: 0.1408839225769 seconds; explode execution time: 0.06751012802124 seconds; strpos execution time: 0.064877986907959 seconds; tok execution time: 0.047760963439941 seconds;
regexp execution time: 0.14162802696228 seconds; explode execution time: 0.065848112106323 seconds; strpos execution time: 0.064821004867554 seconds; tok execution time: 0.041788101196289 seconds;
regexp execution time: 0.14043688774109 seconds; explode execution time: 0.066350221633911 seconds; strpos execution time: 0.066242933273315 seconds; tok execution time: 0.041517972946167 seconds;
regexp execution time: 0.14228296279907 seconds; explode execution time: 0.06665301322937 seconds; strpos execution time: 0.063700199127197 seconds; tok execution time: 0.041836977005005 seconds;
strtok wins, and is by far the smallest code.
If you have any problems with the "not like" query, Consider that you may have a null in the database. In this case, Use:
IFNULL(word, '') NOT LIKE '%something%'
Summary.
Can I nest git repositories?
Yes. However, by default git does not track the .git
folder of the nested repository. Git has features designed to manage nested repositories (read on).
Does it make sense to git init/add the /project_root to ease management of everything locally or do I have to manage my_project and the 3rd party one separately?
It probably doesn't make sense as git has features to manage nested repositories. Git's built in features to manage nested repositories are submodule
and subtree
.
Here is a blog on the topic and here is a SO question that covers the pros and cons of using each.
I did it in following way :
success: function (result) {
response($.map(result.d.slice(0,10), function (item) {
return {
// Mapping to Required columns (Employee Name and Employee No)
label: item.EmployeeName,
value: item.EmployeeNo
}
}
));
Update 2018
Bootstrap 4
Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col
class on the fluid column.
.sidebar {
width: 180px;
min-height: 100vh;
}
<div class="row">
<div class="sidebar p-2">Fixed width</div>
<div class="col bg-dark text-white pt-2">
Content
</div>
</div>
http://www.codeply.com/go/7LzXiPxo6a
Bootstrap 3..
One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...
@media (min-width:768px) {
#sidebar {
min-width: 300px;
max-width: 300px;
}
#main {
width:calc(100% - 300px);
}
}
Working Bootstrap 3 Fixed-Fluid Demo
Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?
I don't know Sphinx, but as for Lucene vs a database full-text search, I think that Lucene performance is unmatched. You should be able to do almost any search in less than 10 ms, no matter how many records you have to search, provided that you have set up your Lucene index correctly.
Here comes the biggest hurdle though: personally, I think integrating Lucene in your project is not easy. Sure, it is not too hard to set it up so you can do some basic search, but if you want to get the most out of it, with optimal performance, then you definitely need a good book about Lucene.
As for CPU & RAM requirements, performing a search in Lucene doesn't task your CPU too much, though indexing your data is, although you don't do that too often (maybe once or twice a day), so that isn't much of a hurdle.
It doesn't answer all of your questions but in short, if you have a lot of data to search, and you want great performance, then I think Lucene is definitely the way to go. If you're not going to have that much data to search, then you might as well go for a database full-text search. Setting up a MySQL full-text search is definitely easier in my book.
You can definitely do this with vanilla JS like stecb has shown, but I think each
is the best answer to the core question concerning how to do it with lodash.
_.each( myObject.options, ( val, key ) => {
console.log( key, val );
} );
Like JohnnyHK mentioned, there is also the has
method which would be helpful for the use case, but from what is originally stated set
may be more useful. Let's say you wanted to add something to this object dynamically as you've mentioned:
let dynamicKey = 'someCrazyProperty';
let dynamicValue = 'someCrazyValue';
_.set( myObject.options, dynamicKey, dynamicValue );
That's how I'd do it, based on the original description.
I had the same issue.For me the problem was how to configure a cache limit to images.And i came across this site which gave some insights to the procedure on how the issue can be handled.Hope it will be helpful for you too Link:[https://varvy.com/pagespeed/cache-control.html]
I believe that you are looking for the java.lang.BigDecimal class.
Based on the warning message, the component ReactTooltip renders an HTML that might look like this:
<p>
<div>...</div>
</p>
According to this document, a <p></p>
tag can only contain inline elements. That means putting a <div></div>
tag inside it should be improper, since the div
tag is a block element. Improper nesting might cause glitches like rendering extra tags, which can affect your javascript and css.
If you want to get rid of this warning, you might want to customize the ReactTooltip component, or wait for the creator to fix this warning.
A couple of more options :
With asplit
asplit(xy.df, 1)
#[[1]]
# x y
#0.1137 0.6936
#[[2]]
# x y
#0.6223 0.5450
#[[3]]
# x y
#0.6093 0.2827
#....
With split
and row
split(xy.df, row(xy.df)[, 1])
#$`1`
# x y
#1 0.1137 0.6936
#$`2`
# x y
#2 0.6223 0.545
#$`3`
# x y
#3 0.6093 0.2827
#....
data
set.seed(1234)
xy.df <- data.frame(x = runif(10), y = runif(10))
// this works on all browsers.
$(document).ready(function() {
//set initial state.
$('#textbox1').val($(this).is(':checked'));
$('#checkbox1').change(function(e) {
this.checked = $(this).is(":checked") && !!confirm("Are you sure?");
$('#textbox1').val(this.checked);
return true;
});
});
Edited Jarno Argillanders answer:
How to fit Image with your Width and Height:
1) Initialize ImageView and set Image:
iv = (ImageView) findViewById(R.id.iv_image);
iv.setImageBitmap(image);
2) Now resize:
scaleImage(iv);
Edited scaleImage
method: (you can replace EXPECTED bounding values)
private void scaleImage(ImageView view) {
Drawable drawing = view.getDrawable();
if (drawing == null) {
return;
}
Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int xBounding = ((View) view.getParent()).getWidth();//EXPECTED WIDTH
int yBounding = ((View) view.getParent()).getHeight();//EXPECTED HEIGHT
float xScale = ((float) xBounding) / width;
float yScale = ((float) yBounding) / height;
Matrix matrix = new Matrix();
matrix.postScale(xScale, yScale);
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
width = scaledBitmap.getWidth();
height = scaledBitmap.getHeight();
BitmapDrawable result = new BitmapDrawable(context.getResources(), scaledBitmap);
view.setImageDrawable(result);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
And .xml:
<ImageView
android:id="@+id/iv_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
If your Controller extends ControllerBase
or Controller
you can use Content(...)
method:
[HttpGet]
public ContentResult Index()
{
return base.Content("<div>Hello</div>", "text/html");
}
If you choose not to extend from Controller
classes, you can create new ContentResult
:
[HttpGet]
public ContentResult Index()
{
return new ContentResult
{
ContentType = "text/html",
Content = "<div>Hello World</div>"
};
}
Return string content with media type text/html
:
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
response.Content = new StringContent("<div>Hello World</div>");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
There is also an easy way for copying via the clipboard:
In VB.NET, you need to use the GetType
method to retrieve the type of an instance of an object, and the GetType()
operator to retrieve the type of another known type.
Once you have the two types, you can simply compare them using the Is
operator.
So your code should actually be written like this:
Sub FillCategories(ByVal Obj As Object)
Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
cmd.CommandType = CommandType.StoredProcedure
Obj.DataSource = cmd.ExecuteReader
If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then
End If
Obj.DataBind()
End Sub
You can also use the TypeOf
operator instead of the GetType
method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:
If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then
End If
Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.
String file = "";
try {
InputStream is = new FileInputStream(filename);
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
BufferedReader br = new BufferedReader(new InputStreamReader(is,
UTF8), BUFFER_SIZE);
String str;
while ((str = br.readLine()) != null) {
file += str;
}
} catch (Exception e) {
}
Try this,.. :-)
You have the :nth-child()
pseudo-class:
table tr:nth-child(odd) td{
...
}
table tr:nth-child(even) td{
...
}
In the early days of :nth-child()
its browser support was kind of poor. That's why setting class="odd"
became such a common technique. In late 2013 I'm glad to say that IE6 and IE7 are finally dead (or sick enough to stop caring) but IE8 is still around — thankfully, it's the only exception.
I hit this page trying to pad hexadecimal values when I realized that DEC2HEX()
provides that very feature for free.
You just need to add a second parameter. For example, tying to turn 12
into 0C
DEC2HEX(12,2)
=> 0C
DEC2HEX(12,4)
=> 000C
... and so on
"WORKSPACE" environment variable works for the latest version of Jenkins Pipeline. You can use this in your Jenkins file: "${env.WORKSPACE}"
Sample use below:
def files = findFiles glob: '**/reports/*.json'
for (def i=0; i<files.length; i++) {
jsonFilePath = "${files[i].path}"
jsonPath = "${env.WORKSPACE}" + "/" + jsonFilePath
echo jsonPath
hope that helps!!
Mine DID execute commands in order. Here's my version of what I was using it for:
START cmd.exe /k "U: & cd U:\Design_stuff\new_lcso_website_2017 & python -m http.server"
I needed to
If those commands are out of order, it would not display the correct files. I initially forgot to change to U:
and, running the batch file on my Desktop, it created a web page in my browser at http://localhost:8000 showing me the contents of my Desktop instead of the folder I wanted.
All the changes to the NSMutableURLRequest
must be made before calling NSURLConnection
.
I see this problem as I copy and paste the code above and run TCPMon
and see the request is GET
instead of the expected POST
.
NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
delegate:self];
You can use RVM(Ruby version manager) which helps in managing all versions of ruby on your machine , which is very helpful for you development (when migrating to unstable release to stable release )
or for Linux (ubuntu) go for
sudo apt-get install ruby1.8-dev
then sudo gem install rails
to verify it do rails -v
it will show version on rails
after that you can install bundles (required gems for development)
Do you want to add JSON serialization/deserialization functionality, right? Then look at this:
You want to achieve this:
toJson() is a normal method.
fromJson() is a static method.
Implementation:
var Book = function (title, author, isbn, price, stock){
this.title = title;
this.author = author;
this.isbn = isbn;
this.price = price;
this.stock = stock;
this.toJson = function (){
return ("{" +
"\"title\":\"" + this.title + "\"," +
"\"author\":\"" + this.author + "\"," +
"\"isbn\":\"" + this.isbn + "\"," +
"\"price\":" + this.price + "," +
"\"stock\":" + this.stock +
"}");
};
};
Book.fromJson = function (json){
var obj = JSON.parse (json);
return new Book (obj.title, obj.author, obj.isbn, obj.price, obj.stock);
};
Usage:
var book = new Book ("t", "a", "i", 10, 10);
var json = book.toJson ();
alert (json); //prints: {"title":"t","author":"a","isbn":"i","price":10,"stock":10}
var book = Book.fromJson (json);
alert (book.title); //prints: t
Note: If you want you can change all property definitions like this.title
, this.author
, etc by var title
, var author
, etc. and add getters to them to accomplish the UML definition.
If you need a more convenient way to access the results, it's possible to transform the result of an arbitrarily complex SQL query to a Java class with minimal hassle:
Query query = em.createNativeQuery("select 42 as age, 'Bob' as name from dual",
MyTest.class);
MyTest myTest = (MyTest) query.getResultList().get(0);
assertEquals("Bob", myTest.name);
The class needs to be declared an @Entity, which means you must ensure it has an unique @Id.
@Entity
class MyTest {
@Id String name;
int age;
}
I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'MyTable'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
some_col = Column(String(500))
def __init__(self, some_col):
self.some_col = some_col
engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
for class_instance in session.query(MyTable).all():
print(vars(class_instance))
session.close()
You could also get this error when JRE is not set. If so, try adding JRE System Library to your project.
Under Eclipse IDE:
Just to cover one more case when I was getting the same error and the reason was using in instead of of in iterator
Wrong way let file in files
Correct way let file of files
echo $STRING | cut -d " " -f $N
version for data.table based on code from dmanuge :
convNumValues<-function(ds){
ds<-data.table(ds)
dsnum<-data.table(data.matrix(ds))
num_cols <- sapply(dsnum,function(x){mean(as.numeric(is.na(x)))<0.5})
nds <- data.table( dsnum[, .SD, .SDcols=attributes(num_cols)$names[which(num_cols)]]
,ds[, .SD, .SDcols=attributes(num_cols)$names[which(!num_cols)]] )
return(nds)
}
you can set margin based on screen resolution
@media screen and (min-width:768px) and (max-width:991px) {
body {
margin-top:100px;
}
@media screen and (min-width:992px) and (max-width:1199px) {
body {
margin-top:50px;
}
}
body{
padding-top: 10%;
}
#nav{
position: fixed;
background-color: #8b0000;
width: 100%;
top:0;
}
Gartner in Oct 2006 states that testing typically consumes between 10% and 35% of work on a system integration project. I assume that it applies to the waterfall method. This is quite a wide range - but there are many dependencies on the amount of customisations to a standard product and the number of systems to be integrated.
If you need it prefix than you might like this
for ((i=7;i<=12;i++)); do echo `printf "%2.0d\n" $i |sed "s/ /0/"`;done
that will yield
07
08
09
10
11
12
Firstly It tries insert. If there is a conflict on url
column then it updates content and last_analyzed fields. If updates are rare this might be better option.
INSERT INTO URLs (url, content, last_analyzed)
VALUES
(
%(url)s,
%(content)s,
NOW()
)
ON CONFLICT (url)
DO
UPDATE
SET content=%(content)s, last_analyzed = NOW();
There is a very simple solution: http_build_query()
. It takes your query parameters as an associative array:
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
will return
string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"
http_build_query()
handles all the necessary escaping for you (%5B
=> [
and %5D
=> ]
), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d
.
None of the highly upvoted answers worked for me. They threw various undefined errors and ended up calculating inf/nan for angles. I suspect perhaps the behavior of LatLngBounds has changed over time. In any case, I found this code to work for my needs, perhaps it can help someone:
function latRad(lat) {
var sin = Math.sin(lat * Math.PI / 180);
var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
}
function getZoom(lat_a, lng_a, lat_b, lng_b) {
let latDif = Math.abs(latRad(lat_a) - latRad(lat_b))
let lngDif = Math.abs(lng_a - lng_b)
let latFrac = latDif / Math.PI
let lngFrac = lngDif / 360
let lngZoom = Math.log(1/latFrac) / Math.log(2)
let latZoom = Math.log(1/lngFrac) / Math.log(2)
return Math.min(lngZoom, latZoom)
}
The short answer is that the syntax is this.dataset.whatever
.
Your code should look like this:
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset.uid, this.dataset.name, this.dataset.value)">
Another important note: Javascript will always strip out hyphens and make the data attributes camelCase, regardless of whatever capitalization you use. data-camelCase
will become this.dataset.camelcase
and data-Camel-case
will become this.dataset.camelCase
.
jQuery (after v1.5 and later) always uses lowercase, regardless of your capitalization.
So when referencing your data attributes using this method, remember the camelCase:
<div data-this-is-wild="yes, it's true"
onclick="fun(this.dataset.thisIsWild)">
Also, you don't need to use commas to separate attributes.
You need to make two case
labels.
Control will fall through from the first label to the second, so they'll both execute the same code.
Inside template this working finely.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<input ng-model="name" value="0">
<p>My first expression: {{ (name-0) + 5 }}</p>
</div>
</body>
</html>
Binary(16) would be fine, better than use of varchar(32).
There is no way to use the ^
(Bitwise XOR) operator to calculate the power of a number.
Therefore, in order to calculate the power of a number we have two options, either we use a while loop or the pow() function.
1. Using a while loop.
#include <stdio.h>
int main() {
int base, expo;
long long result = 1;
printf("Enter a base no.: ");
scanf("%d", &base);
printf("Enter an exponent: ");
scanf("%d", &expo);
while (expo != 0) {
result *= base;
--expo;
}
printf("Answer = %lld", result);
return 0;
}
2. Using the pow()
function
#include <math.h>
#include <stdio.h>
int main() {
double base, exp, result;
printf("Enter a base number: ");
scanf("%lf", &base);
printf("Enter an exponent: ");
scanf("%lf", &exp);
// calculate the power of our input numbers
result = pow(base, exp);
printf("%.1lf^%.1lf = %.2lf", base, exp, result);
return 0;
}
Simply it's work fine, in HTML:
<button type="button" id="btn_CommitAll"class="btn_CommitAll">save</button>
In JQuery side put this function for disable button:
function disableButton() {
$('.btn_CommitAll').prop("disabled", true);
}
For enable button:
function enableButton() {
$('.btn_CommitAll').prop("disabled", false);
}
That's all.
There is different ways to make dropdown menu using css. Here is simple code.
HTML Code
<label class="dropdown">
<div class="dd-button">
Dropdown
</div>
<input type="checkbox" class="dd-input" id="test">
<ul class="dd-menu">
<li>Dropdown 1</li>
<li>Dropdown 2</li>
</ul>
</label>
CSS Code
body {
color: #000000;
font-family: Sans-Serif;
padding: 30px;
background-color: #f6f6f6;
}
a {
text-decoration: none;
color: #000000;
}
a:hover {
color: #222222
}
/* Dropdown */
.dropdown {
display: inline-block;
position: relative;
}
.dd-button {
display: inline-block;
border: 1px solid gray;
border-radius: 4px;
padding: 10px 30px 10px 20px;
background-color: #ffffff;
cursor: pointer;
white-space: nowrap;
}
.dd-button:after {
content: '';
position: absolute;
top: 50%;
right: 15px;
transform: translateY(-50%);
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid black;
}
.dd-button:hover {
background-color: #eeeeee;
}
.dd-input {
display: none;
}
.dd-menu {
position: absolute;
top: 100%;
border: 1px solid #ccc;
border-radius: 4px;
padding: 0;
margin: 2px 0 0 0;
box-shadow: 0 0 6px 0 rgba(0,0,0,0.1);
background-color: #ffffff;
list-style-type: none;
}
.dd-input + .dd-menu {
display: none;
}
.dd-input:checked + .dd-menu {
display: block;
}
.dd-menu li {
padding: 10px 20px;
cursor: pointer;
white-space: nowrap;
}
.dd-menu li:hover {
background-color: #f6f6f6;
}
.dd-menu li a {
display: block;
margin: -10px -20px;
padding: 10px 20px;
}
.dd-menu li.divider{
padding: 0;
border-bottom: 1px solid #cccccc;
}
More css code example