First thing you need to do here is correct the hibernate dialect version like @JavaLearner has explained. Then you have make sure that all the versions of hibernate dependencies you are using are upto date. Typically you would need: database driver like mysql-connector-java
, hibernate dependency: hibernate-core
and hibernate entity manager: hibernate-entitymanager
. Lastly don't forget to check that the database tables you are using are not the reserved words like order
, group
, limit
, etc. It might save you a lot of headache.
It also disturb me a lot but now it is fine The solution is very simple (written blow) [window (android studio)]
Use: https://github.com/mkoryak/floatThead
Docs: http://mkoryak.github.io/floatThead/examples/bootstrap3/
$(document).ready(function(){
$(".sticky-header").floatThead({top:50});
});
http://jsbin.com/zuzuqe/1/edit
HTML
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
<!-- Begin page content -->
<div class="container">
<div class="page-header">
<h1>Sticky footer with fixed navbar</h1>
</div>
<p class="lead">Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS. A fixed navbar has been added within <code>#wrap</code> with <code>padding-top: 60px;</code> on the <code>.container</code>.</p>
<table class="table table-striped sticky-header">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
<h3>Table 2</h3>
<table class="table table-striped sticky-header">
<thead>
<tr>
<th>#</th>
<th>New Table</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
CSS
body{
padding-top:50px;
}
table.floatThead-table {
border-top: none;
border-bottom: none;
background-color: #fff;
}
You can use the JDOM library in Java. Define your tags as Element objects, document your elements with Document Class, and build your xml file with SAXBuilder. Try this example:
//Root Element
Element root=new Element("CONFIGURATION");
Document doc=new Document();
//Element 1
Element child1=new Element("BROWSER");
//Element 1 Content
child1.addContent("chrome");
//Element 2
Element child2=new Element("BASE");
//Element 2 Content
child2.addContent("http:fut");
//Element 3
Element child3=new Element("EMPLOYEE");
//Element 3 --> In this case this element has another element with Content
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));
//Add it in the root Element
root.addContent(child1);
root.addContent(child2);
root.addContent(child3);
//Define root element like root
doc.setRootElement(root);
//Create the XML
XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));
I was totally lost on why my Gridview.Databind()
would not refresh.
My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:
gvServerConfiguration.Databind()
uppServerConfiguration.Update()
uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.
Hope this helps someone.
You need to set useaccessibleheader
attribute of the gridview to true
and also then also specify a TableSection
to be a header after calling the DataBind()
method on you GridView object. So if your grid view is mygv
mygv.UseAccessibleHeader = True
mygv.HeaderRow.TableSection = TableRowSection.TableHeader
This should result in a proper formatted grid with thead
and tbody
tags
If you want to compare to a string literal you need to put it in (single) quotes:
<xsl:if test="Count != 'N/A'">
Its even good to use tortoise svn cleanup, no need to use Ankh one in my case
Your log4j.properties file should be on the root level of your capitolo2.ear (not in META-INF), that is, here:
MyProject
¦ build.xml
¦
+---build
¦ ¦ capitolo2-ejb.jar
¦ ¦ capitolo2-war.war
¦ ¦ JBoss4.dpf
¦ ¦ log4j.properties
Use typeof(Book).GetProperties()
to get an array of PropertyInfo
instances. Then use GetCustomAttributes()
on each PropertyInfo
to see if any of them have the Author
Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.
Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):
public static Dictionary<string, string> GetAuthors()
{
Dictionary<string, string> _dict = new Dictionary<string, string>();
PropertyInfo[] props = typeof(Book).GetProperties();
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
AuthorAttribute authAttr = attr as AuthorAttribute;
if (authAttr != null)
{
string propName = prop.Name;
string auth = authAttr.Name;
_dict.Add(propName, auth);
}
}
}
return _dict;
}
You don't need to use GROUP BY but using it won't change the outcome. Just add an ORDER BY line at the end to sort your results.
SELECT player_name, player_salary, SUM(player_salary*1.1) AS NewSalary
FROM players
GROUP BY player_salary, player_name;
ORDER BY SUM(player_salary*1.1) DESC
function scrollTo(hash) {
location.hash = "#" + hash;
}
No jQuery required at all!
The argument to split is a regular expression. "." matches anything so your delimiter to split on is anything.
#include<stdio.h>
int main()
{
int i,j,n,b;
printf("Enter no of rows ");
scanf("%d",&n);
b=n;
for(i=1;i<=n;++i)
{
for(j=1;j<=i;j++)
{
printf("%*d",b,j);
b=1;
}
b=n;
b=b-i;
printf("\n");
}
return 0;
}
I did it in one project of mine. I used MDB to store the data about bills and used Excel to render them, giving the user the possibility to adapt it.
In this case the best solution is:
Not to use any ADO/DAO in Excel. I implemented everything as public functions in MDB modules and called them directly from Excel. You can return even complex data objects, like arrays of strings etc by calling MDB functions with necessary arguments. This is similar to client/server architecture of modern web applications: you web application just does the rendering and user interaction, database and middle tier is then on the server side.
Use Excel forms for user interaction and for data visualisation.
I usually have a very last sheet with some names regions for settings: the path to MDB files, some settings (current user, password if needed etc.) -- so you can easily adapt your Excel implementation to different location of you "back-end" data.
An excellent resource is the material of the MIT course 6.828: Operating System Engineering.
XV6 - simple Unix-like teaching OS written in ANSI C for x86 http://pdos.csail.mit.edu/6.828/2012/xv6.html
XV6 source - as a printed booklet with line numbers http://pdos.csail.mit.edu/6.828/2012/xv6/xv6-rev7.pdf
XV6 book - explains the main ideas of os design http://pdos.csail.mit.edu/6.828/2012/xv6/book-rev7.pdf
The material is compact: 92 pages source and 96 pages commentary.
I like it more than the Minix book! It's a true gem!
You should specify
<input type="checkbox" name="Days[]" value="Daily">Daily<br>
as array.
Add []
to all names Days
and work at php with this like an array.
After it, you can INSERT
values at different columns at db, or use implode
and save values into one column.
Didn't tested it, but you can try like this. Don't forget to replace mysql
with mysqli
.
<html>
<body>
<form method="post" action="chk123.php">
Flights on: <br/>
<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>
<input type="checkbox" name="Days[]" value="Monday">Monday<br>
<input type="checkbox" name="Days[]" value="Tuesday">Tuesday <br>
<input type="checkbox" name="Days[]" value="Wednesday">Wednesday<br>
<input type="checkbox" name="Days[]" value="Thursday">Thursday <br>
<input type="checkbox" name="Days[]" value="Friday">Friday<br>
<input type="checkbox" name="Days[]" value="Saturday">Saturday <br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$checkBox = implode(',', $_POST['Days']);
if(isset($_POST['submit']))
{
$query="INSERT INTO example (orange) VALUES ('" . $checkBox . "')";
mysql_query($query) or die (mysql_error() );
echo "Complete";
}
?>
Without a loop, just for the kicks of it...
You can either convert the array to a non-associative one, by doing:
$page = array_values($page);
And then acessing each element by it's zero-based index:
echo $page[0]; // 'index.html'
echo $page[1]; // 'services.html'
Or you can use a slightly more complicated version:
$value = array_slice($page, 0, 1);
echo key($value); // Home
echo current($value); // index.html
$value = array_slice($page, 1, 1);
echo key($value); // Service
echo current($value); // services.html
I fixed this issue by deleting the output file and running the command again. It turns out it does NOT overwrite the previous file. I had this issue when renewing a let's encrypt cert with tomcat
I have encountered this problem and finally solved it today, so I write down what I have learned and I hope it is helpful for someone who is new to Android's ViewPager
and update as I do. I'm using FragmentStatePagerAdapter
in API level 17 and currently have just 2 fragments. I think there must be something not correct, please correct me, thanks.
Serialized data has to be loaded into memory. This can be done using a CursorLoader
/AsyncTask
/Thread
. Whether it's automatically loaded depends on your code. If you are using a CursorLoader
, it's auto-loaded since there is a registered data observer.
After you call viewpager.setAdapter(pageradapter)
, the adapter's getCount()
is constantly called to build fragments. So if data is being loaded, getCount()
can return 0, thus you don't need to create dummy fragments for no data shown.
After the data is loaded, the adapter will not build fragments automatically since getCount()
is still 0, so we can set the actually loaded data number to be returned by getCount()
, then call the adapter's notifyDataSetChanged()
. ViewPager
begin to create fragments (just the first 2 fragments) by data in memory. It's done before notifyDataSetChanged()
is returned. Then the ViewPager
has the right fragments you need.
If the data in the database and memory are both updated (write through), or just data in memory is updated (write back), or only data in the database is updated. In the last two cases if data is not automatically loaded from the database to memory (as mentioned above).
The ViewPager
and pager adapter just deal with data in memory.
So when data in memory is updated, we just need to call the adapter's notifyDataSetChanged()
. Since the fragment is already created, the adapter's onItemPosition()
will be called before notifyDataSetChanged()
returns. Nothing needs to be done in getItemPosition()
. Then the data is updated.
Well, first you need to request the username of the user from the session in your controller action like this:
$username=$this->get('security.context')->getToken()->getUser()->getUserName();
then do a query to the db and get your object with regular dql like
$em = $this->get('doctrine.orm.entity_manager');
"SELECT u FROM Acme\AuctionBundle\Entity\User u where u.username=".$username;
$q=$em->createQuery($query);
$user=$q->getResult();
the $user should now hold the user with this username ( you could also use other fields of course)
...but you will have to first configure your /app/config/security.yml configuration to use the appropriate field for your security provider like so:
security:
provider:
example:
entity: {class Acme\AuctionBundle\Entity\User, property: username}
hope this helps!
You should be able to &&
the conditions:
ng-disabled="condition1 && condition2"
While this seems to work
Code::query()
->where('to_be_used_by_user_id', '!=' , 2)
->orWhereNull('to_be_used_by_user_id')
->get();
you should not use it for big tables, because as a general rule "or" in your where clause is stopping query to use index. You are going from "Key lookup" to "full table scan"
Instead, try Union
$first = Code::whereNull('to_be_used_by_user_id');
$code = Code::where('to_be_used_by_user_id', '!=' , 2)
->union($first)
->get();
This is a step-by-step procedure to get pkg-config working on Windows, based on my experience, using the info from Oliver Zendel's comment.
I assume here that MinGW was installed to C:\MinGW. There were multiple versions of the packages available, and in each case I just downloaded the latest version.
Now CMake will be able to use pkg-config if it is configured to use MinGW.
If you wants to concatenate two arrays without any duplicate value,Just try this
var a=[34, 35, 45, 48, 49];
var b=[48, 55];
var c=a.concat(b).sort();
var res=c.filter((value,pos) => {return c.indexOf(value) == pos;} );
I actually had a failure in the Microsoft uninstall. I had installed node-v8.2.1-x64 and needed to run version node-v6.11.1-x64.
The uninstalled was failing with the error: "Windows cannot access the specified device, path, or file" or similar.
I ended up going to the Downloads folder right clicking the node-v8.2.1-x64 MSI and selecting uninstall.. this worked.
Regards, Jon
I got this error when I tried adding a column from a different table. Indeed I got duplicate index values along the way. But it turned out I was just doing it wrong: I actually needed to df.join
the other table.
This pointer might help someone in a similar situation.
There is a dedicated npm
package for it. css-scrollbar-side
The .egg
file is a distribution format for Python packages. It’s just an alternative to a source code distribution or Windows exe
. But note that for pure Python
, the .egg
file is completely cross-platform.
The .egg
file itself is essentially a .zip
file. If you change the extension to “zip
”, you can see that it will have folders inside the archive.
Also, if you have an .egg
file, you can install it as a package using easy_install
Example:
To create an .egg
file for a directory say mymath
which itself may have several python scripts, do the following step:
# setup.py
from setuptools import setup, find_packages
setup(
name = "mymath",
version = "0.1",
packages = find_packages()
)
Then, from the terminal do:
$ python setup.py bdist_egg
This will generate lot of outputs, but when it’s completed you’ll see that you have three new folders: build, dist, and mymath.egg-info. The only folder that we care about is the dist folder where you'll find your .egg
file, mymath-0.1-py3.5.egg
with your default python (installation) version number(mine here: 3.5)
Source: Python library blog
No, POST/GET values are never null
. The best they can be is an empty string, which you can convert to null
/'NULL'
.
if ($_POST['value'] === '') {
$_POST['value'] = null; // or 'NULL' for SQL
}
One can avoid the AttributeError
brought about by set_axis_labels()
method by using the matplotlib.pyplot.xlabel
and matplotlib.pyplot.ylabel
.
matplotlib.pyplot.xlabel
sets the x-axis label while the matplotlib.pyplot.ylabel
sets the y-axis label of the current axis.
Solution code:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)
Output figure:
My suggestion would be
$value = $_POST["myfield"];
$Query = Database::Prepare("SELECT * FROM TABLE WHERE MYFIELD LIKE ?");
$Query->Execute(array("%".$value."%"));
if u are getting errors even after downloading newest SDK and Android Studio I am a newbie: What i did was 1. Download the recent SDK (i was ) 2.Open file-Project structure (ctrl+alt+shift+S) 3. In modules select app 4.In properties tab..change compile sdk version to api 23 Android 6.0 marshmallow(latest)
make sure compile adk versionand buildtools are of same version(23)
Hope it helps someone so that he wont suffer like i did for these couple of days.
I have had this issue multiple times only in Windows I try these in the order usually.
npm install --force
node_modules/
Usually trying npm install
after one of those steps will resolve it.
There's MonoDevelop, which I occasionally use when I want to do some light C# coding when in Linux. It's nothing close to VS.Net, but it works for small projects. I really don't think most of the alternatives people have listed come anywhere close to VS.Net.
TL;DR Use scanner.skip("\\R")
(since skip
uses regex where \R
represents line separators) before each scanner.newLine()
call, which is executed after:
scanner.next()
scanner.next*TYPE*()
method, like scanner.nextInt()
.text which represents few lines also contains non-printable characters between lines (we call them line separators) like
carriage return (CR - in String literals represented as "\r"
)
line feed (LF - in String literals represented as "\n"
)
when you are reading data from the console, it allows the user to type his response and when he is done he needs to somehow confirm that fact. To do so, the user is required to press "enter"/"return" key on the keyboard.
What is important is that this key beside ensuring placing user data to standard input (represented by System.in
which is read by Scanner
) also sends OS dependant line separators (like for Windows \r\n
) after it.
So when you are asking the user for value like age
, and user types 42 and presses enter, standard input will contain "42\r\n"
.
Scanner#nextInt
(and other Scanner#nextType
methods) doesn't allow Scanner to consume these line separators. It will read them from System.in
(how else Scanner would know that there are no more digits from the user which represent age
value than facing whitespace?) which will remove them from standard input, but it will also cache those line separators internally. What we need to remember, is that all of the Scanner methods are always scanning starting from the cached text.
Now Scanner#nextLine()
simply collects and returns all characters until it finds line separators (or end of stream). But since line separators after reading the number from the console are found immediately in Scanner's cache, it returns empty String, meaning that Scanner was not able to find any character before those line separators (or end of stream).
BTW nextLine
also consumes those line separators.
So when you want to ask for number and then for entire line while avoiding that empty string as result of nextLine
, either
nextInt
from Scanners cache bynextLine
,skip("\\R")
or skip("\r\n|\r|\n")
to let Scanner skip part matched by line separator (more info about \R
: https://stackoverflow.com/a/31060125)nextInt
(nor next
, or any nextTYPE
methods) at all. Instead read entire data line-by-line using nextLine
and parse numbers from each line (assuming one line contains only one number) to proper type like int
via Integer.parseInt
.BTW: Scanner#nextType
methods can skip delimiters (by default all whitespaces like tabs, line separators) including those cached by scanner, until they will find next non-delimiter value (token). Thanks to that for input like "42\r\n\r\n321\r\n\r\n\r\nfoobar"
code
int num1 = sc.nextInt();
int num2 = sc.nextInt();
String name = sc.next();
will be able to properly assign num1=42
num2=321
name=foobar
.
A temporary table can have 3 kinds, the #
is the most used. This is a temp table that only exists in the current session.
An equivalent of this is @
, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session.
The ##
is one that is the same as the #
, however, the scope is wider, so you can use it within the same session, within other stored procedures.
You can create a temp table in various ways:
declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz
The short answer is NO; we don't have a parent selector
at this stage in CSS, but if you don't have to swap the elements or classes anyway, the second option is using JavaScript. Something like this:
var activeATag = Array.prototype.slice.call(document.querySelectorAll('a.active'));
activeATag.map(function(x) {
if(x.parentNode.tagName === 'LI') {
x.parentNode.style.color = 'red'; // Your property: value;
}
});
Or a shorter way if you use jQuery in your application:
$('a.active').parents('li').css('color', 'red'); // Your property: value;
Do you create the DataTables yourself? Because iterating through the children of any Object (as in DataSet.Tables) is usually not needed, as it's the job of the Parent to dispose all its child members.
Generally, the rule is: If you created it and it implements IDisposable, Dispose it. If you did NOT create it, then do NOT dispose it, that's the job of the parent object. But each object may have special rules, check the Documentation.
For .NET 3.5, it explicitly says "Dispose it when not using anymore", so that's what I would do.
For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:
// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
class MyReceivingClass {
// ---------------------------------------------
// INIT -> GOOD PLACE FOR REGISTERING
// ---------------------------------------------
init() {
// WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)
// Register without parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)
// Register WITH parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
}
// ---------------------------------------------
// DE-INIT -> LAST OPTION FOR RE-REGISTERING
// ---------------------------------------------
deinit {
NotificationCenter.default.removeObserver(self)
}
// either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'
// ---------------------------------------------
// HANDLE NOTIFICATION WITHOUT PARAMETER
// ---------------------------------------------
@objc func handleNotification() {
print("RECEIVED ANY NOTIFICATION")
}
// ---------------------------------------------
// HANDLE NOTIFICATION WITH PARAMETER
// ---------------------------------------------
@objc func handle(withNotification notification : NSNotification) {
print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
}
}
In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):
// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {
print("POSTING")
// Define identifiyer
let notificationName = Notification.Name.UIApplicationWillResignActive
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
}
Instead of copy/paste a unicode character or setting it in the code-behind you could also change the properties of the TextBox. Simply set "UseSystemPasswordChar" to True and everytghing will be done for you by the Framework. Or in code-behind:
this.txtPassword.UseSystemPasswordChar = true;
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
please try these
<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "User_name" value= "<?php echo $row['User_name']; ?> "size=10>
Password
<input type="text" name= "User_password" value= "<?php echo $row['User_password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>
Try this MEX file for ACTUALLY calling Python from MATLAB not the other way around as others suggest. It provides fairly decent integration : http://algoholic.eu/matpy/
You can do something like this easily:
[X,Y]=meshgrid(-10:0.1:10,-10:0.1:10);
Z=sin(X)+cos(Y);
py_export('X','Y','Z')
stmt = sprintf(['import matplotlib\n' ...
'matplotlib.use(''Qt4Agg'')\n' ...
'import matplotlib.pyplot as plt\n' ...
'from mpl_toolkits.mplot3d import axes3d\n' ...
'f=plt.figure()\n' ...
'ax=f.gca(projection=''3d'')\n' ...
'cset=ax.plot_surface(X,Y,Z)\n' ...
'ax.clabel(cset,fontsize=9,inline=1)\n' ...
'plt.show()']);
py('eval', stmt);
What bout this query (based on the description from manual)?
SELECT table_name
FROM information_schema.tables
WHERE table_schema='public'
AND table_type='BASE TABLE';
-- First Truncate temporary table SQL> TRUNCATE TABLE test_temp1; -- Then Drop temporary table SQL> DROP TABLE test_temp1;
This should probably be a comment, however, I don't have enough reputation to comment.
I suggest you really use the table (HTML) instead of ion-row and ion-col. Things will not look nice when one of the cell's content is too long.
One worse case looks like this:
| 10 | 20 | 30 | 40 |
| 1 | 2 | 3100 | 41 |
Higher fidelity example fork from @jpoveda
Here is a complete example showing how to use the **
operator to pass values from a dictionary as keyword arguments.
>>> def f(x=2):
... print(x)
...
>>> new_x = {'x': 4}
>>> f() # default value x=2
2
>>> f(x=3) # explicit value x=3
3
>>> f(**new_x) # dictionary value x=4
4
It depends on the context. I think you're referring to the operating system's hostname (returned by hostname
when you're logged in). This command is for internal names only, so to query for a machine's name requires different naming systems. There are multiple systems which use names to identify hosts including DNS, DHCP, LDAP (DN's), hostname
, etc. and many systems use zeroconf to synchronize names between multiple naming systems. For this reason, results from hostname
will sometimes match results from dig
(see below) or other naming systems, but often times they will not match.
DNS is by far the most common and is used both on the internet (like google.com. A 216.58.218.142
) and at home (mDNS/LLMNR), so here's how to perform a reverse DNS lookup: dig -x <address>
(nslookup
and host
are simpler, provide less detail, and may even return different results; however, dig
is not included in Windows).
Note that hostnames within a CDN will not resolve to the canonical domain name (e.g. "google.com"), but rather the hostname of the host IP you queried (e.g. "dfw25s08-in-f142.1e100.net"; interesting tidbit: 1e100 is 1 googol).
Also note that DNS hosts can have more than one name. This is common for hosts with more than one webserver (virtual hosting), although this is becoming less common thanks to the proliferation of virtualization technologies. These hosts have multiple PTR DNS records.
Finally, note that DNS host records can be overridden by the local machine via /etc/hosts. If you're not getting the hostname you expect, be sure you check this file.
DHCP hostnames are queried differently depending on which DHCP server software is used, because (as far as I know) the protocol does not define a method for querying; however, most servers provide some way of doing this (usually with a privileged account).
Note DHCP names are usually synchronized with DNS server(s), so it's common to see the same hostnames in a DHCP client least table and in the DNS server's A (or AAAA for IPv6) records. Again, this is usually done as part of zeroconf.
Also note that just because a DHCP lease exists for a client, doesn't mean it's still being used.
NetBIOS for TCP/IP (NBT) was used for decades to perform name resolution, but has since been replaced by LLMNR for name resolution (part of zeroconf on Windows). This legacy system can still be queried with the nbtstat
(Windows) or nmblookup
(Linux).
For me upgrading gradle version and plugin to the latest version did the trick.
Use replace with Environment.NewLine
myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;
As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of new line control characters.
Static arrays are allocated memory at compile time and the memory is allocated on the stack. Whereas, the dynamic arrays are allocated memory at the runtime and the memory is allocated from heap.
int arr[] = { 1, 3, 4 }; // static integer array.
int* arr = new int[3]; // dynamic integer array.
EDIT based on comments:
If you have line breaks in your result set and want to remove them, make your query this way:
SELECT
REPLACE(REPLACE(YourColumn1,CHAR(13),' '),CHAR(10),' ')
,REPLACE(REPLACE(YourColumn2,CHAR(13),' '),CHAR(10),' ')
,REPLACE(REPLACE(YourColumn3,CHAR(13),' '),CHAR(10),' ')
--^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
--only add the above code to strings that are having line breaks, not to numbers or dates
FROM YourTable...
WHERE ...
This will replace all the line breaks with a space character.
Run this to "get" all characters permitted in a char() and varchar():
;WITH AllNumbers AS
(
SELECT 1 AS Number
UNION ALL
SELECT Number+1
FROM AllNumbers
WHERE Number+1<256
)
SELECT Number AS ASCII_Value,CHAR(Number) AS ASCII_Char FROM AllNumbers
OPTION (MAXRECURSION 256)
OUTPUT:
ASCII_Value ASCII_Char
----------- ----------
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 !
34 "
35 #
36 $
37 %
38 &
39 '
40 (
41 )
42 *
43 +
44 ,
45 -
46 .
47 /
48 0
49 1
50 2
51 3
52 4
53 5
54 6
55 7
56 8
57 9
58 :
59 ;
60 <
61 =
62 >
63 ?
64 @
65 A
66 B
67 C
68 D
69 E
70 F
71 G
72 H
73 I
74 J
75 K
76 L
77 M
78 N
79 O
80 P
81 Q
82 R
83 S
84 T
85 U
86 V
87 W
88 X
89 Y
90 Z
91 [
92 \
93 ]
94 ^
95 _
96 `
97 a
98 b
99 c
100 d
101 e
102 f
103 g
104 h
105 i
106 j
107 k
108 l
109 m
110 n
111 o
112 p
113 q
114 r
115 s
116 t
117 u
118 v
119 w
120 x
121 y
122 z
123 {
124 |
125 }
126 ~
127
128 €
129
130 ‚
131 ƒ
132 „
133 …
134 †
135 ‡
136 ˆ
137 ‰
138 Š
139 ‹
140 Œ
141
142 Ž
143
144
145 ‘
146 ’
147 “
148 ”
149 •
150 –
151 —
152 ˜
153 ™
154 š
155 ›
156 œ
157
158 ž
159 Ÿ
160
161 ¡
162 ¢
163 £
164 ¤
165 ¥
166 ¦
167 §
168 ¨
169 ©
170 ª
171 «
172 ¬
173
174 ®
175 ¯
176 °
177 ±
178 ²
179 ³
180 ´
181 µ
182 ¶
183 ·
184 ¸
185 ¹
186 º
187 »
188 ¼
189 ½
190 ¾
191 ¿
192 À
193 Á
194 Â
195 Ã
196 Ä
197 Å
198 Æ
199 Ç
200 È
201 É
202 Ê
203 Ë
204 Ì
205 Í
206 Î
207 Ï
208 Ð
209 Ñ
210 Ò
211 Ó
212 Ô
213 Õ
214 Ö
215 ×
216 Ø
217 Ù
218 Ú
219 Û
220 Ü
221 Ý
222 Þ
223 ß
224 à
225 á
226 â
227 ã
228 ä
229 å
230 æ
231 ç
232 è
233 é
234 ê
235 ë
236 ì
237 í
238 î
239 ï
240 ð
241 ñ
242 ò
243 ó
244 ô
245 õ
246 ö
247 ÷
248 ø
249 ù
250 ú
251 û
252 ü
253 ý
254 þ
255 ÿ
(255 row(s) affected)
I've posted a new solution for this on another thread.
It uses a table to store variables, and can be updated at any time. A static immutable getter function is dynamically created (by another function), triggered by update to your table. You get nice table storage, plus the blazing fast speeds of an immutable getter.
Given an array, you can traverse it one of the many ways as follows.
1. Classic for
loop
const myArray = ['Hello', 'World'];
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
_x000D_
2. for...of
const myArray = ['Hello', 'World'];
for (const item of myArray) {
console.log(item);
}
_x000D_
const myArray = ['Hello', 'World'];
myArray.forEach(item => {
console.log(item);
});
_x000D_
4. while
loop
const myArray = ['Hello', 'World'];
let i = 0;
while (i < myArray.length) {
console.log(myArray[i]);
i++;
}
_x000D_
5. do...while
loop
const myArray = ['Hello', 'World'];
let i = 0;
do {
console.log(myArray[i]);
i++;
} while (i < myArray.length);
_x000D_
6. Queue style
const myArray = ['Hello', 'World'];
while (myArray.length) {
console.log(myArray.shift());
}
_x000D_
7. Stack style
Note: The list is printed reverse in this one.
const myArray = ['Hello', 'World'];
while (myArray.length) {
console.log(myArray.pop());
}
_x000D_
Prolog program actually is big condition for "if" with "then" which prints "Goal is reached" and "else" which prints "No sloutions was found". A, B
means "A is true and B is true", most of prolog systems will not try to satisfy "B" if "A" is not reachable (i.e. X=3, write('X is 3'),nl
will print 'X is 3' when X=3, and will do nothing if X=2).
\n
is Unix, \r
is Mac, \r\n
is Windows.
Sometimes it's giving trouble especially when running code cross platform. You can bypass this by using Environment.NewLine
.
Please refer to What is the difference between \r, \n and \r\n ?! for more information. Happy reading
From Java 9+ and up, you can define a new URLStreamHandlerProvider
. The URL
class uses the service loader framework to load it at run time.
Create a provider:
package org.example;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.spi.URLStreamHandlerProvider;
public class ClasspathURLStreamHandlerProvider extends URLStreamHandlerProvider {
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
if ("classpath".equals(protocol)) {
return new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return ClassLoader.getSystemClassLoader().getResource(u.getPath()).openConnection();
}
};
}
return null;
}
}
Create a file called java.net.spi.URLStreamHandlerProvider
in the META-INF/services
directory with the contents:
org.example.ClasspathURLStreamHandlerProvider
Now the URL class will use the provider when it sees something like:
URL url = new URL("classpath:myfile.txt");
You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).
select
if(
fieldA is NULL,
if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
) as maxValue
You can change NULL to your preferred default value (if both values is NULL).
Serge is right - my workaround:
function mySleep (sec)
{
SpreadsheetApp.flush();
Utilities.sleep(sec*1000);
SpreadsheetApp.flush();
}
I would say there is also a starred notation for the import
ES6 keyword worth to mention.
If you try to console log Mix:
import * as Mix from "./A";
console.log(Mix);
You will get:
When should I use curly braces for ES6 import?
The brackets are golden when you need only specific components from the module, which makes smaller footprints for bundlers like webpack.
var isEqual = function(f,s) {
if (f === s) return true;
if (Array.isArray(f)&&Array.isArray(s)) {
return isEqual(f.sort(), s.sort());
}
if (_.isObject(f)) {
return isEqual(f, s);
}
return _.isEqual(f, s);
};
If you want to control the level of transparency you can use rgba. where a is the alpha. 0 for transparent and 1 for opaque. Make sure that final output file must have .png extension for transparency.
convert
test.png
-channel rgba
-matte
-fuzz 40%
-fill "rgba(255,255,255,0.5)"
-opaque "rgb(255,255,255)"
semi_transparent.png
supervised learning
supervised learning is where we know the output of the raw input, i.e the data is labelled so that during the training of machine learning model it will understand what it need to detect in the give output, and it will guide the system during the training to detect the pre-labelled objects on that basis it will detect the similar objects which we have provided in training.
Here the algorithms will know what's the structure and pattern of data. Supervised learning is used for classification
As an example, we can have a different objects whose shapes are square, circle, trianle our task is to arrange the same types of shapes the labelled dataset have all the shapes labelled, and we will train the machine learning model on that dataset, on the based of training dateset it will start detecting the shapes.
Un-supervised learning
Unsupervised learning is a unguided learning where the end result is not known, it will cluster the dataset and based on similar properties of the object it will divide the objects on different bunches and detect the objects.
Here algorithms will search for the different pattern in the raw data, and based on that it will cluster the data. Un-supervised learning is used for clustering.
As an example, we can have different objects of multiple shapes square, circle, triangle, so it will make the bunches based on the object properties, if a object has four sides it will consider it square, and if it have three sides triangle and if no sides than circle, here the the data is not labelled, it will learn itself to detect the various shapes
Program to an interface allows to change implementation of contract defined by interface seamlessly. It allows loose coupling between contract and specific implementations.
IInterface classRef = new ObjectWhatever()
You could use any class that implements IInterface? When would you need to do that?
Have a look at this SE question for good example.
Why should the interface for a Java class be preferred?
does using an Interface hit performance?
if so how much?
Yes. It will have slight performance overhead in sub-seconds. But if your application has requirement to change the implementation of interface dynamically, don't worry about performance impact.
how can you avoid it without having to maintain two bits of code?
Don't try to avoid multiple implementations of interface if your application need them. In absence of tight coupling of interface with one specific implementation, you may have to deploy the patch to change one implementation to other implementation.
One good use case: Implementation of Strategy pattern:
When indicating HTTP Basic Authentication we return something like:
WWW-Authenticate: Basic realm="myRealm"
Whereas Basic
is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.
You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.
From recollection, Windows Challenge Response uses a different scheme and different arguments.
The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.
My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.
For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.
Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.
The other alternative is burn the AJAX request but that's a poor user experience.
why don't you try this?
password="your password"
username="username"
Ip="<IP>"
sshpass -p "$password" scp /<PATH>/final.txt $username@$Ip:/root/<PATH>
If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.
https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html
This error might occur when you return an object instead of a string in your __unicode__
method. For example:
class Author(models.Model):
. . .
name = models.CharField(...)
class Book(models.Model):
. . .
author = models.ForeignKey(Author, ...)
. . .
def __unicode__(self):
return self.author # <<<<<<<< this causes problems
To avoid this error you can cast the author instance to unicode:
class Book(models.Model):
. . .
def __unicode__(self):
return unicode(self.author) # <<<<<<<< this is OK
You have to do binding in a directive. Look at this:
angular.module('ng', []).
directive('sliderRange', function($parse, $timeout){
return {
restrict: 'A',
replace: true,
transclude: false,
compile: function(element, attrs) {
var html = '<div class="slider-range"></div>';
var slider = $(html);
element.replaceWith(slider);
var getterLeft = $parse(attrs.ngModelLeft), setterLeft = getterLeft.assign;
var getterRight = $parse(attrs.ngModelRight), setterRight = getterRight.assign;
return function (scope, slider, attrs, controller) {
var vsLeft = getterLeft(scope), vsRight = getterRight(scope), f = vsLeft || 0, t = vsRight || 10;
var processChange = function() {
var vs = slider.slider("values"), f = vs[0], t = vs[1];
setterLeft(scope, f);
setterRight(scope, t);
}
slider.slider({
range: true,
min: 0,
max: 10,
step: 1,
change: function() { setTimeout(function () { scope.$apply(processChange); }, 1) }
}).slider("values", [f, t]);
};
}
};
});
This shows you an example of a slider range, done with jQuery UI. Example usage:
<div slider-range ng-model-left="question.properties.range_from" ng-model-right="question.properties.range_to"></div>
EntityManager interface is similar to sessionFactory in hibernate. EntityManager under javax.persistance package but session and sessionFactory under org.hibernate.Session/sessionFactory package.
Entity manager is JPA specific and session/sessionFactory are hibernate specific.
Use jQuery
html
<div id="b"> </div>
css
div#b {
position: fixed;
top:40px;
left:0;
width: 40px;
height: 40px;
background: url(http://www.wiredforwords.com/IMAGES/FlyingBee.gif) 0 0 no-repeat;
}
script
var b = function($b,speed){
$b.animate({
"left": "50%"
}, speed);
};
$(function(){
b($("#b"), 5000);
});
see jsfiddle http://jsfiddle.net/vishnurajv/Q4Jsh/
SELECT art.* , sec.section.title, cat.title, use1.name, use2.name as modifiedby
FROM article art
INNER JOIN section sec ON art.section_id = sec.section.id
INNER JOIN category cat ON art.category_id = cat.id
INNER JOIN user use1 ON art.author_id = use1.id
LEFT JOIN user use2 ON art.modified_by = use2.id
WHERE art.id = '1';
Hope This Might Help
So, rather return the whole object
first, just wrap it to json_encode
and then return it. This will return a proper and valid object.
public function id($id){
$promotion = Promotion::find($id);
return json_encode($promotion);
}
Or, For DB this will be just like,
public function id($id){
$promotion = DB::table('promotions')->first();
return json_encode($promotion);
}
I think it may help someone else.
CMD:
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
reg query HKEY_CURRENT_USER\Environment
PowerShell:
Get-Item "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Get-Item HKCU:\Environment
Powershell/.NET: (see EnvironmentVariableTarget Enum)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)
Try cast (columnName as unsigned)
unsigned is positive value only
If you want to include negative value, then cast (columnName as signed)
,
The difference between sign (negative include) and unsigned (twice the size of sign, but non-negative)
Best answer is great, short and on point, but I would like to put my pennyworth.
Basically npm start and ng serve can be used interchangeably in Angular projects as long as you do not want the command to do additional stuff. Let me elaborate on this one.
For example you may want to configure your proxy in package.json start script like this: "start": "ng serve --proxy-config proxy.config.json",
Obviously sole use of ng serve will not be enough.
Another instance is when instead of using the defaults you need to use some additional options ad hoc like define the temporary port: ng serve --port 4444
Some parameters are only available to ng serve, others to npm start. Notice that port option works for both, so in that case it is up to your taste, again. :)
->List all the packages by :
adb shell su 0 pm list packages -f
->Search for your package name by holding keys "ctrl+alt+f".
->Once found, look for the location associated with it.
ES2017/8 for Node 7.6+ with a temporary write file for atomic replacement.
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))
async function replaceRegexInFile(file, search, replace){
let contents = await fs.readFileAsync(file, 'utf8')
let replaced_contents = contents.replace(search, replace)
let tmpfile = `${file}.jstmpreplace`
await fs.writeFileAsync(tmpfile, replaced_contents, 'utf8')
await fs.renameAsync(tmpfile, file)
return true
}
Note, only for smallish files as they will be read into memory.
DAO provides abstraction on database/data files or any other persistence mechanism so that, persistence layer could be manipulated without knowing its implementation details.
Whereas in Repository classes, multiple DAO classes can be used inside a single Repository method to get an operation done from "app perspective". So, instead of using multiple DAO at Domain layer, use repository to get it done. Repository is a layer which may contain some application logic like: If data is available in in-memory cache then fetch it from cache otherwise, fetch data from network and store it in in-memory cache for next time retrieval.
The datatool package offers a nice way to sort bibliography by an arbitrary criterion, by converting it first into some database format.
Short example, taken from here and posted for the record:
\documentclass{article}
\usepackage{databib}
\begin{document}
% First argument is the name of new datatool database
% Second argument is list of .bib files
\DTLloadbbl{mybibdata}{acmtr}
% Sort database in order of year starting from most recent
\DTLsort{Year=descending}{mybibdata}
% Add citations
\nocite{*}
% Display bibliography
\DTLbibliography{mybibdata}
\end{document}
You can generate NPM dependency trees without the need of installing a dependency by using the command
npm list
This will generate a dependency tree for the project at the current directory and print it to the console.
You can get the dependency tree of a specific dependency like so:
npm list [dependency]
You can also set the maximum depth level by doing
npm list --depth=[depth]
Note that you can only view the dependency tree of a dependency that you have installed either globally, or locally to the NPM project.
Elements()
will only check direct children - which in the first case is the root element, in the second case children of the root element, hence you get a match in the second case. If you just want any matching descendant use Descendants()
instead:
var query = from c in xmlFile.Descendants("Band") select c;
Also I would suggest you re-structure your Xml: The band name should be an attribute or element value, not the element name itself - this makes querying (and schema validation for that matter) much harder, i.e. something like this:
<Band>
<BandProperties Name ="Doors" ID="222" started="1968" />
<Description>regular Band<![CDATA[lalala]]></Description>
<Last>1</Last>
<Salary>2</Salary>
</Band>
I've implemented this to send Cyrillic e-mails through my MS Exchange server.
function to_base64(t in varchar2) return varchar2 is
begin
return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
end to_base64;
Try it.
upd: after a minor adjustment I came up with this, so it works both ways now:
function from_base64(t in varchar2) return varchar2 is
begin
return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(t)));
end from_base64;
You can check it:
SQL> set serveroutput on
SQL>
SQL> declare
2 function to_base64(t in varchar2) return varchar2 is
3 begin
4 return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
5 end to_base64;
6
7 function from_base64(t in varchar2) return varchar2 is
8 begin
9 return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw (t)));
10 end from_base64;
11
12 begin
13 dbms_output.put_line(from_base64(to_base64('asdf')));
14 end;
15 /
asdf
PL/SQL procedure successfully completed
upd2: Ok, here's a sample conversion that works for CLOB
I just came up with. Try to work it out for your blobs. :)
declare
clobOriginal clob;
clobInBase64 clob;
substring varchar2(2000);
n pls_integer := 0;
substring_length pls_integer := 2000;
function to_base64(t in varchar2) return varchar2 is
begin
return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
end to_base64;
function from_base64(t in varchar2) return varchar2 is
begin
return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(t)));
end from_base64;
begin
select clobField into clobOriginal from clobTable where id = 1;
while true loop
/*we substract pieces of substring_length*/
substring := dbms_lob.substr(clobOriginal,
least(substring_length, substring_length * n + 1 - length(clobOriginal)),
substring_length * n + 1);
/*if no substring is found - then we've reached the end of blob*/
if substring is null then
exit;
end if;
/*convert them to base64 encoding and stack it in new clob vadriable*/
clobInBase64 := clobInBase64 || to_base64(substring);
n := n + 1;
end loop;
n := 0;
clobOriginal := null;
/*then we do the very same thing backwards - decode base64*/
while true loop
substring := dbms_lob.substr(clobInBase64,
least(substring_length, substring_length * n + 1 - length(clobInBase64)),
substring_length * n + 1);
if substring is null then
exit;
end if;
clobOriginal := clobOriginal || from_base64(substring);
n := n + 1;
end loop;
/*and insert the data in our sample table - to ensure it's the same*/
insert into clobTable (id, anotherClobField) values (1, clobOriginal);
end;
If the children have FKs linking them to the parent, then you can use DELETE CASCADE on the parent.
e.g.
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE
);
Delete the supplier, and it will delate all products for that supplier
This works and gives you the installed at path for each gem. This super helpful when trying to do multi-stage docker builds.. You can copy in the specific directory post-bundle install.
bash-4.4# gem list -d
Output::
aasm (5.0.6)
Authors: Thorsten Boettger, Anil Maurya
Homepage: https://github.com/aasm/aasm
License: MIT
Installed at: /usr/local/bundle
State machine mixin for Ruby objects
Well, it partly depends what you want to happen if you're actually in a derived class.
For example, suppose SuperClass
is in A.jar and SubClass
is in B.jar, and you're executing code in an instance method declared in SuperClass
but where this
refers to an instance of SubClass
. If you use this.getClass().getResource()
it will look relative to SubClass
, in B.jar. I suspect that's usually not what's required.
Personally I'd probably use Foo.class.getResourceAsStream(name)
most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo
, that's the most robust way of doing it IMO.
Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.
update Angular 5
ngOutletContext
was renamed to ngTemplateOutletContext
See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
original
Templates (<template>
, or <ng-template>
since 4.x) are added as embedded views and get passed a context.
With let-col
the context property $implicit
is made available as col
within the template for bindings.
With let-foo="bar"
the context property bar
is made available as foo
.
For example if you add a template
<ng-template #myTemplate let-col let-foo="bar">
<div>{{col}}</div>
<div>{{foo}}</div>
</ng-template>
<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
[ngTemplateOutletContext]="{
$implicit: 'some col value',
bar: 'some bar value'
}"
></ng-template>
See also this answer and ViewContainerRef#createEmbeddedView.
*ngFor
also works this way. The canonical syntax makes this more obvious
<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
<div>{{item}}</div>
</ng-template>
where NgFor
adds the template as embedded view to the DOM for each item
of items
and adds a few values (item
, index
, odd
) to the context.
You should use python Explicit Conversion Flag PEP-3101
'My name is {0!s:10} {1}'.format('Dunkin', 'Donuts')
'My name is Dunkin Donuts'
or
'My name is %-10s %s' % ('Dunkin', 'Donuts')
'My name is Dunkin Donuts'
It's another way of Git telling you:
Hey, I see you made some changes, but keep in mind that when you write pages to my history, those changes won't be in these pages.
Changes to files are not staged if you do not explicitly git add
them (and this makes sense).
So when you git commit
, those changes won't be added since they are not staged. If you want to commit them, you have to stage them first (ie. git add
).
First thing first. set the column in which you are working in by clicking on format cells->number-> date and then format e.g Jan-16 representing Jan, 1, 2016. and then apply either of the formulas above.
Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
Left outer join -
A left outer join will give all rows in A, plus any common rows in B.
Full outer join -
A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa.
check this
Python 2.7.9 auto promotes numbers. For a case where one is unsure to use int() or long().
>>> a = int("123")
>>> type(a)
<type 'int'>
>>> a = int("111111111111111111111111111111111111111111111111111")
>>> type(a)
<type 'long'>
Adjust this shell script for automatic merging two branches.
You do not have Gemfile
in a directory where you run that command.
Gemfile
is a file containing your gem
settings for a current program.
I did Anagram excersize, which is like Count Change problem but with 50 000 denominations (coins). I am not sure that it can be done iteratively, I do not care. I just know that the -xss option had no effect -- I always failed after 1024 stack frames (might be scala does bad job delivering to to java or printStackTrace limitation. I do not know). This is bad option, as explained anyway. You do not want all threads in to app to be monstrous. However, I did some experiments with new Thread (stack size). This works indeed,
def measureStackDepth(ss: Long): Long = {
var depth: Long = 0
val thread: Thread = new Thread(null, new Runnable() {
override def run() {
try {
def sum(n: Long): Long = {depth += 1; if (n== 0) 0 else sum(n-1) + 1}
println("fact = " + sum(ss * 10))
} catch {
case e: StackOverflowError => // eat the exception, that is expected
}
}
}, "deep stack for money exchange", ss)
thread.start()
thread.join()
depth
} //> measureStackDepth: (ss: Long)Long
for (ss <- (0 to 10)) println("ss = 10^" + ss + " allows stack of size " -> measureStackDepth((scala.math.pow (10, ss)).toLong) )
//> fact = 10
//| (ss = 10^0 allows stack of size ,11)
//| fact = 100
//| (ss = 10^1 allows stack of size ,101)
//| fact = 1000
//| (ss = 10^2 allows stack of size ,1001)
//| fact = 10000
//| (ss = 10^3 allows stack of size ,10001)
//| (ss = 10^4 allows stack of size ,1336)
//| (ss = 10^5 allows stack of size ,5456)
//| (ss = 10^6 allows stack of size ,62736)
//| (ss = 10^7 allows stack of size ,623876)
//| (ss = 10^8 allows stack of size ,6247732)
//| (ss = 10^9 allows stack of size ,62498160)
You see that stack can grow exponentially deeper with exponentially more stack alloted to the thread.
There are a least these apt-get
extension packages that can help:
apt-offline - offline apt package manager
apt-zip - Update a non-networked computer using apt and removable media
This is specifically for the case of wanting to download where you have network access but to install on another machine where you do not.
Otherwise, the --download-only
option to apt-get
is your friend:
-d, --download-only
Download only; package files are only retrieved, not unpacked or installed.
Configuration Item: APT::Get::Download-Only.
I’m tempted to say that both are bad practices.
The use of onclick
or javascript:
should be dismissed in favor of listening to events from outside scripts, allowing for a better separation between markup and logic and thus leading to less repeated code.
Note also that external scripts get cached by the browser.
Have a look at this answer.
Some good ways of implementing cross-browser event listeners here.
The link to the help page is the same for python 2.6 and as far as I know there was no change in the csv module since 2.5 (besides bug fixes). Here is the code that just works without any encoding/decoding (file da.csv contains the same data as the variable data). I assume that your file should be read correctly without any conversions.
test.py:
## -*- coding: utf-8 -*-
#
# NOTE: this first line is important for the version b) read from a string(unicode) variable
#
import csv
data = \
"""0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert"""
# a) read from a file
print 'reading from a file:'
for (f1, f2, f3) in csv.reader(open('da.csv'), dialect=csv.excel):
print (f1, f2, f3)
# b) read from a string(unicode) variable
print 'reading from a list of strings:'
reader = csv.reader(data.split('\n'), dialect=csv.excel)
for (f1, f2, f3) in reader:
print (f1, f2, f3)
da.csv:
0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert
Try this:
if cookie and not cookie.isspace():
# the string is non-empty
else:
# the string is empty
The above takes in consideration the cases where the string is None
or a sequence of white spaces.
I came across the same issue.
I found that it is easy to group by any minute interval is just dividing epoch by minutes in amount of seconds and then either rounding or using floor to get ride of the remainder. So if you want to get interval in 5 minutes you would use 300 seconds.
SELECT COUNT(*) cnt,
to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300)
AT TIME ZONE 'UTC' as interval_alias
FROM TABLE_NAME GROUP BY interval_alias
interval_alias cnt
------------------- ----
2010-11-16 10:30:00 2
2010-11-16 10:35:00 10
2010-11-16 10:45:00 8
2010-11-16 10:55:00 11
This will return the data correctly group by the selected minutes interval; however, it will not return the intervals that don't contains any data. In order to get those empty intervals we can use the function generate_series.
SELECT generate_series(MIN(date_trunc('hour',timestamp_column)),
max(date_trunc('minute',timestamp_column)),'5m') as interval_alias FROM
TABLE_NAME
Result:
interval_alias
-------------------
2010-11-16 10:30:00
2010-11-16 10:35:00
2010-11-16 10:40:00
2010-11-16 10:45:00
2010-11-16 10:50:00
2010-11-16 10:55:00
Now to get the result with interval with zero occurrences we just outer join both result sets.
SELECT series.minute as interval, coalesce(cnt.amnt,0) as count from
(
SELECT count(*) amnt,
to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300)
AT TIME ZONE 'UTC' as interval_alias
from TABLE_NAME group by interval_alias
) cnt
RIGHT JOIN
(
SELECT generate_series(min(date_trunc('hour',timestamp_column)),
max(date_trunc('minute',timestamp_column)),'5m') as minute from TABLE_NAME
) series
on series.minute = cnt.interval_alias
The end result will include the series with all 5 minute intervals even those that have no values.
interval count
------------------- ----
2010-11-16 10:30:00 2
2010-11-16 10:35:00 10
2010-11-16 10:40:00 0
2010-11-16 10:45:00 8
2010-11-16 10:50:00 0
2010-11-16 10:55:00 11
The interval can be easily changed by adjusting the last parameter of generate_series. In our case we use '5m' but it could be any interval we want.
This can also happen when you're trying to load a DLL and that in turn needs another DLL which cannot be not found.
Try to see if SQL snap-ins are present:
get-pssnapin -Registered
Name : SqlServerCmdletSnapin100
PSVersion : 2.0
Description : This is a PowerShell snap-in that includes various SQL Server cmdlets.
Name : SqlServerProviderSnapin100
PSVersion : 2.0
Description : SQL Server Provider
If so
Add-PSSnapin SqlServerCmdletSnapin100 # here lives Invoke-SqlCmd
Add-PSSnapin SqlServerProviderSnapin100
then you can do something like this:
invoke-sqlcmd -inputfile "c:\mysqlfile.sql" -serverinstance "servername\serverinstance" -database "mydatabase" # the parameter -database can be omitted based on what your sql script does.
After downloading all the libraries said by ezaoutis, the error message on my windows 10 persisted, reading the wampserver3.1.3 installation requirements, there was a verification tool called check_vcredist.exe , i ran it and it show me all the missing libraries and it's download links, so i finally could install it succesfully.
I know this is an old question but I want to share an example that I think explains bounded wildcards pretty well. java.util.Collections
offers this method:
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
If we have a List of T
, the List can, of course, contain instances of types that extend T
. If the List contains Animals, the List can contain both Dogs and Cats (both Animals). Dogs have a property "woofVolume" and Cats have a property "meowVolume." While we might like to sort based upon these properties particular to subclasses of T
, how can we expect this method to do that? A limitation of Comparator is that it can compare only two things of only one type (T
). So, requiring simply a Comparator<T>
would make this method usable. But, the creator of this method recognized that if something is a T
, then it is also an instance of the superclasses of T
. Therefore, he allows us to use a Comparator of T
or any superclass of T
, i.e. ? super T
.
I was searching for the same thing, my solution was this:
$('#el-id').focus().select();
I just went through this issue and none of the suggestions solved my problem. While I was unable to start MySQL on boot and found the same message in the logs ("Another MySQL daemon already running with the same unix socket"), I was able to start the service once I arrived at the console.
In my configuration file, I found the following line: bind-address=xx.x.x.x
. I randomly decided to comment it out, and the error on boot disappeared. Because the bind address provides security, in a way, I decided to explore it further. I was using the machine's IP address, rather than the IPv4 loopback address - 127.0.0.1
.
In short, by using 127.0.0.1
as the bind-address
, I was able to fix this error. I hope this helps those who have this problem, but are unable to resolve it using the answers detailed above.
Please Find below code
select trim(string_agg(value,' ')) from STRING_SPLIT(' single spaces only ',' ')
where value<>' '
This worked for me.. Hope this helps...
You can access those values with the global $_GET variable
//www.example.com/index.php?id=7
print $_GET['id']; // prints "7"
You should check all "incoming" user data - so here, that "id" is an INT. Don't use it directly in your SQL (vulnerable to SQL injections).
First, I would try and refactor these tables to get away from using phone numbers as natural keys. I am not a fan of natural keys and this is a great example why. Natural keys, especially things like phone numbers, can change and frequently so. Updating your database when that change happens will be a HUGE, error-prone headache. *
Method 1 as you describe it is your best bet though. It looks a bit terse due to the naming scheme and the short aliases but... aliasing is your friend when it comes to joining the same table multiple times or using subqueries etc.
I would just clean things up a bit:
SELECT t.PhoneNumber1, t.PhoneNumber2,
t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2
FROM Table1 t
JOIN Table2 t1 ON t1.PhoneNumber = t.PhoneNumber1
JOIN Table2 t2 ON t2.PhoneNumber = t.PhoneNumber2
What i did:
*One way DBAs avoid the headaches of updating natural keys is to not specify primary keys and foreign key constraints which further compounds the issues with poor db design. I've actually seen this more often than not.
I use printf, is shorter as it doesn't need flags to do the work:
printf "\rMy static $myvars composed text"
this should be it try it.
document.getElementById("test").style.display="none";
You can use str.zfill
:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
prints:
01
10
100
@littleguy23 That is correct, but you don't want to do it to multi select. So just a small change to the code:
$(document).ready(function() {
// Select - Single
$('select:not([multiple])').material_select();
});
height:100% works if the parent container has a specified height property else, it won't work
I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.
Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))
I have tried accepted answer but it isn't seems working on my end and I don't know how the accepted answer suppose to work.
$('#modalId').on('hidden.bs.modal', function () {
$(this).remove();
})
This is working perfectly fine on my side. BS Version > 3
Why not just select the Table and view the variable that way?
SELECT * FROM @d
Using CSS touch-events: none Completly takes out all the touch events. Just leaving this here in case someone also has this problems, took me 2 hours to find this solution and it's only one line of css. https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action
Run the below commands
git log
From this you will get your last push commit hash key
git reset --hard <your commit hash key>
Here is a Github link to a lightweight and very easy to integrate library that enables you to play with borders as you want for any widget you want, simply based on a FrameLayout widget.
Here is a quick sample code for you to see how easy it is, but you will find more information on the link.
<com.khandelwal.library.view.BorderFrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:leftBorderColor="#00F0F0"
app:leftBorderWidth="10dp"
app:topBorderColor="#F0F000"
app:topBorderWidth="15dp"
app:rightBorderColor="#F000F0"
app:rightBorderWidth="20dp"
app:bottomBorderColor="#000000"
app:bottomBorderWidth="25dp" >
</com.khandelwal.library.view.BorderFrameLayout>
So, if you don't want borders on bottom, delete the two lines about bottom in this custom widget, and that's done.
And no, I'm neither the author of this library nor one of his friend ;-)
Try this
$(document).ready(function(){
var form=$("#myForm");
$("#smt").click(function(){
$.ajax({
type:"POST",
url:form.attr("action"),
data:$("#myForm input").serialize(),//only input
success: function(response){
console.log(response);
}
});
});
});
Just change convert datetime to time that should do the trick:
SELECT timeEvent
FROM tbEvents
WHERE convert(time, startHour) >= convert(time, @startHour)
What I like to do is completely remove the control using Angular2 then it's reloaded when the next song has an audio path:
<audio id="audioplayer" *ngIf="song?.audio_path">
Then when I want to unload it in code I do this:
this.song = Object.assign({},this.song,{audio_path: null});
When the next song is assigned, the control gets completely recreated from scratch:
this.song = this.songOnDeck;
You can just pass it
def my_function(my_data):
my_data["schoolname"] = "something"
print my_data
or if you really want to
def my_function(**kwargs):
kwargs["schoolname"] = "something"
print kwargs
You can do this instead too:
tasklist | find /I "test.exe" > nul && taskkill /f /im test.exe > nul
In your androidmanifest.xml file:
<activity android:name="MainActivity" android:configChanges="keyboardHidden|orientation">
or
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
I use this to avoid negative interval.
var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;
I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.
select CONVERT(bigint,'60') as seconds
and it returns
60
You urls are not in the same repository, so you can't do it with the svn diff
command.
svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'
Another way you could do it, is export each repos using svn export
, and then use the diff command to compare the 2 directories you exported.
// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2
// Compare exported directories
diff repos1 repos2 > file.diff
Okay. If you do not want to store the file in database and store in the application, like assets (custom folder), you can define non-db instance variable defined by attr_accessor: document and use form_for - f.file_field
to get the file,
In controller,
@person = Person.new(person_params)
Here person_params
return whitelisted params[:person]
(define yourself)
Save file as,
dir = "#{Rails.root}/app/assets/custom_path"
FileUtils.mkdir(dir) unless File.directory? dir
document = @person.document.document_file_name # check document uploaded params
File.copy_stream(@font.document, "#{dir}/#{document}")
Note, Add this path in .gitignore
& if you want to use this file again add this path asset_path
an of application by application.rb
Whenever form read file field, it get store in tmp folder, later you can store at your place, I gave example to store at assets
note: Storing files like this will increase the size of the application, better to store in the database using paperclip
.
If you do not have the pandas and sqlalchemy libraries, import using pip
pip install pandas
pip install sqlalchemy
We can use pandas and sqlalchemy to directly insert into the database
import csv
import pandas as pd
from sqlalchemy import create_engine, types
engine = create_engine('mysql://root:*Enter password here*@localhost/*Enter Databse name here*') # enter your password and database names here
df = pd.read_csv("Excel_file_name.csv",sep=',',quotechar='\'',encoding='utf8') # Replace Excel_file_name with your excel sheet name
df.to_sql('Table_name',con=engine,index=False,if_exists='append') # Replace Table_name with your sql table name
PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC
tells PDO to return the result as an associative array.
The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:
Array
(
[email] => '[email protected]'
[password] => 'yourpassword'
)
To read data from the 'email' column, do:
$user['email'];
and for 'password':
$user['password'];
Using indexOf(it doesn’t work with IE8).
if (['apple', 'cherry', 'orange', 'banana'].indexOf(value) >= 0) {
// found
}
To support IE8, you could implement Mozilla’s indexOf.
if (!Array.prototype.indexOf) {
// indexOf polyfill code here
}
Regular Expressions via String.prototype.match (docs).
if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {
}
Use:
+ scale_y_continuous(labels = scales::percent)
Or, to specify formatting parameters for the percent:
+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))
(the command labels = percent
is obsolete since version 2.2.1 of ggplot2)
In Swift 4
let array:[String] = ["Apple", "Pear ","Orange"]
array.joined(separator: " ")
Underscore-java library contains methods push(values), pop(), shift() and unshift(values).
Code example:
import com.github.underscore.U:
List<String> strings = Arrays.asList("one", "two", " three");
List<String> newStrings = U.push(strings, "four", "five");
// ["one", " two", "three", " four", "five"]
String newPopString = U.pop(strings).fst();
// " three"
String newShiftString = U.shift(strings).fst();
// "one"
List<String> newUnshiftStrings = U.unshift(strings, "four", "five");
// ["four", " five", "one", " two", "three"]
Replace double quotes with single ones:
INSERT
INTO MY.LOGFILE
(id,severity,category,logdate,appendername,message,extrainfo)
VALUES (
'dee205e29ec34',
'FATAL',
'facade.uploader.model',
'2013-06-11 17:16:31',
'LOGDB',
NULL,
NULL
)
In SQL, double quotes are used to mark identifiers, not string constants.
Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")
Or, in a more structured way...
Sub openwb()
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"
Set wb = Workbooks.Open(sFile)
End Sub
The problem with the css3 scroll bars is that, interaction can only be performed on the content. we can't interact with the scroll bar on touch devices.
We use a sonicwall vpn. It launches a java applet that launches mstc with all the credentials setup. You really can't do this without a java applet or activex plugin.
Microsoft uses this technique itself on their small business server for getting inside the network. I wouldn't say it is a terrible idea, as long as platform independence isn't important.
upper-case(string) and lower-case(string)
This one
if [[ ! $(cat /etc/passwd | grep "sysa") ]]
Then echo " something"
exit 2
fi
For those who are able to access cpanel, there is a simpler way getting around it.
log in cpanel => "Remote MySQL" under DATABASES section:
Add the IPs / hostname which you are accessing from
done!!!
0755
= User:rwx
Group:r-x
World:r-x
0750
= User:rwx
Group:r-x
World:---
(i.e. World: no access)
r = read
w = write
x = execute (traverse for directories)
In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
you can use this . it's so easy to understand : by https://developer.android
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:text="Tom"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="24sp" />
<TextView
android:text="Tim"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="24sp" />
<TextView
android:text="Todd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="24sp" />
</LinearLayout>
As @Sugrue I'm also digging out an old thread.
To explain why there is 32768 (I think it should be 32767, but lets believe experimental testing result) characters limitation we need to dig into Windows API.
No matter how you launch program with command line arguments it goes to ShellExecute, CreateProcess or any extended their version. These APIs basically wrap other NT level API that are not officially documented. As far as I know these calls wrap NtCreateProcess, which requires OBJECT_ATTRIBUTES structure as a parameter, to create that structure InitializeObjectAttributes is used. In this place we see UNICODE_STRING
. So now lets take a look into this structure:
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING;
It uses USHORT
(16-bit length [0; 65535]) variable to store length. And according this, length indicates size in bytes, not characters. So we have: 65535 / 2 = 32767
(because WCHAR
is 2 bytes long).
There are a few steps to dig into this number, but I hope it is clear.
Also, to support @sunetos answer what is accepted. 8191 is a maximum number allowed to be entered into cmd.exe
, if you exceed this limit, The input line is too long.
error is generated. So, answer is correct despite the fact that cmd.exe
is not the only way to pass arguments for new process.
You can find the sample code on the wikibooks link
/**************************************************************
* A simpler and shorter implementation of ls(1)
* ls(1) is very similar to the DIR command on DOS and Windows.
**************************************************************/
#include <stdio.h>
#include <dirent.h>
int listdir(const char *path)
{
struct dirent *entry;
DIR *dp;
dp = opendir(path);
if (dp == NULL)
{
perror("opendir");
return -1;
}
while((entry = readdir(dp)))
puts(entry->d_name);
closedir(dp);
return 0;
}
int main(int argc, char **argv) {
int counter = 1;
if (argc == 1)
listdir(".");
while (++counter <= argc) {
printf("\nListing %s...\n", argv[counter-1]);
listdir(argv[counter-1]);
}
return 0;
}
Add this statement into AppDelegate.h
//whether to allow cross screen marker
@property (nonatomic, assign) allowRotation BOOL;
Write down this section of code into AppDelegate.m
- (UIInterfaceOrientationMask) application: (UIApplication *) supportedInterfaceOrientationsForWindow: application (UIWindow *) window {
If (self.allowRotation) {
UIInterfaceOrientationMaskAll return;
}
UIInterfaceOrientationMaskPortrait return;
}
Change the allowRotation
property of delegate app
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps
$("#gst_show>input").change(function(){
var checked = $(this).is(":checked");
if($("#gst_show>input:checkbox").attr("checked",checked)){
alert('Checked Successfully');
}
});
Above solutions should solve your problem. If these do not, make sure you update your Android sdk using SDK manager and install the latest lib project and then repeat the above steps again.
"If I want two columns for anything over 768px, should I apply both classes?"
This should be as simple as:
<div class="row">
<div class="col-sm-6"></div>
<div class="col-sm-6"></div>
</div>
No need to add the col-lg-6
too.
In CI v3, you can try:
function partial_uri($start = 0) {
return join('/',array_slice(get_instance()->uri->segment_array(), $start));
}
This will drop the number of URL segments specified by the $start
argument. If your URL is http://localhost/dropbox/derrek/shopredux/ahahaha/hihihi
, then:
partial_uri(3); # returns "ahahaha/hihihi"
I believe you simply call PrivateImpl
what it is: a non-public top-level class
. You can also declare non-public top-level interfaces
as well.
e.g., elsewhere on SO: Non-public top-level class vs static nested class
As for changes in behavior between versions, there was this discussion about something that "worked perfectly" in 1.2.2. but stopped working in 1.4 in sun's forum: Java Compiler - unable to declare a non public top level classes in a file.
I believe +%s
is seconds since epoch. It's timezone invariant.
Here's what I do:
curl https://raw.githubusercontent.com/creationix/nvm/v0.20.0/install.sh | bash
cd / && . ~/.nvm/nvm.sh && nvm install 0.10.35
. ~/.nvm/nvm.sh && nvm alias default 0.10.35
No Homebrew for this one.
nvm
soon will support io.js, but not at time of posting: https://github.com/creationix/nvm/issues/590
Then install everything else, per-project, with a package.json
and npm install
.
The above formatting approach works but only for three levels. The above used KB, MB, and GB. Here I've expanded it to six. Right-click on the cell(s) and select Format Cells. Under the Number tab, select Custom. Then in the Type: box, put the following:
[<1000]##0.00" B";[<1000000]##0.00," KB";##0.00,," MB"
Then select OK. This covers B, KB, and MB. Then, with the same cells selected, click Home ribbon, Conditional Formatting, New Rule. Select Format only cells that contain. Then below in the rule description, Format only cells with, Cell Value, greater than or equal to, 1000000000 (that's 9 zeros.) Then click on Format, Number tab, Custom, and in the Type: box, put the following:
[<1000000000000]##0.00,,," GB";[<1000000000000000]##0.00,,,," TB";#,##0.00,,,,," PB"
Select OK, and OK. This conditional formatting will take over only if the value is bigger than 1,000,000,000. And it will take care of the GB, TB, and PB ranges.
567.00 B
5.67 KB
56.70 KB
567.00 KB
5.67 MB
56.70 MB
567.00 MB
5.67 GB
56.70 GB
567.00 GB
5.67 TB
56.70 TB
567.00 TB
5.67 PB
56.70 PB
Anything bigger than PB will just show up as a bigger PB, e.g. 56,700 PB. You could add another conditional formatting to handle even bigger values, EB, and so on.
.hide() does not work in Chrome for me.
This works for hiding:
var pctDOM = jQuery("#vr-preview-progress-content")[0];
pctDOM.hidden = true;
<%= link_to root_path do %><%= image_tag("Search.png",:alt=>'Vivek',:title=>'Vivek',:class=>'dock-item')%><%= content_tag(:span, "Search").html_safe%><% end %>
Since you are using Java, printf
is available from version 1.5
You may use it like this
System.out.printf("%03d ", x);
For Example:
System.out.printf("%03d ", 5);
System.out.printf("%03d ", 55);
System.out.printf("%03d ", 555);
Will Give You
005 055 555
as output
See: System.out.printf
and Format String Syntax
[System.Diagnostics.FileVersionInfo]::GetVersionInfo("Path\To\File.dll")
As mentioned by ecdpalma below, git 1.7.12+ (August 2012) has enhanced the option --root
for git rebase
:
"git rebase [-i] --root $tip
" can now be used to rewrite all the history leading to "$tip
" down to the root commit.
That new behavior was initially discussed here:
I personally think "
git rebase -i --root
" should be made to just work without requiring "--onto
" and let you "edit" even the first one in the history.
It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise.
The patch followed.
(original answer, February 2010)
As mentioned in the Git FAQ (and this SO question), the idea is:
git reset --hard
Rebase branch on top of changed commit, using:
git rebase --onto <tmp branch> <commit after changed> <branch>`
The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use filter-branch --tree-filter
to make sure the content of that file does not contain in any commit the sensible information.
In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite.
If one need to use the sp_executesql
with OUTPUT
variables:
EXEC sp_executesql @sql
,N'@p0 INT'
,N'@p1 INT OUTPUT'
,N'@p2 VARCHAR(12) OUTPUT'
,@p0
,@p1 OUTPUT
,@p2 OUTPUT;
If your SQL Server table has a column of type INT IDENTITY
(or BIGINT IDENTITY
), then you can get the latest inserted value using:
INSERT INTO dbo.YourTable(columns....)
VALUES(..........)
SELECT SCOPE_IDENTITY()
This works as long as you haven't inserted another row - it just returns the last IDENTITY
value handed out in this scope here.
There are at least two more options - @@IDENTITY
and IDENT_CURRENT
- read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.
You need to convert your private key to PKCS8 format using following command:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file -nocrypt > pkcs8_key
After this your java program can read it.
From the Design Patterns theory; "encapsulate what varies". By defining a 'getter' there is good adherence to the above principle. So, if the implementation-representation of the member changes in future, the member can be 'massaged' before returning from the 'getter'; implying no code refactoring at the client side where the 'getter' call is made.
Regards,
Check out my fiddle.
http://jsfiddle.net/mohany2712/vaw8k/
.uploadFile {_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
#uploadIcon {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<body>_x000D_
<div class="uploadBox">_x000D_
<label for="uploadFile" id="uploadIcon">_x000D_
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Icon_-_upload_photo_2.svg/512px-Icon_-_upload_photo_2.svg.png" width="20px" height="20px"/>_x000D_
</label>_x000D_
<input type="file" value="upload" id="uploadFile" class="uploadFile" />_x000D_
</div>_x000D_
</body>
_x000D_
Well I tried Nathan Koop's answer and it didn't work for me. I changed it to the following and it did work:
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_name'
It also didn't work if I put USE 'database_name'
nor WHERE table_catalog = 'database_name' AND table_name' = 'table_name'
. I actually will be happy to know why.
Using the BCNF definition
If and only if for every one of its dependencies X ? Y, at least one of the following conditions hold:
and the 3NF definition
If and only if, for each of its functional dependencies X ? A, at least one of the following conditions holds:
whereas
Where
That is, no partial subset (any non trivial subset except the full set) of a candidate key can be functionally dependent on anything other than a superkey.
A table/relation not in BCNF is subject to anomalies such as the update anomalies mentioned in the pizza example by another user. Unfortunately,
An example of the difference can currently be found at "3NF table not meeting BCNF (Boyce–Codd normal form)" on Wikipedia, where the following table meets 3NF but not BCNF because "Tennis Court" (a partial key/prime attribute) depends on "Rate Type" (a partial key/prime attribute that is not a superkey), which is a dependency we could determine by asking the clients of the database, the tennis club:
Today's Tennis Court Bookings (3NF, not BCNF)
Court Start Time End Time Rate Type
------- ---------- -------- ---------
1 09:30 10:30 SAVER
1 11:00 12:00 SAVER
1 14:00 15:30 STANDARD
2 10:00 11:30 PREMIUM-B
2 11:30 13:30 PREMIUM-B
2 15:00 16:30 PREMIUM-A
The table's superkeys are:
S1 = {Court, Start Time}
S2 = {Court, End Time}
S3 = {Rate Type, Start Time}
S4 = {Rate Type, End Time}
S5 = {Court, Start Time, End Time}
S6 = {Rate Type, Start Time, End Time}
S7 = {Court, Rate Type, Start Time}
S8 = {Court, Rate Type, End Time}
ST = {Court, Rate Type, Start Time, End Time}, the trivial superkey
The 3NF problem: The partial key/prime attribute "Court" is dependent on something other than a superkey. Instead, it is dependent on the partial key/prime attribute "Rate Type". This means that the user must manually change the rate type if we upgrade a court, or manually change the court if wanting to apply a rate change.
(In technical terms, we cannot guarantee that the "Rate Type" -> "Court" functional dependency will not be violated.)
The BCNF solution: If we want to place the above table in BCNF we can decompose the given relation/table into the following two relations/tables (assuming we know that the rate type is dependent on only the court and membership status, which we could discover by asking the clients of our database, the owners of the tennis club):
Rate Types (BCNF and the weaker 3NF, which is implied by BCNF)
Rate Type Court Member Flag
--------- ----- -----------
SAVER 1 Yes
STANDARD 1 No
PREMIUM-A 2 Yes
PREMIUM-B 2 No
Today's Tennis Court Bookings (BCNF and the weaker 3NF, which is implied by BCNF)
Member Flag Court Start Time End Time
----------- ----- ---------- --------
Yes 1 09:30 10:30
Yes 1 11:00 12:00
No 1 14:00 15:30
No 2 10:00 11:30
No 2 11:30 13:30
Yes 2 15:00 16:30
Problem Solved: Now if we upgrade the court we can guarantee the rate type will reflect this change, and we cannot charge the wrong price for a court.
(In technical terms, we can guarantee that the functional dependency "Rate Type" -> "Court" will not be violated.)
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
strstr(request, "favicon") != NULL
Good Question & Matt's was a good answer. To expand on the syntax a little if the oldtable has an identity a user could run the following:
SELECT col1, col2, IDENTITY( int ) AS idcol
INTO #newtable
FROM oldtable
That would be if the oldtable was scripted something as such:
CREATE TABLE [dbo].[oldtable]
(
[oldtableID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[col1] [nvarchar](50) NULL,
[col2] [numeric](18, 0) NULL,
)
None of these suggestions were working for me. I finally found something else I could do - dbms_output.put_line
. For example:
SET SERVEROUTPUT ON
begin
for i in (select dbms_metadata.get_ddl('INDEX', index_name, owner) as ddl from all_indexes where owner = 'MYUSER') loop
dbms_output.put_line(i.ddl);
end loop;
end;
/
Boom. It printed out everything I wanted - no truncating or anything like that. And that works straight in sqlplus
- no need to put it in a separate file or anything.
For python, use the
from selenium.webdriver import ActionChains
and
ActionChains(browser).click(element).perform()
This may have been asked before but:
"every link that specifies target="_new" looks for and finds that window by name, and opens in it.
If you use target="_blank," a brand new window will be created each time, on top of the current window."
from here: http://thedesignspace.net/MT2archives/000316.html
$(this)
and this
aren't the same. The first represents a jQuery object wrapped around your element. The second is just your element. The id
property exists on the element, but not the jQuery object. As such, you have a few options:
Access the property on the element directly:
this.id
Access it from the jQuery object:
$(this).attr("id")
Pull the object out of jQuery:
$(this).get(0).id; // Or $(this)[0].id
Get the id
from the event
object:
When events are raised, for instance a click event, they carry important information and references around with them. In your code above, you have a click event. This event object has a reference to two items: currentTarget
and target
.
Using target
, you can get the id
of the element that raised the event. currentTarget
would simply tell you which element the event is currently bubbling through. These are not always the same.
$("#button").on("click", function(e){ console.log( e.target.id ) });
Of all of these, the best option is to just access it directly from this
itself, unless you're engaged in a series of nested events, then it might be best to use the event
object of each nested event (give them all unique names) to reference elements in higher or lower scopes.
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
You can do:
if not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
else:
do sth. # condition is satisfied
Using a loop:
while not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
do sth. # condition is satisfied
You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer: http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#SetMode
Edit: in case something happens to kill the msdn link, here is the content:
Specifying Document Compatibility Modes
You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.
<html> <head> <!-- Enable IE9 Standards mode --> <meta http-equiv="X-UA-Compatible" content="IE=9" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.
The following example specifies EmulateIE7 mode.
<html> <head> <!-- Mimic Internet Explorer 7 --> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.
In append to JaredPar answer
1-usual ctor, 2nd-function-like-ctor with temporary object.
Compile this source somewhere here http://melpon.org/wandbox/ with different compilers
// turn off rvo for clang, gcc with '-fno-elide-constructors'
#include <stdio.h>
class Thing {
public:
Thing(const char*){puts(__FUNCTION__ );}
Thing(const Thing&){puts(__FUNCTION__ );}
~Thing(){puts(__FUNCTION__);}
};
int main(int /*argc*/, const char** /*argv*/) {
Thing myThing = Thing("asdf");
}
And you will see the result.
From ISO/IEC 14882 2003-10-15
8.5, part 12
Your 1st,2nd construction are called direct-initialization
12.1, part 13
A functional notation type conversion (5.2.3) can be used to create new objects of its type. [Note: The syntax looks like an explicit call of the constructor. ] ... An object created in this way is unnamed. [Note: 12.2 describes the lifetime of temporary objects. ] [Note: explicit constructor calls do not yield lvalues, see 3.10. ]
Where to read about RVO:
12 Special member functions / 12.8 Copying class objects/ Part 15
When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects.
Turn off it with compiler flag from comment to view such copy-behavior)
In Oracle (atleast 11g) database :
If you hit
select to_char(SYSDATE,'Month') from dual;
It gives unformatted month name, with spaces, for e.g. May would be given as 'May '. The string May will have spaces.
In order to format month name, i.e to trim spaces, you need
select to_char(SYSDATE,'fmMonth') from dual;
This would return 'May'.
Thunderbird supports html-body
: mailto:[email protected]?subject=Me&html-body=<b>ME</b>
Just remove the width from both divs.
A div
is a block level element and will use all available space (unless you start floating or positioning them) so the outer div will automatically be 100% wide and the inner div will use all remaining space after setting the left margin.
I have added an example with a textarea
on jsfiddle.
Updated example with an input.
ES6 Update - ES6 (ES2015 specification) allows for default parameters
The following will work just fine in an ES6 (ES015) environment...
function(nodeBox, str="hai")
{
// ...
}
L is a prefix used for wide strings. Each character uses several bytes (depending on the size of wchar_t
). The encoding used is independent from this prefix. I mean it must not be necessarily UTF-16 unlike stated in other answers here.
You don't have to modify bootstrap-responsive by removing @media (max-width:1200px)
...
My application has a max-width
of 1600px. Here's how it worked for me:
Create bootstrap-custom.css - As much as possible, I don't want to override my original bootstrap css.
Inside bootstrap-custom.css, override the container-fluid by including this code:
Like this:
/* set a max-width for horizontal fluid layout and make it centered */
.container-fluid {
margin-right: auto;
margin-left: auto;
max-width: 1600px; /* or 950px */
}
Here is class structure of UIDevice
+ (UIDevice *)currentDevice;
@property(nonatomic,readonly,strong) NSString *name; // e.g. "My iPhone"
@property(nonatomic,readonly,strong) NSString *model; // e.g. @"iPhone", @"iPod touch"
@property(nonatomic,readonly,strong) NSString *localizedModel; // localized version of model
@property(nonatomic,readonly,strong) NSString *systemName; // e.g. @"iOS"
@property(nonatomic,readonly,strong) NSString *systemVersion;
Is there a way to detect if a key is currently down in JavaScript?
Nope. The only possibility is monitoring each keyup
and keydown
and remembering.
after some period of time the key begins to repeat, firing off keydown and keyup events like a fiend.
It shouldn't. You'll definitely get keypress
repeating, and in many browsers you'll also get repeated keydown
, but if keyup
repeats, it's a bug.
Unfortunately it is not a completely unheard-of bug: on Linux, Chromium, and Firefox (when it is being run under GTK+, which it is in popular distros such as Ubuntu) both generate repeating keyup-keypress-keydown sequences for held keys, which are impossible to distinguish from someone hammering the key really fast.
Yet another reason (not for this case, but maybe it'll save some nerves for someone) is that in PHP 5.5 short open tags <? phpinfo(); ?>
are disabled by default.
So the PHP interpreter would process code within short tags as plain text. In previous versions PHP this feature was enable by default. So the new behaviour can be a little bit mysterious.
I was using ASP.NET 4.5 MVC application on IIS 7. My fix was to set runallmanagedmodule to true.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
or If you have other modules, you may want to add them inside the module tag.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="ErrorLogWeb" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
...
</modules>
</system.webServer>
I use the following (stripped-down code) in Firefox 69.0 (on Ubuntu) to read a directory and show the image as part of a digital photo frame. The page is made in HTML, CSS, and JavaScript, and it is located on the same machine where I run the browser. The images are located on the same machine as well, so there is no viewing from "outside".
var directory = <path>;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', directory, false); // false for synchronous request
xmlHttp.send(null);
var ret = xmlHttp.responseText;
var fileList = ret.split('\n');
for (i = 0; i < fileList.length; i++) {
var fileinfo = fileList[i].split(' ');
if (fileinfo[0] == '201:') {
document.write(fileinfo[1] + "<br>");
document.write('<img src=\"' + directory + fileinfo[1] + '\"/>');
}
}
This requires the policy security.fileuri.strict_origin_policy
to be disabled. This means it might not be a solution you want to use. In my case I deemed it ok.
Finally I decided to use ls, and bash array expansion:
TEMP=( $( ls -ln FILE ) )
SIZE=${TEMP[4]}
it's not really nice, but at least it does only 1 fork+execve, and it doesn't rely on secondary programming language (perl/ruby/python/whatever)
The value of hjust
and vjust
are only defined between 0 and 1:
Source: ggplot2, Hadley Wickham, page 196
(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)
hjust
controls horizontal justification and vjust
controls vertical justification.
An example should make this clear:
td <- expand.grid(
hjust=c(0, 0.5, 1),
vjust=c(0, 0.5, 1),
angle=c(0, 45, 90),
text="text"
)
ggplot(td, aes(x=hjust, y=vjust)) +
geom_point() +
geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) +
facet_grid(~angle) +
scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))
To understand what happens when you change the hjust
in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)
DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() +
ylab("Very long label for y") +
theme(axis.title.y=element_text(angle=0))
p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")
library(ggExtra)
align.plots(p1, p2, p3)
To explore what happens with vjust
aligment of axis labels:
DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()
p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) +
xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) +
xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) +
xlab("X-axis labels aligned with vjust=1")
library(ggExtra)
align.plots(p1, p2, p3)
A lesser known trick is that mod_php maps stderr to the Apache log. And, there is a stream for that, so file_put_contents('php://stderr', print_r($foo, TRUE))
will nicely dump the value of $foo
into the Apache error log.
Just F.Y.I I pulled my hair out with this problem for hours.. finally I call my hosting provider and found that in my case using a cloud server that in the control panel for 1and1 they have a secondary firewall that you have to clone and add port 3306. Once added I got straight in..
CSS is called Cascading Style Sheets because the rules are inherited. Using the following selector, will select just the direct child of the parent, but its rules will be inherited by that div
's children divs
:
div.section > div { color: red }
Now, both that div
and its children will be red
. You need to cancel out whatever you set on the parent if you don't want it to inherit:
div.section > div { color: red }
div.section > div div { color: black }
Now only that single div
that is a direct child of div.section
will be red, but its children divs
will still be black.
DataSet ds = new DataSet();
using (var reader = cmd.ExecuteReader())
{
while (!reader.IsClosed)
{
ds.Tables.Add().Load(reader);
}
}
return ds;
I can give you two advices:
An alternative to Martin's
select LEFT(name, CHARINDEX(' ', name + ' ') -1),
STUFF(name, 1, Len(Name) +1- CHARINDEX(' ',Reverse(name)), '')
from somenames
Sample table
create table somenames (Name varchar(100))
insert somenames select 'abcd efgh'
insert somenames select 'ijk lmn opq'
insert somenames select 'asd j. asdjja'
insert somenames select 'asb (asdfas) asd'
insert somenames select 'asd'
insert somenames select ''
insert somenames select null
To answer the question more generally, the answer is:
select: function( event , ui ) {
alert( "You selected: " + ui.item.label );
}
Complete example :
$('#test').each(function(i, el) {_x000D_
var that = $(el);_x000D_
that.autocomplete({_x000D_
source: ['apple','banana','orange'],_x000D_
select: function( event , ui ) {_x000D_
alert( "You selected: " + ui.item.label );_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
A fix for this problem is to add swap
(i.e. paging
) space to the instance.
Paging works by creating an area on your hard drive and using it for extra memory, this memory is much slower than normal memory however much more of it is available.
To add this extra space to your instance you type:
sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1
If you need more than 1024 then change that to something higher.
To enable it by default after reboot, add this line to /etc/fstab:
/var/swap.1 swap swap defaults 0 0
object.setForeground(Color.green);
*any colour you wish *object being declared earlier
it is simple just use .qsize() example:
a=Queue()
a.put("abcdef")
print a.qsize() #prints 1 which is the size of queue
The above snippet applies for Queue()
class of python. Thanks @rayryeng for the update.
for deque from collections
we can use len()
as stated here by K Z.
Simply add a new UITabBarController reference to the project.Next create a reference of UITabBar in this controller:
@IBOutlet weak var appTabBar: UITabBar!
In its viewDidLoad(), simply add below for title text color:
appTabBar.tintColor = UIColor.scandidThemeColor()
For image
tabBarItem = UITabBarItem(title: "FirstTab", image: UIImage(named: "firstImage"), selectedImage: UIImage(named: "firstSelectedImage"))
@perreal's command works great! If you forget, try in two steps...
example: filter top to display only application called yakuake:
$ pgrep yakuake
1755
$ top -p 1755
useful top interactive commands 'c' : toggle full path vs. command name 'k' : kill by PID 'F' : filter by... select with arrows... then press 's' to set the sort
the answer below is good too... I was looking for that today but couldn't find it. Thanks
This is my solution:
/*
Change dimension of Image
*/
public static Image resizeImage(Image image, int scaledWidth, int scaledHeight, boolean preserveRatio) {
if (preserveRatio) {
double imageHeight = image.getHeight();
double imageWidth = image.getWidth();
if (imageHeight/scaledHeight > imageWidth/scaledWidth) {
scaledWidth = (int) (scaledHeight * imageWidth / imageHeight);
} else {
scaledHeight = (int) (scaledWidth * imageHeight / imageWidth);
}
}
BufferedImage inputBufImage = SwingFXUtils.fromFXImage(image, null);
// creates output image
BufferedImage outputBufImage = new BufferedImage(scaledWidth, scaledHeight, inputBufImage.getType());
// scales the input image to the output image
Graphics2D g2d = outputBufImage.createGraphics();
g2d.drawImage(inputBufImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
return SwingFXUtils.toFXImage(outputBufImage, null);
}
For Xcode 6 it is a little different.
After adding the device UDID in the developer site (https://developer.apple.com/account/ios/device/deviceList.action), go back to Xcode.
Xcode -> Preferences -> Accounts Select the Apple ID you added the device under and in the bottom right, click "View Details..."
Hit the refresh icon on the bottom left and then try to run the app again.
@larowlan great sample code. With the new GitHub API V3, the curl statement needs to be updated. Also, the login is no longer required:
curl https://api.github.com/repos/$2/$3 2> /dev/null | grep size | tr -dc '[:digit:]'
For example:
curl https://api.github.com/repos/dotnet/roslyn 2> /dev/null | grep size | tr -dc '[:digit:]'
returns 931668
(in KB), which is almost a GB.
Make sure the real source file is saved as UTF-8 (You may even want to try the non-recommended BOM Chars with UTF-8 to make sure).
Also in case of HTML, make sure you have declared the correct encoding using meta
tags:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
If it's a CMS (as you've tagged your question with Joomla) you may need to configure appropriate settings for the encoding.
I needed to delete our migration scripts along with the tables themselves ...
class Util::Table < ActiveRecord::Migration
def self.clobber(table_name)
# drop the table
if ActiveRecord::Base.connection.table_exists? table_name
puts "\n== " + table_name.upcase.cyan + " ! "
<< Time.now.strftime("%H:%M:%S").yellow
drop_table table_name
end
# locate any existing migrations for a table and delete them
base_folder = File.join(Rails.root.to_s, 'db', 'migrate')
Dir[File.join(base_folder, '**', '*.rb')].each do |file|
if file =~ /create_#{table_name}.rb/
puts "== deleting migration: " + file.cyan + " ! "
<< Time.now.strftime("%H:%M:%S").yellow
FileUtils.rm_rf(file)
break
end
end
end
def self.clobber_all
# delete every table in the db, along with every corresponding migration
ActiveRecord::Base.connection.tables.each {|t| clobber t}
end
end
from terminal window run:
$ rails runner "Util::Table.clobber 'your_table_name'"
or
$ rails runner "Util::Table.clobber_all"
Suppose you want to insert a particular line of text (not an empty line):
@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1
@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /p L=
IF %%i==%insertat% ECHO(!TL!
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
Somehow easy install doesn't work on my old mac (10.8). This solve my problem.
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py
If you do not have wget, just open in browser https://bootstrap.pypa.io/get-pip.py
then save as get-pip.py