Try the below code-
mSQLiteDatabase = getWritableDatabase();//To delete , database should be writable.
int rowDeleted = mSQLiteDatabase.delete(TABLE_NAME,id + " =?",
new String[] {String.valueOf(id)});
mSQLiteDatabase.close();//This is very important once database operation is done.
if(rowDeleted != 0){
//delete success.
} else {
//delete failed.
}
hi how to delete from datagridview
1.make query delete by id
2.type
tabletableadaptor.delete
query(datagridwiewX1.selectedrows[0].cell[0].value.tostring);
If you are using "table as", then specify it to delete.
In the example i delete all table_1 rows which are do not exists in table_2.
DELETE t1 FROM `table_1` t1 LEFT JOIN `table_2` t2 ON t1.`id` = t2.`id` WHERE t2.`id` IS NULL
You must add an id that auto-increment for each row, after that you can delet the row by its id. so your table will have an unique id for each row and the id_user, id_product ecc...
import numpy as np
arr = np.array([[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 0.53172222],[ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]])
print(arr[np.where(arr != 0.)])
If you are using MySql Wamp. This code work.
string con="SERVER=localhost; user id=root; password=; database=dbname";
public void delete()
{
try
{
MySqlConnection connect = new MySqlConnection(con);
MySqlDataAdapter da = new MySqlDataAdapter();
connect.Open();
da.DeleteCommand = new MySqlCommand("DELETE FROM table WHERE ID='" + ID.Text + "'", connect);
da.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("Successfully Deleted");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
Here's a one-liner using LINQ and avoiding any run-time evaluation of select strings:
someDataTable.Rows.Cast<DataRow>().Where(
r => r.ItemArray[0] == someValue).ToList().ForEach(r => r.Delete());
I think, from your description, the following would suffice:
DELETE FROM guide_category
WHERE id_guide NOT IN (SELECT id_guide FROM guide)
I assume, that there are no referential integrity constraints on the tables involved, are there?
solution :
delete from emp where rowid in
(
select rid from
(
select rowid rid,
row_number() over(partition by empno order by empno) rn
from emp
)
where rn > 1
);
MySQL doesn't reduce the size of ibdata1. Ever. Even if you use optimize table
to free the space used from deleted records, it will reuse it later.
An alternative is to configure the server to use innodb_file_per_table
, but this will require a backup, drop database and restore. The positive side is that the .ibd file for the table is reduced after an optimize table
.
Issue the following command to reseed mytable to start at 1:
DBCC CHECKIDENT (mytable, RESEED, 0)
Read about it in the Books on Line (BOL, SQL help). Also be careful that you don't have records higher than the seed you are setting.
As an alternative answer, if you Visual Studio SSDT or possibly Red Gate Sql Compare, you could simply run a schema comparison, script it out, drop the old database (possibly make a backup first in case there would be a reason that you will need that data), and then create a new database with the script created by the comparison tool. While on a very small database this may be more work, on a very large database it will be much quicker to simply drop the database then to deal with the different triggers and constraints that may be on the database.
When you invoke destroy
or destroy_all
on an ActiveRecord
object, the ActiveRecord
'destruction' process is initiated, it analyzes the class you're deleting, it determines what it should do for dependencies, runs through validations, etc.
When you invoke delete
or delete_all
on an object, ActiveRecord
merely tries to run the DELETE FROM tablename WHERE conditions
query against the db, performing no other ActiveRecord
-level tasks.
DELETE FROM table WHERE date < '2011-09-21 08:21:22';
Where is the problem: It is forbidden to delete items from collection inside a foreach loop.
Solution: Either do it like Widor wrote, or use two loops. In the first pass over DataTable you only store (in a temporary list) the references to rows you want to delete. Then in the second pass over your temporary list you delete those rows.
I use linux and the answers did not help me.
I had to erase the folder ~/.config/smartgit
to make it work again. This is what the documentation is saying
Default Location of SmartGit's Settings Directory
Windows %APPDATA%\syntevo\SmartGit\ (%APPDATA% is the path defined in the environment variable APPDATA)
Mac OS ~/Library/Preferences/SmartGit/ (the Finder might not show the ~/Libraries directory by default, but you can invoke open ~/Library from a terminal)
Linux/Unix ${XDG_CONFIG_HOME}/smartgit/ (if the environment variable XDG_CONFIG_HOME is not defined, ~/.config is used instead)
The following worked for me:
import sys, glob
sys.path.append('/home/marc/python/importtest/modus')
fl = glob.glob('modus/*.py')
modulist = []
adapters=[]
for i in range(len(fl)):
fl[i] = fl[i].split('/')[1]
fl[i] = fl[i][0:(len(fl[i])-3)]
modulist.append(getattr(__import__(fl[i]),fl[i]))
adapters.append(modulist[i]())
It loads modules from the folder 'modus'. The modules have a single class with the same name as the module name. E.g. the file modus/modu1.py contains:
class modu1():
def __init__(self):
self.x=1
print self.x
The result is a list of dynamically loaded classes "adapters".
I would like to propose a generalization with awk.
When the file is made by blocks of a fixed size and the lines to delete are repeated for each block, awk can work fine in such a way
awk '{nl=((NR-1)%2000)+1; if ( (nl<714) || ((nl>1025)&&(nl<1029)) ) print $0}'
OriginFile.dat > MyOutputCuttedFile.dat
In this example the size for the block is 2000 and I want to print the lines [1..713] and [1026..1029].
NR
is the variable used by awk to store the current line number.%
gives the remainder (or modulus) of the division of two integers;nl=((NR-1)%BLOCKSIZE)+1
Here we write in the variable nl the line number inside the current block. (see below)||
and &&
are the logical operator OR and AND.print $0
writes the full lineWhy ((NR-1)%BLOCKSIZE)+1:
(NR-1) We need a shift of one because 1%3=1, 2%3=2, but 3%3=0.
+1 We add again 1 because we want to restore the desired order.
+-----+------+----------+------------+
| NR | NR%3 | (NR-1)%3 | (NR-1)%3+1 |
+-----+------+----------+------------+
| 1 | 1 | 0 | 1 |
| 2 | 2 | 1 | 2 |
| 3 | 0 | 2 | 3 |
| 4 | 1 | 0 | 1 |
+-----+------+----------+------------+
If you are running on a 64 bit system and trying to load a 32 bit dll you need to compile your application as 32 bit instead of any cpu. If you are not doing this it behaves exactly as you describe.
If that isn't the case use Dependency Walker to verify that the dll has its required dependencies.
Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.
bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]
You should override the layoutmanager of your recycleview for this. This way it will only disable scrolling, none of ther other functionalities. You will still be able to handle click or any other touch events. For example:-
public class CustomGridLayoutManager extends LinearLayoutManager {
private boolean isScrollEnabled = true;
public CustomGridLayoutManager(Context context) {
super(context);
}
public void setScrollEnabled(boolean flag) {
this.isScrollEnabled = flag;
}
@Override
public boolean canScrollVertically() {
//Similarly you can customize "canScrollHorizontally()" for managing horizontal scroll
return isScrollEnabled && super.canScrollVertically();
}
}
Here using "isScrollEnabled" flag you can enable/disable scrolling functionality of your recycle-view temporarily.
Simple override your existing implementation to disable scrolling and allow clicking.
linearLayoutManager = new LinearLayoutManager(context) {
@Override
public boolean canScrollVertically() {
return false;
}
};
Kotlin:
:LinearLayoutManager(this){ override fun canScrollVertically(): Boolean { return false } }
The simple way:
Use this to insert into mysql:
$msg = $_GET['msgtextarea']; //or POST and my msg field format: text
$msg = htmlspecialchars($msg, ENT_QUOTES);
And use this for output:
echo nl2br($br['msg']);
There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.
You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.
When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.
function createLineReader(fileName){
var EM = require("events").EventEmitter
var ev = new EM()
var stream = require("fs").createReadStream(fileName)
var remainder = null;
stream.on("data",function(data){
if(remainder != null){//append newly received data chunk
var tmp = new Buffer(remainder.length+data.length)
remainder.copy(tmp)
data.copy(tmp,remainder.length)
data = tmp;
}
var start = 0;
for(var i=0; i<data.length; i++){
if(data[i] == 10){ //\n new line
var line = data.slice(start,i)
ev.emit("line", line)
start = i+1;
}
}
if(start<data.length){
remainder = data.slice(start);
}else{
remainder = null;
}
})
stream.on("end",function(){
if(null!=remainder) ev.emit("line",remainder)
})
return ev
}
//---------main---------------
fileName = process.argv[2]
lineReader = createLineReader(fileName)
lineReader.on("line",function(line){
console.log(line.toString())
//console.log("++++++++++++++++++++")
})
If you're looking for a pure css option, try using the :focus pseudo class.
#style {
background-color: red;
}
#style:focus {
background-color:yellow;
}
Here you go:
public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
public static String ToBinary(Byte[] data)
{
return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}
// Use any sort of encoding you like.
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
This is special restriction added by developers of create-react-app. It is implemented in ModuleScopePlugin
to ensure files reside in src/
. That plugin ensures that relative imports from app's source directory don't reach outside of it.
You can disable this feature (one of the ways) by eject
operation of create-react-app project.
Most features and its updates are hidden into the internals of create-react-app system. If you make eject
you will no more have some features and its update. So if you are not ready to manage and configure application included to configure webpack and so on - do not do eject
operation.
Play by the existing rules (move to src). But now you can know how to remove restriction: do eject
and remove ModuleScopePlugin
from webpack configuration file.
Instead of eject
there are intermediate solutions, like
rewire which allows you to programmatically modify the webpack config without eject
. But removing the ModuleScopePlugin
plugin is not good - this loses some protection and does not adds some features available in src
.
The better way is to add fully working additional directories similar to src
. This can be done using react-app-rewire-alias
Do not import from public
folder - that will be duplicated in the build
folder and will be available by two different url (or with different ways to load), which ultimately worsen the package download size.
Importing from the src
folder is preferable and has advantages. Everything will be packed by webpack to the bundle with chunks optimal size and for best loading efficiency.
string str1, str2, str3;
cout << "These are the strings: " << endl;
cout << "str1: \"the dog jumped over the fence\"" << endl;
cout << "str2: \"the\"" << endl;
cout << "str3: \"that\"" << endl << endl;
From this, I see that you have not initialized str1, str2, or str3 to contain the values that you are printing. I might suggest doing so first:
string str1 = "the dog jumped over the fence",
str2 = "the",
str3 = "that";
cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;
I was also facing the same problem recently. after struggling a couple of hours,finally a solution came out by addition to
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
to your SVC markup file. e.g.
ServiceHost Language="C#" Debug="true" Service="QuiznetOnline.Web.UI.WebServices.LogService"
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
and now you can compile & run your application successfully.
This is the best you can do, as far as I know...
var keys = [];
for (var k in h)keys.push(k);
Use the below code. I hope it help for you.
NSString *needToChangeStr=@"BOOK";
NSString *display_string=[NSString stringWithFormat:@"This is %@",book];
NSMutableAttributedString *attri_str=[[NSMutableAttributedString alloc]initWithString:display_string];
int begin=[display_string length]-[needToChangeStr length];
int end=[needToChangeStr length];
[attri_str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30] range:NSMakeRange(begin, end)];
Might be cleaner to use PrintWriter
and its method println
.
Just make sure you close the writer when you're done
Long form:
get-content env:computername
Short form:
gc env:computername
This project should be helpful - maps touch events to click events in a way that allows jQuery UI to work on iPad and iPhone without any changes. Just add the JS to any existing project.
This is almost certainly much slower than any other version given here, but it was fun to write.
static bool ByteArrayEquals(byte[] a1, byte[] a2)
{
return a1.Zip(a2, (l, r) => l == r).All(x => x);
}
Here is some code using java 6 to get you started:
JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);
Edit: Since there has been a lot of confusion about put
vs add
here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put
method and in java 7 javax.json contains the add
method.
An example of this using the builder pattern in java 7 looks something like this:
JsonObject jo = Json.createObjectBuilder()
.add("employees", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Doe")))
.build();
That's a bad practice to use the ==
equality operator instead of ===
.
undefined === undefined // true
null == undefined // true
null === undefined // false
The object.x === undefined
should return true
if x
is unknown property.
In chapter Bad Parts of JavaScript: The Good Parts, Crockford writes the following:
If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.
In addition to undefined, JavaScript has a similar value called null. They are so similar that == thinks they are equal. That confuses some programmers into thinking that they are interchangeable, leading to code like
value = myObject[name]; if (value == null) { alert(name + ' not found.'); }
It is comparing the wrong value with the wrong operator. This code works because it contains two errors that cancel each other out. That is a crazy way to program. It is better written like this:
value = myObject[name]; if (value === undefined) { alert(name + ' not found.'); }
Here is Code for Smooth animation, might Be helpful for many developers.
I found this snippet of code from this tutorial.
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[animation setAutoreverses:YES];
[animation setFromValue:[NSNumber numberWithFloat:1.3f]];
[animation setToValue:[NSNumber numberWithFloat:1.f]];
[animation setDuration:2.f];
[animation setRemovedOnCompletion:NO];
[animation setFillMode:kCAFillModeForwards];
[[self.myView layer] addAnimation:animation forKey:@"scale"];/// add here any Controller that you want t put Smooth animation.
Specifying android:onClick
attribute results in Button
instance calling setOnClickListener
internally. Hence there is absolutely no difference.
To have clear understanding, let us see how XML onClick
attribute is handled by the framework.
When a layout file is inflated, all Views specified in it are instantiated. In this specific case, the Button
instance is created using public Button (Context context, AttributeSet attrs, int defStyle)
constructor. All of the attributes in the XML tag are read from the resource bundle and passed as AttributeSet
to the constructor.
Button
class is inherited from View
class which results in View
constructor being called, which takes care of setting the click call back handler via setOnClickListener
.
The onClick attribute defined in attrs.xml, is referred in View.java as R.styleable.View_onClick
.
Here is the code of View.java
that does most of the work for you by calling setOnClickListener
by itself.
case R.styleable.View_onClick:
if (context.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot "
+ "be used within a restricted context");
}
final String handlerName = a.getString(attr);
if (handlerName != null) {
setOnClickListener(new OnClickListener() {
private Method mHandler;
public void onClick(View v) {
if (mHandler == null) {
try {
mHandler = getContext().getClass().getMethod(handlerName,
View.class);
} catch (NoSuchMethodException e) {
int id = getId();
String idText = id == NO_ID ? "" : " with id '"
+ getContext().getResources().getResourceEntryName(
id) + "'";
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity "
+ getContext().getClass() + " for onClick handler"
+ " on view " + View.this.getClass() + idText, e);
}
}
try {
mHandler.invoke(getContext(), View.this);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not execute non "
+ "public method of the activity", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not execute "
+ "method of the activity", e);
}
}
});
}
break;
As you can see, setOnClickListener
is called to register the callback, as we do in our code. Only difference is it uses Java Reflection
to invoke the callback method defined in our Activity.
Here are the reason for issues mentioned in other answers:
Java Class getMethod
is used, only functions with public access specifier are searched for. Otherwise be ready to handle IllegalAccessException
exception.getContext().getClass().getMethod()
call restricts the method search to the current context, which is Activity in case of Fragment. Hence method is searched within Activity class and not Fragment class.Java Class getMethod
searches for method which accepts View.class
as parameter.Both answers are correct. If you user .TO -method then the semicolumn is OK - but not for the addrecipients-method. There you need to split, e.g. :
Dim Splitter() As String
Splitter = Split(AddrMail, ";")
For Each Dest In Splitter
.Recipients.Add (Trim(Dest))
Next
I know that I’m late to the party. After looking into wonderful answers provided here, I thought mine will add some value to this post. Although the posted answers are amazing and easy to understand however, all are calculating the height to the BST in linear time. I think this can be improved and Height can be retrieved in constant time, hence writing this answer – hope you will like it. Let’s start with the Node class:
public class Node
{
public Node(string key)
{
Key = key;
Height = 1;
}
public int Height { get; set; }
public string Key { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public override string ToString()
{
return $"{Key}";
}
}
BinarySearchTree class
So you might have guessed the trick here… Im keeping node instance variable Height to keep track of each node when added. Lets move to the BinarySearchTree class that allows us to add nodes into our BST:
public class BinarySearchTree
{
public Node RootNode { get; private set; }
public void Put(string key)
{
if (ContainsKey(key))
{
return;
}
RootNode = Put(RootNode, key);
}
private Node Put(Node node, string key)
{
if (node == null) return new Node(key);
if (node.Key.CompareTo(key) < 0)
{
node.Right = Put(node.Right, key);
}
else
{
node.Left = Put(node.Left, key);
}
// since each node has height property that is maintained through this Put method that creates the binary search tree.
// calculate the height of this node by getting the max height of its left or right subtree and adding 1 to it.
node.Height = Math.Max(GetHeight(node.Left), GetHeight(node.Right)) + 1;
return node;
}
private int GetHeight(Node node)
{
return node?.Height ?? 0;
}
public Node Get(Node node, string key)
{
if (node == null) return null;
if (node.Key == key) return node;
if (node.Key.CompareTo(key) < 0)
{
// node.Key = M, key = P which results in -1
return Get(node.Right, key);
}
return Get(node.Left, key);
}
public bool ContainsKey(string key)
{
Node node = Get(RootNode, key);
return node != null;
}
}
Once we have added the key, values in the BST, we can just call Height property on the RootNode object that will return us the Height of the RootNode tree in constant time. The trick is to keep the height updated when a new node is added into the tree. Hope this helps someone out there in the wild world of computer science enthusiast!
Unit test:
[TestCase("SEARCHEXAMPLE", 6)]
[TestCase("SEBAQRCHGEXAMPLE", 6)]
[TestCase("STUVWXYZEBAQRCHGEXAMPLE", 8)]
public void HeightTest(string data, int expectedHeight)
{
// Arrange.
var runner = GetRootNode(data);
// Assert.
Assert.AreEqual(expectedHeight, runner.RootNode.Height);
}
private BinarySearchTree GetRootNode(string data)
{
var runner = new BinarySearchTree();
foreach (char nextKey in data)
{
runner.Put(nextKey.ToString());
}
return runner;
}
Note: This idea of keeping the Height of tree maintained in every Put operation is inspired by the Size of BST method found in the 3rd chapter (page 399) of Algorithm (Fourth Edition) book.
JavaScript is case-sensitive. The b
in getElementbyId
should be capitalized.
var content = document.getElementById("edit").innerHTML;
Shorter version for those who like short code:
// usage: deleteOldFiles("./xml", "xml,xsl", 24 * 3600)
function deleteOldFiles($dir, $patterns = "*", int $timeout = 3600) {
// $dir is directory, $patterns is file types e.g. "txt,xls", $timeout is max age
foreach (glob($dir."/*"."{{$patterns}}",GLOB_BRACE) as $f) {
if (is_writable($f) && filemtime($f) < (time() - $timeout))
unlink($f);
}
}
Install jQuery using NPM Jquery NPM
npm install jquery
Install the jQuery declaration file
npm install -D @types/jquery
Import jQuery inside .ts
import * as $ from 'jquery';
call inside class
export class JqueryComponent implements OnInit {
constructor() {
}
ngOnInit() {
$(window).click(function () {
alert('ok');
});
}
}
I had a similar issue with a ~400MB file. Setting low_memory=False
did the trick for me. Do the simple things first,I would check that your dataframe isn't bigger than your system memory, reboot, clear the RAM before proceeding. If you're still running into errors, its worth making sure your .csv
file is ok, take a quick look in Excel and make sure there's no obvious corruption. Broken original data can wreak havoc...
The best way to apply a class is to use ng-class.It can be used to apply classes based on some condition.
<div ng-repeat="product in products">
<div ng-class="getRowClass($index)">
<div class="col-sm-4" >
<!-- your code -->
</div>
</div>
and then in your controller
$scope.getRowClass = function(index){
if(index%3 == 0){
return "row";
}
}
There is no way to know unless the particular company reveals the info. The best you can do is find a few companies that are sharing and then extrapolate based on app ranking (which is available publicly). The best you'll get is a ball park estimate.
To get the first key name in the object you can use:
var obj = { first: 'someVal' };
Object.keys(obj)[0]; //returns 'first'
Returns a string, so you cant access nested objects if there were, like:
var obj = { first: { someVal : { id : 1} };
Here with that solution you can't access id.
The best solution if you want to get the actual object is using lodash like:
obj[_.first(_.keys(obj))].id
To return the value of the first key, (if you don't know exactly the first key name):
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'
if you know the key name just use:
obj.first
or
obj['first']
If we think of getting name of items from any specific category then we can do that by specifying the class name of that category using css selector:
import requests ; from bs4 import BeautifulSoup
soup = BeautifulSoup(requests.get('https://www.flipkart.com/').text, "lxml")
for link in soup.select('div._2kSfQ4'):
print(link.text)
This is the partial search results:
Puma, USPA, Adidas & moreUp to 70% OffMen's Shoes
Shirts, T-Shirts...Under ?599For Men
Nike, UCB, Adidas & moreUnder ?999Men's Sandals, Slippers
Philips & moreStarting ?99LED Bulbs & Emergency Lights
Run 'npm install' it will install all necessary pkg .
I've experienced a similar problem, however this appears to a generic warning, and may not in fact be related to the line-end character. In my case it was giving this error because the file I was using contained Cyrillic characters, once I replaced them with latin characters the error disappeared.
You can use Jackson API as well for this :
final String json = "....your json...";
final ObjectMapper mapper = new ObjectMapper();
final MapType type = mapper.getTypeFactory().constructMapType(
Map.class, String.class, Object.class);
final Map<String, Object> data = mapper.readValue(json, type);
If you're using LESS or SCSS/SASS and you're using a LESS/SCSS version of Bootstrap, you can use variables as well, provided you have access to them. A LESS translation of @full-decent's answer would be as follows:
@media(max-width: @screen-xs-max){}
@media(min-width: @screen-sm-min){} /* deprecated: @screen-tablet, or @screen-sm */
@media(min-width: @screen-md-min){} /* deprecated: @screen-desktop, or @screen-md */
@media(min-width: @screen-lg-min){} /* deprecated: @screen-lg-desktop, or @screen-lg */
There are also variables for @screen-sm-max
and @screen-md-max
, which are 1 pixel less than @screen-md-min
and @screen-lg-min
, respectively, typically for use with @media(max-width)
.
EDIT: If you're using SCSS/SASS, variables start with a $
instead of a @
, so it'd be $screen-xs-max
etc.
I will show you some examples:
const string &dontDoThis(const string &s)
{
string local = s;
return local;
}
You can't return local
by reference, because local
is destroyed at the end of the body of dontDoThis
.
const string &shorterString(const string &s1, const string &s2)
{
return (s1.size() < s2.size()) ? s1 : s2;
}
Here, you can return by reference both s1
and s2
because they were defined before shorterString
was called.
char &get_val(string &str, string::size_type ix)
{
return str[ix];
}
usage code as below:
string s("123456");
cout << s << endl;
char &ch = get_val(s, 0);
ch = 'A';
cout << s << endl; // A23456
get_val
can return elements of s
by reference because s
still exists after the call.
class Student
{
public:
string m_name;
int age;
string &getName();
};
string &Student::getName()
{
// you can return by reference
return m_name;
}
string& Test(Student &student)
{
// we can return `m_name` by reference here because `student` still exists after the call
return stu.m_name;
}
usage example:
Student student;
student.m_name = 'jack';
string name = student.getName();
// or
string name2 = Test(student);
class String
{
private:
char *str_;
public:
String &operator=(const String &str);
};
String &String::operator=(const String &str)
{
if (this == &str)
{
return *this;
}
delete [] str_;
int length = strlen(str.str_);
str_ = new char[length + 1];
strcpy(str_, str.str_);
return *this;
}
You could then use the operator=
above like this:
String a;
String b;
String c = b = a;
A UNIX guy probably told you that. :)
You can use makefiles in VS, but when you do it bypasses all the built-in functionality in MSVC's IDE. Makefiles are basically the reinterpret_cast of the builder. IMO the simplest thing is just to use Solutions.
replace p.setval(0);
with the following.
const unsigned int param = 0;
p.setval(param);
That way it knows for sure which type the constant 0 is.
Add this style to your span:
position:relative;
top: 10px;
As mentioned by top scoring answer by Win you may need to install Microsoft.EntityFrameworkCore.SqlServer NuGet Package, but please note that this question is using asp.net core mvc. In the latest ASP.NET Core 2.1, MS have included what is called a metapackage called Microsoft.AspNetCore.App
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/metapackage-app?view=aspnetcore-2.2
You can see the reference to it if you right-click the ASP.NET Core MVC project in the solution explorer and select Edit Project File
You should see this metapackage if ASP.NET core webapps the using statement
<PackageReference Include="Microsoft.AspNetCore.App" />
Microsoft.EntityFrameworkCore.SqlServer is included in this metapackage. So in your Startup.cs you may only need to add:
using Microsoft.EntityFrameworkCore;
why dont you add a "source" column to each of the queries with a static value like
select 'source 1' as Source, column1, column2...
from table1
UNION ALL
select 'source 2' as Source, column1, column2...
from table2
In my case, I use Symfony2.3.x and the minimum-stability parameter is by default "stable" (which is good). I wanted to import a repo not in packagist but had the same issue "Your requirements could not be resolved to an installable set of packages.". It appeared that the composer.json in the repo I tried to import use a minimum-stability "dev".
So to resolve this issue, don't forget to verify the minimum-stability
. I solved it by requiring a dev-master
version instead of master
as stated in this post.
I received this error when I copied a class object using JSON.parse and JSON.stringify() which removed the function like:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Method
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log('area of square: ', square.calcArea());
const squareCopy = JSON.parse(JSON.stringify(square));
// Will throw an exception since calcArea() is no longer function
console.log('area of square copy: ', squareCopy.calcArea());
You can use the method Path.GetFileName(yourFileName);
(MSDN) to just get the name of the file.
I won't try to give a complete answer here. My recommendation would be to focus on understanding what each one of them does and then it should be cleare to see that their effects are completely different and why sometimes they are used together.
static
is for members of a class (attributes and methods) and it has to be understood in contrast to instance (non static) members. I'd recommend reading "Understanding Instance and Class Members" in The Java Tutorials. I can also be used in static
blocks but I would not worry about it for a start.
final
has different meanings according if its applied to variables, methods, classes or some other cases. Here I like Wikipedia explanations better.
The ggpubr package offers a shortcut that does the right thing by default (right align text, middle align text box to tick):
library(ggplot2)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
q <- qplot(cut, carat, data = diamonds, geom = "boxplot")
q + ggpubr::rotate_x_text()
Created on 2018-11-06 by the reprex package (v0.2.1)
Found with a GitHub search for the relevant argument names: https://github.com/search?l=R&q=element_text+angle+90+vjust+org%3Acran&type=Code
I was having trouble with mobile touchscreen button styling. This will fix your hover-stick / active button problems.
body, html {
width: 600px;
}
p {
font-size: 20px;
}
button {
border: none;
width: 200px;
height: 60px;
border-radius: 30px;
background: #00aeff;
font-size: 20px;
}
button:active {
background: black;
color: white;
}
.delayed {
transition: all 0.2s;
transition-delay: 300ms;
}
.delayed:active {
transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>
<button>Normal button</button>
<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>
<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures. With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely. This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>
<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
Using the ${#VAR}
syntax will calculate the number of characters in a variable.
https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion
To both check if it exists and create if it doesn't, including intermediaries:
QDir dir("path/to/dir");
if (!dir.exists())
dir.mkpath(".");
Before killing sessions, if possible do
ALTER SYSTEM ENABLE RESTRICTED SESSION;
to stop new sessions from connecting.
It also worth noting that Concat works in constant time and in constant memory. For example, the following code
long boundary = 60000000;
for (long i = 0; i < boundary; i++)
{
list1.Add(i);
list2.Add(i);
}
var listConcat = list1.Concat(list2);
var list = listConcat.ToList();
list1.AddRange(list2);
gives the following timing/memory metrics:
After lists filled mem used: 1048730 KB
concat two enumerables: 00:00:00.0023309 mem used: 1048730 KB
convert concat to list: 00:00:03.7430633 mem used: 2097307 KB
list1.AddRange(list2) : 00:00:00.8439870 mem used: 2621595 KB
Read open as
open for inheritance in other modules
I repeat open for inheritance in other modules. So an open class is open for subclassing in other modules that include the defining module. Open vars and functions are open for overriding in other modules. Its the least restrictive access level. It is as good as public access except that something that is public is closed for inheritance in other modules.
From Apple Docs:
Open access applies only to classes and class members, and it differs from public access as follows:
Classes with public access, or any more restrictive access level, can be subclassed only within the module where they’re defined.
Class members with public access, or any more restrictive access level, can be overridden by subclasses only within the module where they’re defined.
Open classes can be subclassed within the module where they’re defined, and within any module that imports the module where they’re defined.
Open class members can be overridden by subclasses within the module where they’re defined, and within any module that imports the module where they’re defined.
Yes, it is very Simple. Just Put your Code Inside this:
<androidx.core.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
//YOUR CODE
</androidx.core.widget.NestedScrollView>
I know that it may be not directly answer to your question, because you said that null values have to be supported.
But I just want to note that supporting nulls in compareTo is not in line with compareTo contract described in official javadocs for Comparable:
Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
So I would either throw NullPointerException explicitly or just let it be thrown first time when null argument is being dereferenced.
How about:
df['D'] = df['B'].values
this should work
ListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "long clicked, "+"pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
also don't forget to in your xml android:longClickable="true"
or if you have a custom view add this to your custom view class youCustomView.setLongClickable(true);
Here is a use case for AtomicReference:
Consider this class that acts as a number range, and uses individual AtmomicInteger variables to maintain lower and upper number bounds.
public class NumberRange {
// INVARIANT: lower <= upper
private final AtomicInteger lower = new AtomicInteger(0);
private final AtomicInteger upper = new AtomicInteger(0);
public void setLower(int i) {
// Warning -- unsafe check-then-act
if (i > upper.get())
throw new IllegalArgumentException(
"can't set lower to " + i + " > upper");
lower.set(i);
}
public void setUpper(int i) {
// Warning -- unsafe check-then-act
if (i < lower.get())
throw new IllegalArgumentException(
"can't set upper to " + i + " < lower");
upper.set(i);
}
public boolean isInRange(int i) {
return (i >= lower.get() && i <= upper.get());
}
}
Both setLower and setUpper are check-then-act sequences, but they do not use sufficient locking to make them atomic. If the number range holds (0, 10), and one thread calls setLower(5) while another thread calls setUpper(4), with some unlucky timing both will pass the checks in the setters and both modifications will be applied. The result is that the range now holds (5, 4)an invalid state. So while the underlying AtomicIntegers are thread-safe, the composite class is not. This can be fixed by using a AtomicReference instead of using individual AtomicIntegers for upper and lower bounds.
public class CasNumberRange {
// Immutable
private static class IntPair {
final int lower; // Invariant: lower <= upper
final int upper;
private IntPair(int lower, int upper) {
this.lower = lower;
this.upper = upper;
}
}
private final AtomicReference<IntPair> values =
new AtomicReference<IntPair>(new IntPair(0, 0));
public int getLower() {
return values.get().lower;
}
public void setLower(int lower) {
while (true) {
IntPair oldv = values.get();
if (lower > oldv.upper)
throw new IllegalArgumentException(
"Can't set lower to " + lower + " > upper");
IntPair newv = new IntPair(lower, oldv.upper);
if (values.compareAndSet(oldv, newv))
return;
}
}
public int getUpper() {
return values.get().upper;
}
public void setUpper(int upper) {
while (true) {
IntPair oldv = values.get();
if (upper < oldv.lower)
throw new IllegalArgumentException(
"Can't set upper to " + upper + " < lower");
IntPair newv = new IntPair(oldv.lower, upper);
if (values.compareAndSet(oldv, newv))
return;
}
}
}
System.arraycopy is my answer. Please let me know is there any better ways. Thx
private static long[] r1 = new long[64];
private static long[][] r2 = new long[64][64];
/**Proved:
* {@link Arrays#fill(long[], long[])} makes r2 has 64 references to r1 - not the answer;
* {@link Arrays#fill(long[], long)} sometimes slower than deep 2 looping.<br/>
*/
private static void testFillPerformance() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(new Date()));
Arrays.fill(r1, 0l);
long stamp0 = System.nanoTime();
// Arrays.fill(r2, 0l); -- exception
long stamp1 = System.nanoTime();
// System.out.println(String.format("Arrays.fill takes %s nano-seconds.", stamp1 - stamp0));
stamp0 = System.nanoTime();
for (int i = 0; i < 64; i++) {
for (int j = 0; j < 64; j++)
r2[i][j] = 0l;
}
stamp1 = System.nanoTime();
System.out.println(String.format("Arrays' 2-looping takes %s nano-seconds.", stamp1 - stamp0));
stamp0 = System.nanoTime();
for (int i = 0; i < 64; i++) {
System.arraycopy(r1, 0, r2[i], 0, 64);
}
stamp1 = System.nanoTime();
System.out.println(String.format("System.arraycopy looping takes %s nano-seconds.", stamp1 - stamp0));
stamp0 = System.nanoTime();
Arrays.fill(r2, r1);
stamp1 = System.nanoTime();
System.out.println(String.format("One round Arrays.fill takes %s nano-seconds.", stamp1 - stamp0));
stamp0 = System.nanoTime();
for (int i = 0; i < 64; i++)
Arrays.fill(r2[i], 0l);
stamp1 = System.nanoTime();
System.out.println(String.format("Two rounds Arrays.fill takes %s nano-seconds.", stamp1 - stamp0));
}
12:33:18
Arrays' 2-looping takes 133536 nano-seconds.
System.arraycopy looping takes 22070 nano-seconds.
One round Arrays.fill takes 9777 nano-seconds.
Two rounds Arrays.fill takes 93028 nano-seconds.
12:33:38
Arrays' 2-looping takes 133816 nano-seconds.
System.arraycopy looping takes 22070 nano-seconds.
One round Arrays.fill takes 17042 nano-seconds.
Two rounds Arrays.fill takes 95263 nano-seconds.
12:33:51
Arrays' 2-looping takes 199187 nano-seconds.
System.arraycopy looping takes 44140 nano-seconds.
One round Arrays.fill takes 19555 nano-seconds.
Two rounds Arrays.fill takes 449219 nano-seconds.
12:34:16
Arrays' 2-looping takes 199467 nano-seconds.
System.arraycopy looping takes 42464 nano-seconds.
One round Arrays.fill takes 17600 nano-seconds.
Two rounds Arrays.fill takes 170971 nano-seconds.
12:34:26
Arrays' 2-looping takes 198907 nano-seconds.
System.arraycopy looping takes 24584 nano-seconds.
One round Arrays.fill takes 10616 nano-seconds.
Two rounds Arrays.fill takes 94426 nano-seconds.
If you want to get all Employee name in mysql which having at least one uppercase letter than apply this query.
SELECT * FROM registration WHERE `name` REGEXP BINARY '[A-Z]';
You can easily add Css class, placeholder , etc. as shown below:
@Html.TextBoxFor(m => m.Name, new { @class = "form-control", placeholder="Name" })
Hope this helps
I want to change the width and height of a div. data attributes did not change it. Instead I use:
var size = $("#theme_photo_size").val().split("x");
$("#imageupload_img").width(size[0]);
$("#imageupload_img").attr("data-width", size[0]);
$("#imageupload_img").height(size[1]);
$("#imageupload_img").attr("data-height", size[1]);
be careful:
$("#imageupload_img").data("height", size[1]); //did not work
did not set it
$("#imageupload_img").attr("data-height", size[1]); // yes it worked!
this has set it.
1) The circles are Entities/POJOs/Beans
2) deg is an abbreviation for degree as in graphs (number of edges)
PK=Primary key, FK=Foreign key
Note the contradiction between the degree and the name of the side. Many corresponds to degree=1 while One corresponds to degree >1.
DataFrame.reset_index
is what you're looking for. If you don't want it saved as a column, then do:
df = df.reset_index(drop=True)
If you don't want to reassign:
df.reset_index(drop=True, inplace=True)
regular view----->short name for a query,no additional space is used here
Materialised view---->similar to creating table whose data will refresh periodically based on data query used for creating the view
You need to add -L/opt/lib
to tell ld
to look there for shared objects.
This is the JSON String we want to decode :
{
"stats": {
"sdr": "aa:bb:cc:dd:ee:ff",
"rcv": "aa:bb:cc:dd:ee:ff",
"time": "UTC in millis",
"type": 1,
"subt": 1,
"argv": [
{"1": 2},
{"2": 3}
]}
}
I store this string under the variable name "sJSON" Now, this is how to decode it :)
// Creating a JSONObject from a String
JSONObject nodeRoot = new JSONObject(sJSON);
// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("stats");
// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("sdr");
I solved that problem.
I was implementing an OSI Layer (slider window, Level 2) for a network simulation in C++ (Eclipse Juno). I had frames (template <class T>
) and its states (state pattern, forward declaration).
The solution is as follows:
In the *.cpp
file, you must include the Header file that you forward, i.e.
ifndef STATE_H_
#define STATE_H_
#include <stdlib.h>
#include "Frame.h"
template <class T>
class LinkFrame;
using namespace std;
template <class T>
class State {
protected:
LinkFrame<int> *myFrame;
}
Its cpp:
#include "State.h"
#include "Frame.h"
#include "LinkFrame.h"
template <class T>
bool State<T>::replace(Frame<T> *f){
And... another class.
Best way of doing it
Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.
Sub selectVisibleRange()
Dim DbExtract, DuplicateRecords As Worksheet
Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")
DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
DuplicateRecords.Cells(1, 1).PasteSpecial
End Sub
Well...I tinkered around (using notepadd++) and this is the solution I found
\n\s
\n for end of line (where you start matching) -- the caret would not be of help in my case as the beginning of the row is a string \s takes any space till the next string
hope it helps
I wanted a solution for Gnu sort on Windows, but none of the above solutions worked for me on the command line.
Using Lloyd's clue, the following batch file (.bat) worked for me.
Type the tab character within the double quotes.
C:\>cat foo.bat
sort -k3 -t" " tabfile.txt
Object does not have forEach
, it belongs to Array
prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};
, Object.keys(v)
gives you an array of the keys so you get ["cat","dog","bird"]
ListView listView = getListView();
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
view.setOnTouchListener(new OnTouchListener() {
private float mInitialX;
private float mInitialY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialX = event.getX();
mInitialY = event.getY();
return true;
case MotionEvent.ACTION_MOVE:
final float x = event.getX();
final float y = event.getY();
final float yDiff = y - mInitialY;
if (yDiff > 0.0) {
Log.d(tag, "SCROLL DOWN");
scrollDown = true;
break;
} else if (yDiff < 0.0) {
Log.d(tag, "SCROLL up");
scrollDown = true;
break;
}
break;
}
return false;
}
});
$ foo="/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
1
$ foo="[email protected]:/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
0
The graphicx
package provides the command \resizebox{width}{height}{object}
:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}
Here's a very simple free open-source CsvExport class for C#. There's an ASP.NET MVC example at the bottom.
https://github.com/jitbit/CsvExport
It takes care about line-breaks, commas, escaping quotes, MS Excel compatibilty... Just add one short .cs
file to your project and you're good to go.
(disclaimer: I'm one of the contributors)
Your modifications are in a different branch than the original branch, which simplifies stuff because you get updates in one branch, and your work is in another branch.
Assuming the original branch is named master
, which the case in 99% of git repos, you have to fetch the state of origin, and merge origin/master
updates into your local master
:
git fetch origin
git checkout master
git merge origin/master
To switch to your branch, just do
git checkout branch1
Note that you can still do:
s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '\0';
If min value in array, you can try like:
>>> mydict = {"a": -1.5, "b": -1000.44, "c": -3}
>>> min(mydict.values())
-1000.44
You can use the reset()
method:
$('#myform')[0].reset();
or without jQuery:
document.getElementById('myform').reset();
where myform
is the id of the form containing the elements you want to be cleared.
You could also use the :input
selector if the fields are not inside a form:
$(':input').val('');
Here is what the standard C99 (ISO-IEC 9899 6.2.5 §10) or C++2003 (ISO-IEC 14882-2003 3.1.9 §8) standards say:
There are three floating point types:
float
,double
, andlong double
. The typedouble
provides at least as much precision asfloat
, and the typelong double
provides at least as much precision asdouble
. The set of values of the typefloat
is a subset of the set of values of the typedouble
; the set of values of the typedouble
is a subset of the set of values of the typelong double
.
The C++ standard adds:
The value representation of floating-point types is implementation-defined.
I would suggest having a look at the excellent What Every Computer Scientist Should Know About Floating-Point Arithmetic that covers the IEEE floating-point standard in depth. You'll learn about the representation details and you'll realize there is a tradeoff between magnitude and precision. The precision of the floating point representation increases as the magnitude decreases, hence floating point numbers between -1 and 1 are those with the most precision.
Yes you can - first capture the event using onmouseover
, then set the class name using
Element.className
.
If you like to add or remove classes - use the more convenient Element.classList
method.
.active {
background: red;
}
_x000D_
<div onmouseover=className="active">
Hover this!
</div>
_x000D_
The .map
files are for js
and css
(and now ts
too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.
Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.
So, to answer you questions in order:
I hope this makes sense.
What worked for me is moving the following code from page_load to page_prerender:
lstMain.DataBind();
Image img = (Image)lstMain.Items[0].FindControl("imgMain");
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
cs.RegisterStartupScript(cstype, csname1, "<script language=javascript> p=\"" + img.ClientID + "\"</script>");
}
This function will convert in both directions: 12 to 24 hour or 24 to 12 hour
function toggle24hr(time, onoff){
if(onoff==undefined) onoff = isNaN(time.replace(':',''))//auto-detect format
var pm = time.toString().toLowerCase().indexOf('pm')>-1 //check if 'pm' exists in the time string
time = time.toString().toLowerCase().replace(/[ap]m/,'').split(':') //convert time to an array of numbers
time[0] = Number(time[0])
if(onoff){//convert to 24 hour:
if((pm && time[0]!=12)) time[0] += 12
else if(!pm && time[0]==12) time[0] = '00' //handle midnight
if(String(time[0]).length==1) time[0] = '0'+time[0] //add leading zeros if needed
}else{ //convert to 12 hour:
pm = time[0]>=12
if(!time[0]) time[0]=12 //handle midnight
else if(pm && time[0]!=12) time[0] -= 12
}
return onoff ? time.join(':') : time.join(':')+(pm ? 'pm' : 'am')
}
Here's some examples:
//convert to 24 hour:
toggle24hr('12:00am') //returns 00:00
toggle24hr('2:00pm') //returns 14:00
toggle24hr('8:00am') //returns 08:00
toggle24hr('12:00pm') //returns 12:00
//convert to 12 hour:
toggle24hr('14:00') //returns 2:00pm
toggle24hr('08:00') //returns 8:00am
toggle24hr('12:00') //returns 12:00pm
toggle24hr('00:00') //returns 12:00am
//you can also force a specific format like this:
toggle24hr('14:00',1) //returns 14:00
toggle24hr('14:00',0) //returns 2:00pm
you can also check this link
SELECT * FROM master_question
WHERE 1 ORDER BY question_id
ASC LIMIT 20
Try this
dirname(dirname( __ FILE__))
Edit: removed "./" because it isn't correct syntax. Without it, it works perfectly.
Rather than using a DisplayFilter you could use a very simple CaptureFilter like
port 53
See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.
This is how I would do it.
my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54',
'0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54',
'0.55', '0.55', '0.54']
print type(my_list[0]) # prints <type 'str'>
my_list = [float(i) for i in my_list]
print type(my_list[0]) # prints <type 'float'>
To solve the above in O(n) time complexity (without sorting).
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var obj={};
for(var i=0;i<arr.length;i++){
if(!obj[arr[i]]){
obj[arr[i]]=1;
} else {
obj[arr[i]]=obj[arr[i]]+1;
}
}
var result=[]
for(var key in obj){
if(obj[key]>1){
result.push(Number(key)) // change this to result.push(key) to find duplicate strings in an array
}
}
console.log(result)
if file is committed and pushed to github then you should run
git rm --fileName
git ls-files
to make sure that the file is removed or untracked
git commit -m "UntrackChanges"
git push
I would suggest you just evenly space them as shown in this answer here
.navbar ul {
list-style-type: none;
padding: 0;
display: flex;
flex-direction: row;
justify-content: space-around;
flex-wrap: nowrap; /* assumes you only want one row */
}
I encountered this problem in Laravel 5.8, what I did was to do composer require
for each library and all where installed correctly.
Like so:
instead of adding it to the composer.json file or specifying a version:
composer require msurguy/honeypot: dev-master
I instead did without specifying any version:
composer require msurguy/honeypot
I hope it helps, thanks
Not perfect but close:
newcol<-sapply(rownames(t), function(rn){z[match(rn, rownames(z)), 5]})
cbind(data.frame(t), newcol)
You'll need to use the HTML()
or display()
functions from IPython's display module:
from IPython.display import display, HTML
# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
display(HTML(df2.to_html()))
Note that if you just print df1.to_html()
you'll get the raw, unrendered HTML.
You can also import from IPython.core.display
with the same effect
SELECT name
FROM sys.objects
WHERE type = 'P'
AND (DATEDIFF(D,modify_date, GETDATE()) < 7
OR DATEDIFF(D,create_date, GETDATE()) < 7)
$users = Users::get();
$subset = $users->map(function ($user) {
return array_only(user, ['id', 'name', 'email']);
});
When I was trying to rewrite my example (from tutorialspoint) to use annotations, I got the same exception. This helped me (addAnnotatedClass()):
Configuration cfg=new Configuration();
cfg.addAnnotatedClass(com.tutorialspoint.hibernate.entity.Employee.class);
cfg.configure();
You have to change the format of the date string you are supplying in order to be able to insert it using the STRFTIME function. Reason being, there is no option for a month abbreviation:
%d day of month: 00
%f fractional seconds: SS.SSS
%H hour: 00-24
%j day of year: 001-366
%J Julian day number
%m month: 01-12
%M minute: 00-59
%s seconds since 1970-01-01
%S seconds: 00-59
%w day of week 0-6 with sunday==0
%W week of year: 00-53
%Y year: 0000-9999
%% %
The alternative is to format the date/time into an already accepted format:
Reference: SQLite Date & Time functions
Alternativly if your using bootstrap then you can just add align-middle
to vertical align the element.
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">Continue
<i class="icon-ok align-middle" style="font-size:40px;"></i>
</button>
In Visual Studio 2017, unchecked the ContextSwitchDeadlock option by:
Debug > Windows > Exception Settings
In Exception Setting Windows: Uncheck the ContextSwitchDeadlock option
You have to loop over the input array and add rules for each input as described here: Loop Over Rules
Here is a some code for ya:
$input = Request::all();
$rules = [];
foreach($input['name'] as $key => $val)
{
$rules['name.'.$key] = 'required|distinct|min:3';
}
$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';
$validator = Validator::make($input, $rules);
//Now check validation:
if ($validator->fails())
{
/* do something */
}
from subprocess import call
def cp_dir(source, target):
call(['cp', '-a', source, target]) # Linux
cp_dir('/a/b/c/', '/x/y/z/')
It works for me. Basically, it executes shell command cp.
// I'd modify this slightly to be more resilient to a bad parameter
// it will handle your case and better handle other cases given to it:
int index = 25;
if (index >= 0 && index < array.Length)
{
// Array element found
}
In PHP I like using mysqli_real_escape_string() which escapes special characters in a string for use in an SQL statement.
see https://www.php.net/manual/en/mysqli.real-escape-string.php
Here is an example:
Process.Start("CMD", "/C Pause")
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
And here is a extended function: (Notice the comment-lines using CMD commands.)
#Region " Run Process Function "
' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe"))
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")
Private Function Run_Process(ByVal Process_Name As String, _
Optional Process_Arguments As String = Nothing, _
Optional Read_Output As Boolean = False, _
Optional Process_Hide As Boolean = False, _
Optional Process_TimeOut As Integer = 999999999)
' Returns True if "Read_Output" argument is False and Process was finished OK
' Returns False if ExitCode is not "0"
' Returns Nothing if process can't be found or can't be started
' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.
Try
Dim My_Process As New Process()
Dim My_Process_Info As New ProcessStartInfo()
My_Process_Info.FileName = Process_Name ' Process filename
My_Process_Info.Arguments = Process_Arguments ' Process arguments
My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
My_Process_Info.RedirectStandardOutput = Read_Output ' Redirect (1) Output
My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
My_Process.EnableRaisingEvents = True ' Raise events
My_Process.StartInfo = My_Process_Info
My_Process.Start() ' Run the process NOW
My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)
Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0
If Read_Output = True Then
Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
' Return output by priority
If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
End If
Catch ex As Exception
'MsgBox(ex.Message)
Return Nothing ' Returns nothing if the process can't be found or started.
End Try
Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.
End Function
#End Region
You can also load the body of the script and execute it within the same process:
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile("script2.vbs")
body = ts.ReadAll
ts.Close
Execute body
Try this
$.trim($("#spa").val()).length > 0
It will not treat any white space if any as a correct value
To call GET,POST,DELETE,PUT All kind of request, i have created one common function
function CallAPI($method, $api, $data) {
$url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "GET":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "POST":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
break;
case "PUT":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
break;
}
$response = curl_exec($curl);
$data = json_decode($response);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check the HTTP Status code
switch ($httpCode) {
case 200:
$error_status = "200: Success";
return ($data);
break;
case 404:
$error_status = "404: API Not found";
break;
case 500:
$error_status = "500: servers replied with an error.";
break;
case 502:
$error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
break;
case 503:
$error_status = "503: service unavailable. Hopefully they'll be OK soon!";
break;
default:
$error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
break;
}
curl_close($curl);
echo $error_status;
die;
}
CALL Delete Method
$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);
CALL Post Method
$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);
CALL Get Method
$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);
CALL Put Method
$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);
Only Double and Float type support POSITIVE_INFINITY
constant.
Sure. I suppose that you have already installed TensorFlow for GPU.
You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.
import keras
import tensorflow as tf
config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} )
sess = tf.Session(config=config)
keras.backend.set_session(sess)
Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.
Your "workaround" (hiding the actionBar yourself) is the normal way. But google recommands to always hide the ActionBar when the TitleBar is hidden. Have a look here: https://developer.android.com/training/system-ui/status.html
Actually, you can use the <!--...--> format with multi-lines or tags:
<!--
...
...
...
-->
Use
Try_convert(float,[Value])
See https://raresql.com/2013/04/26/sql-server-how-to-convert-varchar-to-float/
I would create separate images for each one:
LDPI should be 36 x 36.
MDPI should be 48 x 48.
TVDPI should be 64 x 64.
HDPI should be 72 x 72.
XHDPI should be 96 x 96.
XXHDPI should be 144 x 144.
XXXHDPI should be 192 x 192.
Then just put each of them in the separate stalks of the drawable folder.
You are also required to give a large version of your icon when uploading your app onto the Google Play Store and this should be WEB 512 x 512
. This is so large so that Google can rescale it to any size in order to advertise your app throughout the Google Play Store and not add pixelation to your logo.
Basically, all of the other icons should be in proportion to the 'baseline' icon, MDPI at 48 x 48
.
LDPI is MDPI x 0.75.
TVDPI is MDPI x 1.33.
HDPI is MDPI x 1.5.
XHDPI is MDPI x 2.
XXHDPI is MDPI x 3.
XXXHDPI is MDPI x 4.
This is all explained on the Iconography page of the Android Developers website: http://developer.android.com/design/style/iconography.html
Ohhh finally I figured it out! After removing Eclipse directory I installed it into another directory.
echo %ANDROID_SDK_HOME%
has displayed wrong path to sdk directory.
set ANDROID_SDK_HOME "E:\adt-bundle-windows-x86_64-20140321\sdk"
adb kill-server
adb start-server
After these steps, I was able to see confirmation dialog with RSA fingerprint on my phone :)
If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
// Create a new X509TrustManager
sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
.sslContext(sslContext).build();
return client;
private TrustManager[] getTrustManager() {
return new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
};
}
I've slightly modified Peter's answer here to create a reusable, non-interactive shell script called git-split.sh
:
#!/bin/sh
if [[ $# -ne 2 ]] ; then
echo "Usage: git-split.sh original copy"
exit 0
fi
git mv "$1" "$2"
git commit -n -m "Split history $1 to $2 - rename file to target-name"
REV=`git rev-parse HEAD`
git reset --hard HEAD^
git mv "$1" temp
git commit -n -m "Split history $1 to $2 - rename source-file to temp"
git merge $REV
git commit -a -n -m "Split history $1 to $2 - resolve conflict and keep both files"
git mv temp "$1"
git commit -n -m "Split history $1 to $2 - restore name of source-file"
Consider you are designing a simple function, which gets an object of type Bird
and calls its walk()
method. There are two approaches you can think of:
Bird
, or the code will not compile. If anyone wants to use my function, they must be aware that I only accept Bird
sobjects
and I just call the object's walk()
method. So, if the object
can walk()
it is correct, if it can't my function will fail. So here it is not important the object is a Bird
or anything else, it is important that it can walk()
(This is duck typing)It must be considered that the duck typing may be useful in some cases, for example Python uses duck typing a lot.
For the record, I like Job's answer above but I'm curious about a solution just using the variable name by itself in a "do-nothing" statement:
void foo(int x) {
x; /* unused */
...
}
Sure, this has drawbacks; for instance, without the "unused" note it looks like a mistake rather than an intentional line of code.
The benefit is that no DEFINE is needed and it gets rid of the warning.
Are there any performance, optimization, or other differences?
I have searched long and hard for an answer to this question. From what I gather Google did that on purpose once people used the internet connection to add spam comments to the market. However, I did find a guy who had done it and was willing to share the required images. The linked AVD runs(for me) both the market and browser internet.
NOTE: It looks like it's just going to fix the market. But the market won't run without internet, so if the market is fixed, the browser internet will work too. I downloaded the linked files myself and it showed the internet in the browser perfectly.
Try this, it will insert the list item at index 0;
DropDownList1.Items.Insert(0, new ListItem("Add New", ""));
I can't comment yet, but it should be mentioned that if you use numpy array with more than one element this will fail:
if l:
print "list has items"
elif not l:
print "list is empty"
the error will be:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
This is because you are executing the function not referencing it. You should do:
setInterval(swapImages,1000);
Use the Figure.savefig()
method, like so:
ax = s.hist() # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')
It doesn't have to end in pdf
, there are many options. Check out the documentation.
Alternatively, you can use the pyplot
interface and just call the savefig
as a function to save the most recently created figure:
import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf') # saves the current figure
-r
with read.cut
, you can stick with pure bash solutions.
read
a 2nd var (_
) to catch the additional "fields"[[ ]]
over [ ]
.while read -r country _; do
if [[ $country = 'US' ]]; then
((USCOUNTER++))
echo "US counter $USCOUNTER"
fi
done < "$FILE"
If you're using Visual Studio 2013 (may require Pro edition or higher), I was able to add a virtual directory to an IIS Express (file-based) website by right-clicking on the website in the Solution Explorer and clicking Add > New Virtual Directory. This added an entry to the applicationhost.config file as with the manual methods described here.
You need to name the entity that holds the association to User. For example,
... INNER JOIN ug.user u ...
That's the "path" the error message is complaining about -- path from UserGroup to User entity.
Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.
As a good practice I think it is a good idea to test if a popup was blocked and take action in case. You need to know that window.open has a return value, and that value may be null if the action failed. For example, in the following code:
function pop(url,w,h) {
n=window.open(url,'_blank','toolbar=0,location=0,directories=0,status=1,menubar=0,titlebar=0,scrollbars=1,resizable=1,width='+w+',height='+h);
if(n==null) {
return true;
}
return false;
}
if the popup is blocked, window.open will return null. So the function will return false.
As an example, imagine calling this function directly from any link with
target="_blank"
: if the popup is successfully opened, returningfalse
will block the link action, else if the popup is blocked, returningtrue
will let the default behavior (open new _blank window) and go on.
<a href="http://whatever.com" target="_blank" onclick='return pop("http://whatever.com",300,200);' >
This way you will have a popup if it works, and a _blank window if not.
If the popup does not open, you can:
try adding
<meta http-equiv="X-UA-Compatible" content="IE=edge">
right after the opening head tag
Change the minDate dynamically
.datepicker("destroy")
For example
<script>
$(function() {
$( "#datepicker" ).datepicker("destroy");
$( "#datepicker" ).datepicker();
});
</script>
<p>Date: <input type="text" id="datepicker" /></p>
Directly changing eclipse file is not a good idea, no matter facet or ini, unless it could be changed in eclipse. Had the same problem, with jdk1.8 installed. Change it to jdk 1.7.
Besides, according to https://wiki.eclipse.org/Eclipse/Installation, both LUNA and MARS need 1.7. So just ensure you have it installed.
The reason the code in your question does not authenticate is because you are sending the auth in the data object, not in the config, which will put it in the headers. Per the axios docs, the request method alias for post
is:
axios.post(url[, data[, config]])
Therefore, for your code to work, you need to send an empty object for data:
var session_url = 'http://api_address/api/session_endpoint';
var username = 'user';
var password = 'password';
var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.post(session_url, {}, {
headers: { 'Authorization': + basicAuth }
}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});
The same is true for using the auth parameter mentioned by @luschn. The following code is equivalent, but uses the auth parameter instead (and also passes an empty data object):
var session_url = 'http://api_address/api/session_endpoint';
var uname = 'user';
var pass = 'password';
axios.post(session_url, {}, {
auth: {
username: uname,
password: pass
}
}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});
i have this error using datatables.net
i fixed changing the default ajax Get to POST in te properties of the DataTable()
"ajax": {
"url": "../ControllerName/MethodJson",
"type": "POST"
},
Maybe you coul'd use UTF8 bold chars.
For examples: https://yaytext.com/bold-italic/
It works on Chromium 80.0, I don't know on other browsers...
You can also use FunctionalJava library - there is partition
method for List
. This lib has its own collection types, you can convert them to java collections back and forth.
import fj.data.List;
java.util.List<String> javaList = Arrays.asList("a", "b", "c", "d" );
List<String> fList = Java.<String>Collection_List().f(javaList);
List<List<String> partitions = fList.partition(2);
s1.equalsIgnoreCase(s2)
: (see javadoc) s1.equals(s2)
I had a situation when variables went missing from POST and all of the above answers didn't help. It turned out that
max_input_vars=1000
was set by default and POST in question had more than that. This may be a problem.
Suppose you want to set a pop-up text box for clicking a button lets say bt whose id is button, then code using Toast will somewhat look like this:
Button bt;
bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"The text you want to display",Toast.LENGTH_LONG)
}
if [[ $gg =~ ^....grid.* ]]
There are two cases in which you might want to clear a list:
old_list
further in your code;In case 1 you just go on with the assigment:
old_list = [] # or whatever you want it to be equal to
In case 2 the del
statement would reduce the reference count to the list object the name old list
points at. If the list object is only pointed by the name old_list
at, the reference count would be 0, and the object would be freed for garbage collection.
del old_list
Instead of using Bitmap
, you can also do this through a trivial InputStream
. Well, I am not sure, but I think it's a bit efficient.
InputStream inputStream = new FileInputStream(fileName); // You can get an inputStream using any I/O API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
According to Laravel Documentation states you can use this way:
$result->isEmpty();
The isEmpty
method returns true
if the collection is empty; otherwise, false
is returned.
I have just found a way to get server ip and port easily by using Eureka client library. As I am using it anyway for service registration, it is not an additional lib for me just for this purpose.
You need to add the maven dependency first:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
Then you can use the ApplicationInfoManager service in any of your Spring beans.
@Autowired
private ApplicationInfoManager applicationInfoManager;
...
InstanceInfo applicationInfo = applicationInfoManager.getInfo();
The InstanceInfo object contains all important information about your service, like IP address, port, hostname, etc.
You can use toSql method - the easiest way
DB::table('users')->toSql();
And also if you have bindings in your query and want to see the query with bindings. You cant use somthing like that:
$query = DB::table('table')->whereIn('some_field', [1,2,30]);
$sql_with_bindings = str_replace_array('?', $query->getBindings(), $query->toSql());
dd($sql_with_bindings);
If you want this to work in IE 8 and below, use
<!--[if lte IE 8]>
lte
meaning "Less than or equal".
For more on conditional comments, see e.g. the quirksmode.org page.
The issue I had is that sometimes I will need to get at a value that is deeply
nested. Normally you would need to do a type assertion at each level, so I went
ahead and just made a method that takes a map[string]interface{}
and a
string
key, and returns the resulting map[string]interface{}
.
The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:
package main
type Slice []interface{}
type Map map[string]interface{}
func (m Map) M(s string) Map {
return m[s].(map[string]interface{})
}
func (m Map) A(s string) Slice {
return m[s].([]interface{})
}
func (a Slice) M(n int) Map {
return a[n].(map[string]interface{})
}
and example code:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
o, e := os.Open("a.json")
if e != nil {
log.Fatal(e)
}
in_m := Map{}
json.NewDecoder(o).Decode(&in_m)
out_m := in_m.
M("contents").
M("sectionListRenderer").
A("contents").
M(0).
M("musicShelfRenderer").
A("contents").
M(0).
M("musicResponsiveListItemRenderer").
M("navigationEndpoint").
M("browseEndpoint")
fmt.Println(out_m)
}
Update 2016
As this answer receives some attention, I want to hint to a more recommended way on doing this using Virtual Hosts: Apache: Redirect SSL
<VirtualHost *:80>
ServerName mysite.example.com
Redirect permanent / https://mysite.example.com/
</VirtualHost>
<VirtualHost _default_:443>
ServerName mysite.example.com
DocumentRoot /usr/local/apache2/htdocs
SSLEngine On
# etc...
</VirtualHost>
Old answer, hacky thing given that your ssl-port is not set to 80, this will work:
RewriteEngine on
# force ssl
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
Note that this should be your first rewrite rule.
Edit: This code does the following. The RewriteCond(ition) checks wether the ServerPort of the request is 80 (which is the default http-port, if you specified another port, you would have to adjust the condition to it). If so, we match the whole url (.*)
and redirect it to a https-url. %{SERVER_NAME}
may be replaced with a specific url, but this way you don't have to alter the code for other projects. %{REQUEST_URI}
is the portion of the url after the TLD (top-level-domain), so you will be redirected to where you came from, but as https.
You can look into UglifyJS
: http://jstarrdewar.com/blog/2013/02/28/use-uglify-to-automatically-strip-debug-messages-from-your-javascript/, https://github.com/mishoo/UglifyJS
I haven't tried it yet.
Quoting,
if (typeof DEBUG === 'undefined') DEBUG = true; // will be removed
function doSomethingCool() {
DEBUG && console.log("something cool just happened"); // will be removed }
...The log message line will be removed by Uglify's dead-code remover (since it will erase any conditional that will always evaluate to false). So will that first conditional. But when you are testing as uncompressed code, DEBUG will start out undefined, the first conditional will set it to true, and all your console.log() messages will work.
In Visual Studio 2019 WinForm Projects, it is available under
Project Properties -> Application -> View Windows Settings (button)
I ran into the same issue, here's my post:
Android Studio - Gradle build failing - Java Heap Space
exec summary: Windows looks for the gradle.properties file here:
C:\Users\.gradle\gradle.properties
So create that file, and add a line like this:
org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m
as per @Faiz Siddiqui post
Python 3.4 includes the method statistics.mode
, so it is straightforward:
>>> from statistics import mode
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
You can have any type of elements in the list, not just numeric:
>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
===
is not necessary. You know both values are strings so you dont need to compare types.
function do_check()_x000D_
{_x000D_
var str1 = $("#textbox1").val();_x000D_
var str2 = $("#textbox2").val();_x000D_
_x000D_
if (str1 == str2)_x000D_
{_x000D_
$(":text").removeClass("incorrect");_x000D_
alert("equal");_x000D_
}_x000D_
else_x000D_
{_x000D_
$(":text").addClass("incorrect");_x000D_
alert("not equal");_x000D_
}_x000D_
}
_x000D_
.incorrect_x000D_
{_x000D_
background: #ff8888;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input id="textbox1" type="text">_x000D_
<input id="textbox2" type="text">_x000D_
_x000D_
<button onclick="do_check()">check</button>
_x000D_
You can simplify things quite a bit by creating a class that derives from WebClient, overriding its GetWebRequest method and setting a CookieContainer object on it. If you always set the same CookieContainer instance, then cookie management will be handled automatically for you.
But the only way to get at the HttpWebRequest before it is sent is to inherit from WebClient and override that method.
public class CookieAwareWebClient : WebClient
{
private CookieContainer cookie = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = cookie;
}
return request;
}
}
var client = new CookieAwareWebClient();
client.BaseAddress = @"https://www.site.com/any/base/url/";
var loginData = new NameValueCollection();
loginData.Add("login", "YourLogin");
loginData.Add("password", "YourPassword");
client.UploadValues("login.php", "POST", loginData);
//Now you are logged in and can request pages
string htmlSource = client.DownloadString("index.php");
Here's another good solution on stackblitz.
Alternatively:
The accepted answer is a good solution, but it can be improved since your content/chat may often scroll to the bottom involuntarily given how the ngAfterViewChecked() lifecycle hook works.
Here's an improved version...
COMPONENT
import {..., AfterViewChecked, ElementRef, ViewChild, OnInit} from 'angular2/core'
@Component({
...
})
export class ChannelComponent implements OnInit, AfterViewChecked {
@ViewChild('scrollMe') private myScrollContainer: ElementRef;
/**Add the variable**/
scrolledToBottom = false;
ngAfterViewChecked() {
this.scrollToBottom();
}
scrollToBottom(): void {
try {
/**Add the condition**/
if(!this.scrolledToBottom){
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
}
} catch(err) { }
}
/**Add the method**/
onScroll(){
this.scrolledToBottom = true;
}
}
TEMPLATE
<!--Add a scroll event listener-->
<div #scrollMe
style="overflow: scroll; height: xyz;"
(scroll)="onScroll()">
<div class="..."
*ngFor="..."
...>
</div>
</div>
Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
//These variable are initalized here as they need to be used in more than one methid
private double currentLatitude; //lat of user
private double currentLongitude; //long of user
private double latitudeVillageApartmets= 53.385952001750184;
private double longitudeVillageApartments= -6.599087119102478;
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
/*These methods all have to do with the map and wht happens if the activity is paused etc*/
//contains lat and lon of another marker
private void setUpMap() {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
mMap.addMarker(marker); // adding marker
}
//contains your lat and lon
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("You are here");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
@Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.
Guzzle example:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$token = 'your_token';
$httpClient = new Client();
$response = $httpClient->get(
'https://httpbin.org/bearer',
[
RequestOptions::HEADERS => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
]
]
);
print_r($response->getBody()->getContents());
See https://github.com/andriichuk/php-curl-cookbook#bearer-auth
Much simpler than adding URL Just upload an image to the same repository, like:
![Screenshot](screenshot.png)
Looking at the JDK, innermost constructor for Calendar.getInstance()
has this:
public GregorianCalendar(TimeZone zone, Locale aLocale) {
super(zone, aLocale);
gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);
setTimeInMillis(System.currentTimeMillis());
}
so it already automatically does what you suggest. Date's default constructor holds this:
public Date() {
this(System.currentTimeMillis());
}
So there really isn't need to get system time specifically unless you want to do some math with it before creating your Calendar/Date object with it. Also I do have to recommend joda-time to use as replacement for Java's own calendar/date classes if your purpose is to work with date calculations a lot.
In this case, you might get some differences. Consider a line like:
"foo\tbar "
In this case, if you strip
, then you'll get {"foo":"bar"}
as the dictionary entry. If you don't strip, you'll get {"foo":"bar "}
(note the extra space at the end)
Note that if you use line.split()
instead of line.split('\t')
, you'll split on every whitespace character and the "strip
ing" will be done during splitting automatically. In other words:
line.strip().split()
is always identical to:
line.split()
but:
line.strip().split(delimiter)
Is not necessarily equivalent to:
line.split(delimiter)
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
From the bash manpage:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the
--login
option, it first reads and executes commands from the file/etc/profile
, if that file exists. After reading that file, it looks for~/.bash_profile
,~/.bash_login
, and~/.profile
, in that order, and reads and executes commands from the first one that exists and is readable. The--noprofile
option may be used when the shell is started to inhibit this behavior.When a login shell exits, bash reads and executes commands from the file
~/.bash_logout
, if it exists.When an interactive shell that is not a login shell is started, bash reads and executes commands from
~/.bashrc
, if that file exists. This may be inhibited by using the--norc
option. The--rcfile
file option will force bash to read and execute commands from file instead of~/.bashrc
.
Thus, if you want to get the same behavior for both login shells and interactive non-login shells, you should put all of your commands in either .bashrc
or .bash_profile
, and then have the other file source the first one.
Some of the columns in MySQL have an "on update" clause, see:
mysql> SHOW COLUMNS FROM your_table_name;
I'm not sure how to update this but will post an edit when I find out.
Is not necesary to create the function only the @result part. For example:
Select Name,
(SELECT CASE WHEN
DATEPART(DAY, '2016-08-28') > DATEPART(DAY, '2016-09-29')
THEN DATEDIFF(MONTH, '2016-08-28', '2016-09-29') - 1
ELSE DATEDIFF(MONTH, '2016-08-28', '2016-09-29') END) as NumberOfMonths
FROM
tableExample;
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
If you want the style to apply globally you could use the adjacent sibling combinator from css.
.my-button-style + .my-button-style {
margin-left: 40px;
}
/* general button style */
.my-button-style {
height: 100px;
width: 150px;
}
Here is a fiddle: https://jsfiddle.net/caeLosby/10/
It is similar to some of the existing answers but it does not set the margin on the first button. For example in the case
<button id="btn1" class="my-button-style"/>
<button id="btn2" class="my-button-style"/>
only btn2
will get the margin.
For further information see https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator
You can implement a class that holds the fields you have in your JSON
class MyData
{
public string t;
public bool a;
public object[] data;
public string[][] type;
}
and then use the generic version of DeserializeObject:
MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
// Do something with typeStr
}
Documentation: Serializing and Deserializing JSON
The attribute align=middle
sets vertical alignment. To set horizontal alignment using HTML, you can wrap the element inside a center
element and remove all the CSS you have now.
<center><img src=_x000D_
"http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"></center>
_x000D_
If you would rather do it in CSS, there are several ways. A simple one is to set text-align
on a container:
<div style="text-align: center"><img src=_x000D_
"http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"></div>
_x000D_
When you're estimating testing you need to identify the scope of your testing - are we talking unit test, functional, UAT, interface, security, performance stress and volume?
If you're on a waterfall project you probably have some overhead tasks that are fairly constant. Allow time to prepare any planning documents, schedules and reports.
For a functional test phase (I'm a "system tester" so that's my main point of reference) don't forget to include planning! A test case often needs at least as much effort to extract from requirements / specs / user stories as it will take to execute. In addition you need to include some time for defect raising / retesting. For a larger team you'll need to factor in test management - scheduling, reporting, meetings.
Generally my estimates are based on the complexity of the features being delivered rather than a percentage of dev effort. However this does require access to at least a high-level set of instructions. Years of doing testing enables me to work out that a test of a particular complexity will take x hours of effort for preparation and execution. Some tests may require extra effort for data setup. Some tests may involve negotiating with external systems and have a duration far in excess of the effort required.
In the end, though, you need to review it in the context of the overall project. If your estimate is well above that for BA or Development then there may be something wrong with your underlying assumptions.
I know this is an old topic but it's something I'm revisiting at the moment and is of perennial interest to project managers.
Remove .iml file from all your project module and next go to File -> Invalidate Caches/Restart
There is a standard ArgumentException that you could use, or you could subclass and make your own. There are several specific ArgumentException classes:
http://msdn.microsoft.com/en-us/library/system.argumentexception(VS.71).aspx
Whichever one works best.
If you don't want to use jQuery and want to support older browsers:
function addClass(elem, clazz) {
if (!elemHasClass(elem, clazz)) {
elem.className += " " + clazz;
}
}
function elemHasClass(elem, clazz) {
return new RegExp("( |^)" + clazz + "( |$)").test(elem.className);
}
You can use this in app.js
file .
var apiurl = express.Router();
apiurl.use(function(req, res, next) {
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
next();
});
app.use('/', apiurl);
I believe you can find out Eclipse Platform version for every software product that is Eclipse-based.
Open Installation Details:
Choose Plug-ins tab => type org.eclipse.platform => check Version column.
You can match version code and version name on https://wiki.eclipse.org/Older_Versions_Of_Eclipse
For example, check out GitEye (Git GUI client)
Or checkout DBBeaver (DB manager):
Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:
sudo apt install vlc ffmpeg
In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.
I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.
You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:
ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'
For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:
ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554
It depends on your operating system and your shell
On linux with the shell bash, you create environment variables like this(in the console):
export FOO=bar
For more information on environment variables on ubuntu (for example):
If your script always requires an Administrator's privileges then:
runas /user:Administrator "python your_script.py"
I have never considered it to be a bad practice to throw an exception in the constructor. When the class is designed, you have a certain idea in mind of what the structure for that class should be. If someone else has a different idea and tries to execute that idea, then you should error accordingly, giving the user feedback on what the error is. In your case, you might consider something like
if (age < 0) throw new NegativeAgeException("The person you attempted " +
"to construct must be given a positive age.");
where NegativeAgeException
is an exception class that you constructed yourself, possibly extending another exception like IndexOutOfBoundsException
or something similar.
Assertions don't exactly seem to be the way to go, either, since you're not trying to discover bugs in your code. I would say terminating with an exception is absolutely the right thing to do here.
Use display instead of visibility. display: none for invisible and no setting for visible.
If you're trying to grab a range with a dynamically generated string, then you just have to build the string like this:
Range(firstcol & firstrow & ":" & secondcol & secondrow).Select
(I am using Android Studio 3.0.1)
Distance (km) = 10^((Free Space Path Loss – 92.45 – 20log10(f))/20)
stringByReplacingOccurrencesOfString will replace all white space with in the string non only the starting and end
Use
[YourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]
To understand those phrases let's look at the couple of things:
typedef double Foo;
void fooFunc(Foo &_bar){ ... }
So that's passing a double by reference.
typedef double* Foo;
void fooFunc(Foo &_bar){ ... }
now it's passing a pointer to a double by reference.
typedef double** Foo;
void fooFunc(Foo &_bar){ ... }
Finally, it's passing a pointer to a pointer to a double by reference. If you think in terms of typedefs like this you'll understand the proper ordering of the & and * plus what it means.
@ variables are instance variables, without are local variables.
Read more at http://ruby.about.com/od/variables/a/Instance-Variables.htm
You can force it (browser permitting, I imagine) by inserting line breaks in the HTML source, like this:
<INPUT value="Line 1
Line 2">
Of course working out where to place the line breaks is not necessarily trivial...
If you can use an HTML <BUTTON>
instead of an <INPUT>
, such that the button label is the element's content rather than its value
attribute, placing that content inside a <SPAN>
with a width
attribute that is a few pixels narrower than that of the button seems to do the trick (even in IE6 :-).
T
and TRUE
are True, F
and FALSE
are False. T
and F
can be redefined, however, so you should only rely upon TRUE
and FALSE
. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.
Some statistics related to this famous double precision question.
When adding all values (a + b) using a step of 0.1 (from 0.1 to 100) we have ~15% chance of precision error. Note that the error could result in slightly bigger or smaller values. Here are some examples:
0.1 + 0.2 = 0.30000000000000004 (BIGGER)
0.1 + 0.7 = 0.7999999999999999 (SMALLER)
...
1.7 + 1.9 = 3.5999999999999996 (SMALLER)
1.7 + 2.2 = 3.9000000000000004 (BIGGER)
...
3.2 + 3.6 = 6.800000000000001 (BIGGER)
3.2 + 4.4 = 7.6000000000000005 (BIGGER)
When subtracting all values (a - b where a > b) using a step of 0.1 (from 100 to 0.1) we have ~34% chance of precision error. Here are some examples:
0.6 - 0.2 = 0.39999999999999997 (SMALLER)
0.5 - 0.4 = 0.09999999999999998 (SMALLER)
...
2.1 - 0.2 = 1.9000000000000001 (BIGGER)
2.0 - 1.9 = 0.10000000000000009 (BIGGER)
...
100 - 99.9 = 0.09999999999999432 (SMALLER)
100 - 99.8 = 0.20000000000000284 (BIGGER)
*15% and 34% are indeed huge, so always use BigDecimal when precision is of big importance. With 2 decimal digits (step 0.01) the situation worsens a bit more (18% and 36%).
You cannot. Facebook API has read_mailbox but no write_mailbox extended permission. I'm guessing this is done to prevent spammy apps from flooding friend's inboxes.
Did you set the section header height in the viewDidLoad?
self.tableView.sectionHeaderHeight = 70
Plus you should replace
self.view.addSubview(view)
by
view.addSubview(label)
Finally you have to check your frames
let view = UIView(frame: CGRect.zeroRect)
and eventually the desired text color as it seems to be currently white on white.
I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.
<?php
include 'nav.php';
/*
Download PhpMailer from the following link:
https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
Extract the PHPMailer-master folder into your xampp->htdocs folder
Make changes in the following code and its done :-)
You will receive the mail with the name Root User.
To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
And change the name here:
public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some //other folder
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP(); // telling the class to use SMTP
$rec1="[email protected]"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject = "Eventbook";
$mail->Body = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo //Fill in the document.location thing
'<script type="text/javascript">
if(confirm("Your mail has been sent"))
document.location = "/";
</script>';
}
?>
You can shorten JSprangs solution a bit by using a method group instead:
string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ints = s1.Split(';').Select(int.Parse).ToArray();
Don't use IDs at all if you don't need to, instead wrap the input in a label like this:
<label>
My Label
<input type="text"/>
</label>
Then you won't need to worry about unique IDs.
I don´t know if this is relevant anymore, but I fixed it with the @RequestMapping annotation.
@RequestMapping(method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
There's no need for the outer try in your example, so you can at least go down from 3 to 2, and also you don't need closing ;
at the end of the resource list. The advantage of using two try blocks is that all of your code is present up front so you don't have to refer to a separate method:
public List<User> getUser(int userId) {
String sql = "SELECT id, username FROM users WHERE id = ?";
List<User> users = new ArrayList<>();
try (Connection con = DriverManager.getConnection(myConnectionURL);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, userId);
try (ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
users.add(new User(rs.getInt("id"), rs.getString("name")));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
If none of the above solutions work for you (they did not for me) here is what worked on my server:
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]
well, it is not really necessary to create a function for this when it can be done simply with 1 CSS class.
just wrap your text around this class and see the magic :D
<p style={{whiteSpace: 'pre-line'}}>my json text goes here \n\n</p>
note: because you will always present your text in frontend with HTML you can add the style={{whiteSpace: 'pre-line'}} to any tag, not just the p tag.