In my case, this was caused by custom manifest entries added by the maven-jar-plugin.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<git>${buildNumber}</git>
<build-time>${timestamp}</build-time>
</manifestEntries>
</archive>
</configuration>
</plugin>
Removing the following entries fixed the problem
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
For this simplest way is touch start, touch move and touch end. That is working for both PC and touch device just check it in jquery documentation and hope this is the best solution for you. good luck
fstream are great but I will go a little deeper and tell you about RAII.
The problem with a classic example is that you are forced to close the file by yourself, meaning that you will have to bend your architecture to this need. RAII makes use of the automatic destructor call in C++ to close the file for you.
Update: seems that std::fstream already implements RAII so the code below is useless. I'll keep it here for posterity and as an example of RAII.
class FileOpener
{
public:
FileOpener(std::fstream& file, const char* fileName): m_file(file)
{
m_file.open(fileName);
}
~FileOpeneer()
{
file.close();
}
private:
std::fstream& m_file;
};
You can now use this class in your code like this:
int nsize = 10;
char *somedata;
ifstream myfile;
FileOpener opener(myfile, "<path to file>");
myfile.read(somedata,nsize);
// myfile is closed automatically when opener destructor is called
Learning how RAII works can save you some headaches and some major memory management bugs.
.m2 directory on linux box usually would be $HOME/.m2
you could get the $HOME :
echo $HOME
or simply:
cd <enter>
to go to your home directory.
other information from maven site: http://maven.apache.org/download.html#Installation
neat one-liner:
while (dataReader.Read())
{
employee.FirstName = (!dataReader.IsDBNull(dataReader.GetOrdinal("FirstName"))) ? dataReader["FirstName"].ToString() : "";
}
Added another case to Michal Górny's answer:
Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__
", modules intended for use as the main module of a Python application must always use absolute imports.
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
Referring to the WHATWG (Writing a form's user interface) it is not wrong to put the input field inside the label. This saves you code because the for
attribute from the label
is no longer needed.
Depends on where you want to use the email. If it's on the client side, without sending it to a PHP script, JQuery (or javascript) can do the trick.
I've created a fiddle to explain the same - http://jsfiddle.net/qHcpR/
It has an alert which goes off on load and when you click the textbox itself.
http://www.htmlgoodies.com/beyond/php/show-progress-report-for-long-running-php-scripts.html
I was searching for a similar solution and found this one use full.
var es;
function startTask() {
es = new EventSource('yourphpfile.php');
//a message is received
es.addEventListener('message', function(e) {
var result = JSON.parse( e.data );
console.log(result.message);
if(e.lastEventId == 'CLOSE') {
console.log('closed');
es.close();
var pBar = document.getElementById('progressor');
pBar.value = pBar.max; //max out the progress bar
}
else {
console.log(response); //your progress bar action
}
});
es.addEventListener('error', function(e) {
console.log('error');
es.close();
});
}
and your server outputs
header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
function send_message($id, $message, $progress) {
$d = array('message' => $message , 'progress' => $progress); //prepare json
echo "id: $id" . PHP_EOL;
echo "data: " . json_encode($d) . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
//LONG RUNNING TASK
for($i = 1; $i <= 10; $i++) {
send_message($i, 'on iteration ' . $i . ' of 10' , $i*10);
sleep(1);
}
send_message('CLOSE', 'Process complete');
SELECT * FROM table
where Date(col) = 'date'
we will look at how you can use MySQL at getting the last record in a Group By of records. For example if you have this result set of posts.
id category_id post_title
1 1 Title 1
2 1 Title 2
3 1 Title 3
4 2 Title 4
5 2 Title 5
6 3 Title 6
I want to be able to get the last post in each category which are Title 3, Title 5 and Title 6. To get the posts by the category you will use the MySQL Group By keyboard.
select * from posts group by category_id
But the results we get back from this query is.
id category_id post_title
1 1 Title 1
4 2 Title 4
6 3 Title 6
The group by will always return the first record in the group on the result set.
SELECT id, category_id, post_title
FROM posts
WHERE id IN (
SELECT MAX(id)
FROM posts
GROUP BY category_id
);
This will return the posts with the highest IDs in each group.
id category_id post_title
3 1 Title 3
5 2 Title 5
6 3 Title 6
Use setBasicAuth
to define credentials
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("myUsername", myPassword);
Then create the request like you prefer.
Example:
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET,
request, String.class);
String body = response.getBody();
I had to change @User3759685 above answer to this when the openpxyl updated. I was getting an error. Well @phihag reported this in the comments as well
for column_cells in ws.columns:
new_column_length = max(len(as_text(cell.value)) for cell in column_cells)
new_column_letter = (openpyxl.utils.get_column_letter(column_cells[0].column))
if new_column_length > 0:
ws.column_dimensions[new_column_letter].width = new_column_length + 1
In addition to making a symbolic link for apt_pkg.so
, you may want to make apt_inst.so
in the same manner of apt_pkg.so
.
ln -s apt_inst.cpython-35m-x86_64-linux-gnu.so apt_inst.so
With mysql 5.7, date value like 0000-00-00 00:00:00 is not allowed.
If you want to allow it, you have to update your my.cnf like:
sudo nano /etc/mysql/my.cnf
find
[mysqld]
Add after:
sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Restart mysql service:
sudo service mysql restart
Done!
With one feature my Dataframe list converts to a Series. I had to convert it back to a Dataframe list and it worked.
if type(X) is Series:
X = X.to_frame()
Add hamcrest-all-X.X.jar
to your classpath.
Latest version as of Feb 2015 is 1.3: http://code.google.com/p/hamcrest/downloads/detail?name=hamcrest-all-1.3.jar&can=2&q=
There are 2 main solutions:
The pure HTML one:
<input type="text" id="Textbox" name="Textbox" maxlength="10" />
The JavaScript one (attach it to a onKey Event):
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.
In Bootstrap the active
class needs to be applied to the <li>
element and not the <a>
. See the first example here: http://getbootstrap.com/components/#navbar
The way you handle your UI style based on what is active or not has nothing to do with ASP.NET MVC's ActionLink
helper. This is the proper solution to follow how the Bootstrap framework was built.
<ul class="nav navbar-nav">
<li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
Edit:
Since you will most likely be reusing your menu on multiple pages, it would be smart to have a way to apply that selected class automatically based on the current page rather than copy the menu multiple times and do it manually.
The easiest way is to simply use the values contained in ViewContext.RouteData
, namely the Action
and Controller
values. We could build on what you currently have with something like this:
<ul class="nav navbar-nav">
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
It's not pretty in code, but it'll get the job done and allow you to extract your menu into a partial view if you like. There are ways to do this in a much cleaner way, but since you're just getting started I'll leave it at that. Best of luck learning ASP.NET MVC!
Late edit:
This question seems to be getting a bit of traffic so I figured I'd throw in a more elegant solution using an HtmlHelper
extension.
Edit 03-24-2015: Had to rewrite this method to allow for multiple actions and controllers triggering the selected behavior, as well as handling for when the method is called from a child action partial view, thought I'd share the update!
public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string cssClass = "selected")
{
ViewContext viewContext = html.ViewContext;
bool isChildAction = viewContext.Controller.ControllerContext.IsChildAction;
if (isChildAction)
viewContext = html.ViewContext.ParentActionViewContext;
RouteValueDictionary routeValues = viewContext.RouteData.Values;
string currentAction = routeValues["action"].ToString();
string currentController = routeValues["controller"].ToString();
if (String.IsNullOrEmpty(actions))
actions = currentAction;
if (String.IsNullOrEmpty(controllers))
controllers = currentController;
string[] acceptedActions = actions.Trim().Split(',').Distinct().ToArray();
string[] acceptedControllers = controllers.Trim().Split(',').Distinct().ToArray();
return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
cssClass : String.Empty;
}
Works with .NET Core:
public static string IsSelected(this IHtmlHelper htmlHelper, string controllers, string actions, string cssClass = "selected")
{
string currentAction = htmlHelper.ViewContext.RouteData.Values["action"] as string;
string currentController = htmlHelper.ViewContext.RouteData.Values["controller"] as string;
IEnumerable<string> acceptedActions = (actions ?? currentAction).Split(',');
IEnumerable<string> acceptedControllers = (controllers ?? currentController).Split(',');
return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
cssClass : String.Empty;
}
Sample usage:
<ul>
<li class="@Html.IsSelected(actions: "Home", controllers: "Default")">
<a href="@Url.Action("Home", "Default")">Home</a>
</li>
<li class="@Html.IsSelected(actions: "List,Detail", controllers: "Default")">
<a href="@Url.Action("List", "Default")">List</a>
</li>
</ul>
I think things would be easier if you code your success
function to load the appropriate page instead of returning true
or false
.
For example instead of returning true
you could do:
window.location="appropriate page";
That way when the success function is called the page gets redirected.
YourListType ListName = (List<YourListType>)Session["SessionName"];
This will center the text in a text view:
TextView ta = (TextView) findViewById(R.layout.text_view);
LayoutParams lp = new LayoutParams();
lp.gravity = Gravity.CENTER_HORIZONTAL;
ta.setLayoutParams(lp);
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
These are deprecated use the following..
// Connects to your Database
$link = mysqli_connect("localhost", "root", "", "");
and to insert data use the following
$sql = "INSERT INTO Table-Name (Column-Name)
VALUES ('$filename')" ;
Your formula looks fine. Maybe the value you are looking for is not in the first column of the second table?
If the second sheet is in another workbook, you need to add a Workbook reference to your formula:
=VLOOKUP(M3,[Book1]Sheet1!$A$2:$Q$47,13,FALSE)
Let it be simple. It's as simple as
promise
in your service(no need to use then
in service)then
in your controllerDemo. http://plnkr.co/edit/cbdG5p?p=preview
var app = angular.module('plunker', []);
app.factory('myService', function($http) {
return {
async: function() {
return $http.get('test.json'); //1. this returns promise
}
};
});
app.controller('MainCtrl', function( myService,$scope) {
myService.async().then(function(d) { //2. so you can use .then()
$scope.data = d;
});
});
I think that your JAVA_HOME should point to
C:\Program Files\Java\jdk1.6.0_25
instead of
C:\Program Files\Java\jdk1.6.0_25\bin
That is, without the bin folder.
UPDATE
That new error appears to me if I set the JAVA_HOME with the quotes, like you did. Are you using quotation marks? If so, remove them.
" ".join(foo.split())
is not quite correct with respect to the question asked because it also entirely removes single leading and/or trailing white spaces. So, if they shall also be replaced by 1 blank, you should do something like the following:
" ".join(('*' + foo + '*').split()) [1:-1]
Of course, it's less elegant.
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
Press Ctrl and use the mouse wheel to zoom In or Out.
// Modified from EboMike's answer
String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));
extension should have ".txt" in it when run.
Within Crystal, you can do it by creating a formula that uses the ToNumber
function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:
If NumericText ({field}) then ToNumber ({field}) else 0
Alternatively, you might find it easier to convert the field's datatype within the query used in the report.
Control Panel >> Windows Firewall
Advanced settings >> Inbound Rules >> World Wide Web Services - Enable it All or (Domain, Private, Public) as needed.
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
This is all you need to:
id
columnCredit is given to @resnyanskiy who gave this answer in a comment.
With the upcoming Xcode 7 it's now possible to install apps on your devices without an apple developer license, so now it is possible to skip the app store and you don't have to jailbreak your device.
Now everyone can get their app on their Apple device.
Xcode 7 and Swift now make it easier for everyone to build apps and run them directly on their Apple devices. Simply sign in with your Apple ID, and turn your idea into an app that you can touch on your iPad, iPhone, or Apple Watch. Download Xcode 7 beta and try it yourself today. Program membership is not required.
Quoted from: https://developer.apple.com/xcode/
Update:
XCode 7 is now released:
Free On-Device Development Now everyone can run and test their own app on a device—for free. You can run and debug your own creations on a Mac, iPhone, iPad, iPod touch, or Apple Watch without any fees, and no programs to join. All you need to do is enter your free Apple ID into Xcode. You can even use the same Apple ID you already use for the App Store or iTunes. Once you’ve perfected your app the Apple Developer Program can help you get it on the App Store.
See Launching Your App on Devices for detailed information about installing and running on devices.
For a hash function it's not only important to minimize colisions generally but to make it impossible to stay with the same hash while chaning a few bytes.
Say you have an equation:
(x + y*z) % key = x
with 0<x<key
and 0<z<key
.
If key is a primenumber n*y=key is true for every n in N and false for every other number.
An example where key isn't a prime example: x=1, z=2 and key=8 Because key/z=4 is still a natural number, 4 becomes a solution for our equation and in this case (n/2)*y = key is true for every n in N. The amount of solutions for the equation have practially doubled because 8 isn't a prime.
If our attacker already knows that 8 is possible solution for the equation he can change the file from producing 8 to 4 and still gets the same hash.
A very much simpler and elegant way is to use this:
import os
dir_list = os.walk('.').next()[1]
print dir_list
Run this script in the same folder for which you want folder names.It will give you exactly the immediate folders name only(that too without the full path of the folders).
ngStyle
accepts a map:
$scope.myStyle = {
"width" : "900px",
"background" : "red"
};
This code can distinguish between click and movement (drag, scroll). In onTouchEvent set a flag isOnClick, and initial X, Y coordinates on ACTION_DOWN. Clear the flag on ACTION_MOVE (minding that unintentional movement is often detected which can be solved with a THRESHOLD const).
private float mDownX;
private float mDownY;
private final float SCROLL_THRESHOLD = 10;
private boolean isOnClick;
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mDownX = ev.getX();
mDownY = ev.getY();
isOnClick = true;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (isOnClick) {
Log.i(LOG_TAG, "onClick ");
//TODO onClick code
}
break;
case MotionEvent.ACTION_MOVE:
if (isOnClick && (Math.abs(mDownX - ev.getX()) > SCROLL_THRESHOLD || Math.abs(mDownY - ev.getY()) > SCROLL_THRESHOLD)) {
Log.i(LOG_TAG, "movement detected");
isOnClick = false;
}
break;
default:
break;
}
return true;
}
For LongPress as suggested above, GestureDetector is the way to go. Check this Q&A:
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
Try another cable and if that doesn't work try another phone.
I wrestled with this and all the tips above for several days. But the connector on my devices was flakey. As a test move the phone and see if you get connections dropping.
Some of the tips such a ADB USB will fix it temporarily and explicitly (re) selecting the device process to debug. But for me the root cause was that the physical connection.
So now with the new device I have no problem ever! A flakey cable would cause the same issue. Good luck! I feel your pain.
SQL Error: ORA-30926: unable to get a stable set of rows in the source tables
30926. 00000 - "unable to get a stable set of rows in the source tables"
*Cause: A stable set of rows could not be got because of large dml
activity or a non-deterministic where clause.
*Action: Remove any non-deterministic where clauses and reissue the dml.
This Error occurred for me because of duplicate records(16K)
I tried with unique it worked .
but again when I tried merge without unique same proble occurred Second time it was due to commit
after merge if commit is not done same Error will be shown.
Without unique, Query will work if commit is given after each merge operation.
Are you sure you need a regex? It seems that you only need to know if a word is present in a string, so you can do:
>>> line = 'This,is,a,sample,string'
>>> "sample" in line
True
I am listing the difference in each of the casting ways. What a particular type of casting handles and it doesn't?
// object to int
// does not handle null
// does not handle NAN ("102art54")
// convert value to integar
int intObj = (int)obj;
// handles only null or number
int? nullableIntObj = (int?)obj; // null
Nullable<int> nullableIntObj1 = (Nullable<int>)obj; // null
// best way for casting from object to nullable int
// handles null
// handles other datatypes gives null("sadfsdf") // result null
int? nullableIntObj2 = obj as int?;
// string to int
// does not handle null( throws exception)
// does not string NAN ("102art54") (throws exception)
// converts string to int ("26236")
// accepts string value
int iVal3 = int.Parse("10120"); // throws exception value cannot be null;
// handles null converts null to 0
// does not handle NAN ("102art54") (throws exception)
// converts obj to int ("26236")
int val4 = Convert.ToInt32("10120");
// handle null converts null to 0
// handle NAN ("101art54") converts null to 0
// convert string to int ("26236")
int number;
bool result = int.TryParse(value, out number);
if (result)
{
// converted value
}
else
{
// number o/p = 0
}
You can create a a method and pass paramters to it and get the json as a response.
private JSONObject jsonResult(String Name,int id, String curriculum) throws JSONException {
JSONObject json = null;
json = new JSONObject("{\"" + "Name" + "\":" + "\"" + Name+ "\""
+ "," + "\"" + "Id" + "\":" + id + "," + "\"" + "Curriculum"
+ "\":" + "\"" + curriculum+ "\"" + "}");
return json;
}
I hope this will help you.
jQuery normalises event.which
depending on whether event.which
, event.keyCode
or event.charCode
is supported by the browser:
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
An added benefit of .which
is that jQuery does it for mouse clicks too:
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
If one really wanted to they could make there own version of scanf()
like so:
import java.util.ArrayList;
import java.util.Scanner;
public class Testies {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<String> strings = new ArrayList<String>();
// get input
System.out.println("Give me input:");
scanf(strings, nums);
System.out.println("Ints gathered:");
// print numbers scanned in
for(Integer num : nums){
System.out.print(num + " ");
}
System.out.println("\nStrings gathered:");
// print strings scanned in
for(String str : strings){
System.out.print(str + " ");
}
System.out.println("\nData:");
for(int i=0; i<strings.size(); i++){
System.out.println(nums.get(i) + " " + strings.get(i));
}
}
// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
Scanner getLine = new Scanner(System.in);
Scanner input = new Scanner(getLine.nextLine());
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
Scanner input = (new Scanner(in));
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
}
Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext()
should probably be at the bottom of the if-else if
sequence since hasNext()
will return true for all of the data in the string.
Output:
Give me input:
apples 8 9 pears oranges 5
Ints gathered:
8 9 5
Strings gathered:
apples pears oranges
Data:
8 apples
9 pears
5 oranges
Probably not the best example; but, the point is that Scanner
implements the Iterator
class. Making it easy to iterate through the scanners input using the hasNext<datatypehere>()
methods; and then storing the input.
like Jesse Jesse Glick and abguy said you can enumerate string into Boolean type:
Boolean.valueOf(string_variable)
or the opposite Boolean into string:
String.valueOf(boolean_variable)
in my case I had to to downstream Boolean parameter to another job. So for this you will need the use the class BooleanParameterValue :
build job: 'downstream_job_name', parameters:
[
[$class: 'BooleanParameterValue', name: 'parameter_name', value: false],
], wait: true
You might want to check your matplotlib version.
Somehow I installed a dev version of matplotlib which caused the issue. A downgrade to stable release fixed it.
One can also can try python -v -c 'import YOUR_PACKAGE' 2>&1 | less
to see where the issue occurred and if the lines above error can give you some hints.
If you need any type of quoting (single, double, and triple for both) you can "combine"(0) the strings:
>>> raw_string_with_quotes = r'double"' r"single'" r'''double triple""" ''' r"""single triple''' """
>>> print raw_string_with_quotes
double"single'double triple""" single triple'''
You may also "combine"(0) raw strings with non-raw strings:
>>> r'raw_string\n' 'non-raw string\n'
'raw_string\\nnon-raw string\n'
(0): In fact, the Python parser joins the strings, and it does not create multiple strings. If you add the "+" operator, then multiple strings are created and combined.
What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.
E.g.
<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>
When you upload your p8 file in Firebase, in the box that reads App ID Prefix(required) , you should enter your team ID. You can get it from https://developer.apple.com/account/#/membership and copy/paste the Team ID as shown below.
You can pass custom http headers with RestTemplate exchange method as below.
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");
HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);
RestTemplate template = new RestTemplate();
ResponseEntity<RestResponse> respEntity = template
.exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);
EDIT : Below is the updated code. This link has several ways of calling rest service with examples
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Mall[]> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);
Mall[] resp = respEntity.getBody();
I like lambda :)
private void ClearTextBoxes()
{
Action<Control.ControlCollection> func = null;
func = (controls) =>
{
foreach (Control control in controls)
if (control is TextBox)
(control as TextBox).Clear();
else
func(control.Controls);
};
func(Controls);
}
Good luck!
From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.
Here's what your code would look like if changed as suggested:
beforecreate: function(node,targetNode,type,to) {
jQuery.ajax({
url: url,
success: function(result) {
if(result.isOk == false)
alert(result.message);
},
async: false
});
}
this is because $.ajax is the only request type that you can set the asynchronousity for
You can use:
db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true);
Or to just update the docs which contain the property:
db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true);
The false, true
in the method above are: { upsert:false, multi:true }
. You need the multi:true
to update all your records.
Or you can use the former way:
remap = function (x) {
if (x.additional){
db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});
}
}
db.foo.find().forEach(remap);
In MongoDB 3.2 you can also use
db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )
The general syntax of this is
db.collection.updateMany(filter, update, options)
https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/
If you are compiling a PROCEDURE, possibly this is referring to a table or view that does not exist as it is created in the same PROCEDURE. In this case the solution is to make the query declared as String eg v_query: = 'insert into table select * from table2
and then execute immediate on v_query
;
This is because the compiler does not yet recognize the object and therefore does not find the reference. Greetings.
Example: Display different output depending on whether the user is logged in or not.
<?php
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, visitor!';
}
?>
Adding System.Windows.Forms reference requires .NET Framework project type:
I was using .NET Core project type. This project type doesn't allow us to add assemblies into its project references. I had to move to .NET Framework project type before adding System.Windows.Forms
assembly to my references as described in Kendall Frey answer.
Note: There is reference System_Windows_Forms
available under COM tab (for both .NET Core and .NET Framework). It is not the right one. It has to be System.Windows.Forms
under Assemblies tab.
I had the same problem and after some search this is my workaround. I found that if the columns are removed and then re-added the table is updated.
public static <T,U> void refreshTableView(final TableView<T> tableView, final List<TableColumn<T,U>> columns, final List<T> rows) {
tableView.getColumns().clear();
tableView.getColumns().addAll(columns);
ObservableList<T> list = FXCollections.observableArrayList(rows);
tableView.setItems(list);
}
Example of usage:
refreshTableView(myTableView, Arrays.asList(col1, col2, col3), rows);
I have got the same error but I have resolved the issue in the following ways:
PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().
// error reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);
//setting url
$url = 'http://example.com/api';
//data
$data = array("message" => "Hello World!!!");
try {
$ch = curl_init($url);
$data_string = json_encode($data);
if (FALSE === $ch)
throw new Exception('failed to initialize');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$output = curl_exec($ch);
if (FALSE === $output)
throw new Exception(curl_error($ch), curl_errno($ch));
// ...process $output now
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
List<T>.Remove() and List<T>.RemoveAt() do not return the item that is being removed.
Therefore you have to use this:
var item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);
Since printArea is a jQuery plugin it is not included in jquery.d.ts.
You need to create a jquery.printArea.ts definition file.
If you create a complete definition file for the plugin you may want to submit it to DefinitelyTyped.
On the command line:
php -i | grep sourceguardian
If it's there, then you'll get some text. If not, you won't get a thing.
I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:
// creating locale Locale locale2 = new Locale(loc); Locale.setDefault(locale2); Configuration config2 = new Configuration(); config2.locale = locale2; // updating locale mContext.getResources().updateConfiguration(config2, null);
Depending on what arguments you need to pass, especially for custom event handlers, you can do something like this:
<div @customEvent='(arg1) => myCallback(arg1, arg2)'>Hello!</div>
I've found an example on the internet.
Some guy wrote this code and worked perfectly
HTML
<div ng-cloak ng-app="ManagerApp">
<div id="MainWrap" class="container" ng-controller="ManagerCtrl">
<span class="label label-info label-ext">Exposing Controller Function outside the module via onClick function call</span>
<button onClick='ajaxResultPost("Update:Name:With:JOHN","accept",true);'>click me</button>
<br/> <span class="label label-warning label-ext" ng-bind="customParams.data"></span>
<br/> <span class="label label-warning label-ext" ng-bind="customParams.type"></span>
<br/> <span class="label label-warning label-ext" ng-bind="customParams.res"></span>
<br/>
<input type="text" ng-model="sampletext" size="60">
<br/>
</div>
</div>
JAVASCRIPT
var angularApp = angular.module('ManagerApp', []);
angularApp.controller('ManagerCtrl', ['$scope', function ($scope) {
$scope.customParams = {};
$scope.updateCustomRequest = function (data, type, res) {
$scope.customParams.data = data;
$scope.customParams.type = type;
$scope.customParams.res = res;
$scope.sampletext = "input text: " + data;
};
}]);
function ajaxResultPost(data, type, res) {
var scope = angular.element(document.getElementById("MainWrap")).scope();
scope.$apply(function () {
scope.updateCustomRequest(data, type, res);
});
}
*I did some modifications, see original: font JSfiddle
Here's a simple scraper I created in c# to get streaming quote data printed out to a console. It should be easily converted to java. Based on the following post:
http://blog.underdog-projects.net/2009/02/bringing-the-yahoo-finance-stream-to-the-shell/
Not too fancy (i.e. no regex etc), just a fast & dirty solution.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
namespace WebDataAddin
{
public class YahooConstants
{
public const string AskPrice = "a00";
public const string BidPrice = "b00";
public const string DayRangeLow = "g00";
public const string DayRangeHigh = "h00";
public const string MarketCap = "j10";
public const string Volume = "v00";
public const string AskSize = "a50";
public const string BidSize = "b60";
public const string EcnBid = "b30";
public const string EcnBidSize = "o50";
public const string EcnExtHrBid = "z03";
public const string EcnExtHrBidSize = "z04";
public const string EcnAsk = "b20";
public const string EcnAskSize = "o40";
public const string EcnExtHrAsk = "z05";
public const string EcnExtHrAskSize = "z07";
public const string EcnDayHigh = "h01";
public const string EcnDayLow = "g01";
public const string EcnExtHrDayHigh = "h02";
public const string EcnExtHrDayLow = "g11";
public const string LastTradeTimeUnixEpochformat = "t10";
public const string EcnQuoteLastTime = "t50";
public const string EcnExtHourTime = "t51";
public const string RtQuoteLastTime = "t53";
public const string RtExtHourQuoteLastTime = "t54";
public const string LastTrade = "l10";
public const string EcnQuoteLastValue = "l90";
public const string EcnExtHourPrice = "l91";
public const string RtQuoteLastValue = "l84";
public const string RtExtHourQuoteLastValue = "l86";
public const string QuoteChangeAbsolute = "c10";
public const string EcnQuoteAfterHourChangeAbsolute = "c81";
public const string EcnQuoteChangeAbsolute = "c60";
public const string EcnExtHourChange1 = "z02";
public const string EcnExtHourChange2 = "z08";
public const string RtQuoteChangeAbsolute = "c63";
public const string RtExtHourQuoteAfterHourChangeAbsolute = "c85";
public const string RtExtHourQuoteChangeAbsolute = "c64";
public const string QuoteChangePercent = "p20";
public const string EcnQuoteAfterHourChangePercent = "c82";
public const string EcnQuoteChangePercent = "p40";
public const string EcnExtHourPercentChange1 = "p41";
public const string EcnExtHourPercentChange2 = "z09";
public const string RtQuoteChangePercent = "p43";
public const string RtExtHourQuoteAfterHourChangePercent = "c86";
public const string RtExtHourQuoteChangePercent = "p44";
public static readonly IDictionary<string, string> CodeMap = typeof(YahooConstants).GetFields().
Where(field => field.FieldType == typeof(string)).
ToDictionary(field => ((string)field.GetValue(null)).ToUpper(), field => field.Name);
}
public static class StringBuilderExtensions
{
public static bool HasPrefix(this StringBuilder builder, string prefix)
{
return ContainsAtIndex(builder, prefix, 0);
}
public static bool HasSuffix(this StringBuilder builder, string suffix)
{
return ContainsAtIndex(builder, suffix, builder.Length - suffix.Length);
}
private static bool ContainsAtIndex(this StringBuilder builder, string str, int index)
{
if (builder != null && !string.IsNullOrEmpty(str) && index >= 0
&& builder.Length >= str.Length + index)
{
return !str.Where((t, i) => builder[index + i] != t).Any();
}
return false;
}
}
public class WebDataAddin
{
public const string ScriptStart = "<script>";
public const string ScriptEnd = "</script>";
public const string MessageStart = "try{parent.yfs_";
public const string MessageEnd = ");}catch(e){}";
public const string DataMessage = "u1f(";
public const string InfoMessage = "mktmcb(";
protected static T ParseJson<T>(string json)
{
// parse json - max acceptable value retrieved from
//http://forums.asp.net/t/1343461.aspx
var deserializer = new JavaScriptSerializer { MaxJsonLength = 2147483647 };
return deserializer.Deserialize<T>(json);
}
public static void Main()
{
const string symbols = "GBPUSD=X,SPY,MSFT,BAC,QQQ,GOOG";
// these are constants in the YahooConstants enum above
const string attrs = "b00,b60,a00,a50";
const string url = "http://streamerapi.finance.yahoo.com/streamer/1.0?s={0}&k={1}&r=0&callback=parent.yfs_u1f&mktmcb=parent.yfs_mktmcb&gencallback=parent.yfs_gencb®ion=US&lang=en-US&localize=0&mu=1";
var req = WebRequest.Create(string.Format(url, symbols, attrs));
req.Proxy.Credentials = CredentialCache.DefaultCredentials;
var missingCodes = new HashSet<string>();
var response = req.GetResponse();
if(response != null)
{
var stream = response.GetResponseStream();
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
var builder = new StringBuilder();
var initialPayloadReceived = false;
while (!reader.EndOfStream)
{
var c = (char)reader.Read();
builder.Append(c);
if(!initialPayloadReceived)
{
if (builder.HasSuffix(ScriptStart))
{
// chop off the first part, and re-append the
// script tag (this is all we care about)
builder.Clear();
builder.Append(ScriptStart);
initialPayloadReceived = true;
}
}
else
{
// check if we have a fully formed message
// (check suffix first to avoid re-checking
// the prefix over and over)
if (builder.HasSuffix(ScriptEnd) &&
builder.HasPrefix(ScriptStart))
{
var chop = ScriptStart.Length + MessageStart.Length;
var javascript = builder.ToString(chop,
builder.Length - ScriptEnd.Length - MessageEnd.Length - chop);
if (javascript.StartsWith(DataMessage))
{
var json = ParseJson<Dictionary<string, object>>(
javascript.Substring(DataMessage.Length));
// parse out the data. key should be the symbol
foreach(var symbol in json)
{
Console.WriteLine("Symbol: {0}", symbol.Key);
var symbolData = (Dictionary<string, object>) symbol.Value;
foreach(var dataAttr in symbolData)
{
var codeKey = dataAttr.Key.ToUpper();
if (YahooConstants.CodeMap.ContainsKey(codeKey))
{
Console.WriteLine("\t{0}: {1}", YahooConstants.
CodeMap[codeKey], dataAttr.Value);
} else
{
missingCodes.Add(codeKey);
Console.WriteLine("\t{0}: {1} (Warning! No Code Mapping Found)",
codeKey, dataAttr.Value);
}
}
Console.WriteLine();
}
} else if(javascript.StartsWith(InfoMessage))
{
var json = ParseJson<Dictionary<string, object>>(
javascript.Substring(InfoMessage.Length));
foreach (var dataAttr in json)
{
Console.WriteLine("\t{0}: {1}", dataAttr.Key, dataAttr.Value);
}
Console.WriteLine();
} else
{
throw new Exception("Cannot recognize the message type");
}
builder.Clear();
}
}
}
}
}
}
}
}
}
Small addition to Chris Kannon' accepted answer: only print if there actually is a second last column.
(
echo | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 3 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
)
Any ideas?
CSS4 will be fancy if it adds some hooks into walking backwards. Until then it is possible (though not advisable) to use checkbox
and/or radio
input
s to break the usual way that things are connected, and through that also allow CSS to operate outside of its normal scope...
/* Hide things that may be latter shown */
.menu__checkbox__selection,
.menu__checkbox__style,
.menu__hidden {
display: none;
visibility: hidden;
opacity: 0;
filter: alpha(opacity=0); /* Old Microsoft opacity */
}
/* Base style for content and style menu */
.main__content {
background-color: lightgray;
color: black;
}
.menu__hidden {
background-color: black;
color: lightgray;
/* Make list look not so _listy_ */
list-style: none;
padding-left: 5px;
}
.menu__option {
box-sizing: content-box;
display: block;
position: static;
z-index: auto;
}
/* ▼ - \u2630 - Three Bars */
/*
.menu__trigger__selection::before {
content: '\2630';
display: inline-block;
}
*/
/* ▼ - Down Arrow */
.menu__trigger__selection::after {
content: "\25BC";
display: inline-block;
transform: rotate(90deg);
}
/* Customize to look more `select` like if you like */
.menu__trigger__style:hover,
.menu__trigger__style:active {
cursor: pointer;
background-color: darkgray;
color: white;
}
/**
* Things to do when checkboxes/radios are checked
*/
.menu__checkbox__selection:checked + .menu__trigger__selection::after,
.menu__checkbox__selection[checked] + .menu__trigger__selection::after {
transform: rotate(0deg);
}
/* This bit is something that you may see elsewhere */
.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
display: block;
visibility: visible;
opacity: 1;
filter: alpha(opacity=100); /* Microsoft!? */
}
/**
* Hacky CSS only changes based off non-inline checkboxes
* ... AKA the stuff you cannot unsee after this...
*/
.menu__checkbox__style[id="style-default"]:checked ~ .main__content {
background-color: lightgray;
color: black;
}
.menu__checkbox__style[id="style-default"]:checked ~ .main__content .menu__trigger__style[for="style-default"] {
color: darkorange;
}
.menu__checkbox__style[id="style-one"]:checked ~ .main__content {
background-color: black;
color: lightgray;
}
.menu__checkbox__style[id="style-one"]:checked ~ .main__content .menu__trigger__style[for="style-one"] {
color: darkorange;
}
.menu__checkbox__style[id="style-two"]:checked ~ .main__content {
background-color: darkgreen;
color: red;
}
.menu__checkbox__style[id="style-two"]:checked ~ .main__content .menu__trigger__style[for="style-two"] {
color: darkorange;
}
_x000D_
<!--
This bit works, but will one day cause troubles,
but truth is you can stick checkbox/radio inputs
just about anywhere and then call them by id with
a `for` label. Keep scrolling to see what I mean
-->
<input type="radio"
name="colorize"
class="menu__checkbox__style"
id="style-default">
<input type="radio"
name="colorize"
class="menu__checkbox__style"
id="style-one">
<input type="radio"
name="colorize"
class="menu__checkbox__style"
id="style-two">
<div class="main__content">
<p class="paragraph__split">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
</p>
<input type="checkbox"
class="menu__checkbox__selection"
id="trigger-style-menu">
<label for="trigger-style-menu"
class="menu__trigger__selection"> Theme</label>
<ul class="menu__hidden">
<li class="menu__option">
<label for="style-default"
class="menu__trigger__style">Default Style</label>
</li>
<li class="menu__option">
<label for="style-one"
class="menu__trigger__style">First Alternative Style</label>
</li>
<li class="menu__option">
<label for="style-two"
class="menu__trigger__style">Second Alternative Style</label>
</li>
</ul>
<p class="paragraph__split">
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
_x000D_
... pretty gross, but with just CSS and HTML it is possible to touch and re-touch anything but the body
and :root
from just about anywhere by linking the id
and for
properties of radio
/checkbox
input
s and label
triggers; likely someone'll show how to re-touch those at some point.
One additional caveat is that only one input
of a specific id
maybe used, first checkbox
/radio
wins a toggled state in other words... But multiple labels can all point to the same input
, though that would make both the HTML and CSS look even grosser.
... I'm hoping that there is some sort of workaround that exists native to CSS Level 2...
I am not sure about the other pseudo classes, but I :checked
for pre-CSS 3. If I remember correctly, it was something like [checked]
which is why you may find it in the above code, for example,
.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
/* rules: and-stuff; */
}
... but for things like ::after
and :hover
, I'm not at all certain in which CSS version those first appeared.
That all stated, please don't ever use this in production, not even in anger. As a joke sure, or in other words just because something can be done does not always mean it should.
As other have said, you want to use either puts
or p
. Why? Is that magic?
Actually not. A rails console is, under the hood, an IRB, so all you can do in IRB you will be able to do in a rails console. Since for printing in an IRB we use puts
, we use the same command for printing in a rails console.
You can actually take a look at the console code in the rails source code. See the require of irb? :)
Here is a Swift way to get screen sizes, this also takes current interface orientation into account:
var screenWidth: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.width
} else {
return UIScreen.mainScreen().bounds.size.height
}
}
var screenHeight: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height
} else {
return UIScreen.mainScreen().bounds.size.width
}
}
var screenOrientation: UIInterfaceOrientation {
return UIApplication.sharedApplication().statusBarOrientation
}
These are included as a standard function in:
Yes. 'Z' stands for Zulu time, which is also GMT and UTC.
From http://en.wikipedia.org/wiki/Coordinated_Universal_Time:
The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time.
Technically, because the definition of nautical time zones is based on longitudinal position, the Z time is not exactly identical to the actual GMT time 'zone'. However, since it is primarily used as a reference time, it doesn't matter what area of Earth it applies to as long as everyone uses the same reference.
From wikipedia again, http://en.wikipedia.org/wiki/Nautical_time:
Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications; zones M and Y have the same clock time but differ by 24 hours: a full day). These were to be vocalized using a phonetic alphabet which pronounces the letter Z as Zulu, leading sometimes to the use of the term "Zulu Time". The Greenwich time zone runs from 7.5°W to 7.5°E longitude, while zone A runs from 7.5°E to 22.5°E longitude, etc.
You do not need to clear focus, just add this code where you want to focus
time_statusTV.setFocusable(true);
time_statusTV.requestFocus();
InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
imm.showSoftInput( time_statusTV, 0);
I've had simmilar issue. change
event was not good for me because i've needed to refresh some data when user clicks on option
. After few trials i've got this solution:
$('select').on('click',function(ev){
if(ev.offsetY < 0){
//user click on option
}else{
//dropdown is shown
}
});
I agree that this is very ugly and you should stick with change
event where you can, but this solved my problem.
Your @JsonSubTypes
declaration does not make sense: it needs to list implementation (sub-) classes, NOT the class itself (which would be pointless). So you need to modify that entry to list sub-class(es) there are; or use some other mechanism to register sub-classes (SimpleModule
has something like addAbstractTypeMapping
).
I got this error when tried to create folder http://localhost:8080/repository/default/parent/newFolder when http://localhost:8080/repository/default/parent didn't exist.
Late model JAVA has optimizations for + with constant strings, employs a StringBuffer behind the scenes, so you do not want to clutter your code with it.
It points to a JAVA oversight, that it does not resemble ANSI C in the automatic concatenation of double quoted strings with only white space between them, e.g.:
const char usage = "\n"
"Usage: xxxx <options>\n"
"\n"
"Removes your options as designated by the required parameter <options>,\n"
"which must be one of the following strings:\n"
" love\n"
" sex\n"
" drugs\n"
" rockandroll\n"
"\n" ;
I would love to have a multi-line character array constant where embedded linefeeds are honored, so I can present the block without any clutter, e.g.:
String Query = "
SELECT
some_column,
another column
FROM
one_table a
JOIN
another_table b
ON a.id = b.id
AND a.role_code = b.role_code
WHERE a.dept = 'sales'
AND b.sales_quote > 1000
Order BY 1, 2
" ;
To get this, one needs to beat on the JAVA gods.
Check out Lists.partition(java.util.List, int)
from Google Guava:
Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing
[a, b, c, d, e]
with a partition size of 3 yields[[a, b, c]
,[d, e]]
-- an outer list containing two inner lists of three and two elements, all in the original order.
First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).
Second, the -vm argument in eclipse.ini
should point to the java executable. See
http://wiki.eclipse.org/Eclipse.ini for examples.
If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?
you can check by putting these code in php file.
<?php
if(in_array ('curl', get_loaded_extensions())) {
echo "CURL is available on your web server";
}
else{
echo "CURL is not available on your web server";
}
OR
var_dump(extension_loaded('curl'));
$(function(){
$(selector).click();
});
All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.
return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);
Conditions using Array:
$users = User::where([
'column1' => value1,
'column2' => value2,
'column3' => value3
])->get();
Will produce query like bellow:
SELECT * FROM TABLE WHERE column1 = value1 and column2 = value2 and column3 = value3
Conditions using Anonymous Function:
$users = User::where('column1', '=', value1)
->where(function($query) use ($variable1,$variable2){
$query->where('column2','=',$variable1)
->orWhere('column3','=',$variable2);
})
->where(function($query2) use ($variable1,$variable2){
$query2->where('column4','=',$variable1)
->where('column5','=',$variable2);
})->get();
Will produce query like bellow:
SELECT * FROM TABLE WHERE column1 = value1 and (column2 = value2 or column3 = value3) and (column4 = value4 and column5 = value5)
Here is a solution I came up with keeps 100% of the image and no crop is needed:
Basically I mirror tile the image in 3x3 grid then blur everything and then zoom in at the center image effectively creating like a repeat edges when blurring in after effects, it a bit strange that css3 don't have like a repeat edges built in.
Link to the method / code: How to blur an image using CSS3 without cropping or fading the edges?
Put your css/js files in folder src/main/webapp/resources
. Don't put them in WEB-INF
or src/main/resources
.
Then add this line to spring-dispatcher-servlet.xml
<mvc:resources mapping="/resources/**" location="/resources/" />
Include css/js files in jsp pages
<link href="<c:url value="/resources/style.css" />" rel="stylesheet">
Don't forget to declare taglib in your jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
If anybody else is facing this issue in Git for Windows and do not have curl-ca-bundle.crt
anywhere on your system even after reinstalling, this is the process I followed:
curl-**.**.*/lib
in the command line./mk-ca-bundle.prl
ca-bundle.crt
to your git path and update the config as listed in other answersShout out to this gist for helping me get the installation done.
Basically, flush() cleans out your RAM buffer, its real power is that it lets you continue to write to it afterwards - but it shouldn't be thought of as the best/safest write to file feature. It's flushing your RAM for more data to come, that is all. If you want to ensure data gets written to file safely then use close() instead.
If you are referring to the npm module sleep, it notes in the readme that sleep
will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:
setTimeout(function() {
console.log('hello world!');
}, 5000);
For anyone looking to do this using es7 async/await, this example should help:
const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));
const example = async () => {
console.log('About to snooze without halting the event loop...');
await snooze(1000);
console.log('done!');
};
example();
You can also use file_put_contents()
:
file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);
As far as I read manual pages, scanf says that 'l' length modifier indicates (in case of floating points) that the argument is of type double rather than of type float, so you can have 'lf, le, lg'.
As for printing, officially, the manual says that 'l' applies only to integer types. So it might be not supported on some systems or by some standards. For instance, I get the following error message when compiling with gcc -Wall -Wextra -pedantic
a.c:6:1: warning: ISO C90 does not support the ‘%lf’ gnu_printf format [-Wformat=]
So you may want to doublecheck if your standard supports the syntax.
To conclude, I would say that you read with '%lf' and you print with '%f'.
For database list:
show databases
show dbs
For table/collection list:
show collections
show tables
db.getCollectionNames()
That's something else then:
div.inline { float:left; }_x000D_
.clearBoth { clear:both; }
_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<br class="clearBoth" /><!-- you may or may not need this -->
_x000D_
May be it is the problem of using len()
for an integer value.
does not posses the len attribute in Python.
Error as:I will give u an example:
number= 1
print(len(num))
Instead of use ths,
data = [1,2,3,4]
print(len(data))
Didn't wan to mess with carbon. So here's my solution
$start = new \DateTime('now');
$start->modify('first day of this month');
$end = new \DateTime('now');
$end->modify('last day of this month');
$new_releases = Game::whereBetween('release', array($start, $end))->get();
After studying the Internet for a day I found my own solution for selecting an item after create a normal treeview in a normal WPF/C# environment
private void BuildSortTree(int sel)
{
MergeSort.Items.Clear();
TreeViewItem itTemp = new TreeViewItem();
itTemp.Header = SortList[0];
MergeSort.Items.Add(itTemp);
TreeViewItem prev;
itTemp.IsExpanded = true;
if (0 == sel) itTemp.IsSelected= true;
prev = itTemp;
for(int i = 1; i<SortList.Count; i++)
{
TreeViewItem itTempNEW = new TreeViewItem();
itTempNEW.Header = SortList[i];
prev.Items.Add(itTempNEW);
itTempNEW.IsExpanded = true;
if (i == sel) itTempNEW.IsSelected = true;
prev = itTempNEW ;
}
}
From System Preferences, turn on the "Show Keyboard & Character Viewer in menu bar" setting.
Then, the "Character Viewer" menu will pop up a tool that will let you search for any unicode character (by name) and insert it ? you're all set.
You can use JavaScript to do this, with onClick method. This maybe helps CSS3 transition click event
It worked for me.
Here is my test code. Test run follows:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
FileInfo f = new FileInfo(args[0]);
bool result = modifyFile(f, args[1],args[2]);
}
private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
Boolean result = false;
FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
StreamReader streamreader = file.OpenText();
String originalPath = file.FullName;
string input = streamreader.ReadToEnd();
Console.WriteLine("input : {0}", input);
String tempString = input.Replace(extractedMethod, modifiedMethod);
Console.WriteLine("replaced String {0}", tempString);
try
{
sw.Write(tempString);
sw.Flush();
sw.Close();
sw.Dispose();
fs.Close();
fs.Dispose();
streamreader.Close();
streamreader.Dispose();
File.Copy(originalPath, originalPath + ".old", true);
FileInfo newFile = new FileInfo(originalPath + ".tmp");
File.Delete(originalPath);
File.Copy(originalPath + ".tmp", originalPath, true);
result = true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return result;
}
}
}
C:\testarea>ConsoleApplication1.exe file.txt padding testing
input : <style type="text/css">
<!--
#mytable {
border-collapse: collapse;
width: 300px;
}
#mytable th,
#mytable td
{
border: 1px solid #000;
padding: 3px;
}
#mytable tr.highlight {
background-color: #eee;
}
//-->
</style>
replaced String <style type="text/css">
<!--
#mytable {
border-collapse: collapse;
width: 300px;
}
#mytable th,
#mytable td
{
border: 1px solid #000;
testing: 3px;
}
#mytable tr.highlight {
background-color: #eee;
}
//-->
</style>
Simply remove the .value
from your code.
Set envFrmwrkPath = ActiveSheet.Range("D6").Value
instead of this, use:
Set envFrmwrkPath = ActiveSheet.Range("D6")
This one works for me, I first try to get UTC
time, and then add or subtract hours according to the timezone you'd like to set.
today = datetime.utcnow()
Twitter now lets you send the URL through a data attribute. This works great for me:
<a href="javascript:;" class="twitter-share-button" data-lang="en" data-text="check out link b" data-url="http://www.lyricvideos.org/tracks?videoURL=SX05JZ4FisE">Tweet</a>
If this is a Windows app, try checking for a duplicate in the Global Assembly Cache (GAC). Something is overriding your bin / debug version.
If this is a web app, you may need to delete on server and re-upload. If you are publishing you may want to check the Delete all existing files prior to publish check box. Depending on Visual Studio version it should be located in Publish > Settings > File Publish Options
With my mercurial background I was going to use:
git log --patch -1 $ID > $file
But I am considering using git format-patch -1 $ID
now.
But an error occurred which says java.lang.NullPointerException.
Thats because, you never initialized your MainActivity. you should initialize your object before you call its methods.
MainActivity mActivity = new MainActivity();//make sure that you pass the appropriate arguments if you have an args constructor
mActivity.startChronometer();
A DATE
column does not have a format. You cannot specify a format for it.
You can use DateStyle
to control how PostgreSQL emits dates, but it's global and a bit limited.
Instead, you should use to_char
to format the date when you query it, or format it in the client application. Like:
SELECT to_char("date", 'DD/MM/YYYY') FROM mytable;
e.g.
regress=> SELECT to_char(DATE '2014-04-01', 'DD/MM/YYYY');
to_char
------------
01/04/2014
(1 row)
Based on the Enselic and Rahul answers.
It works for me (before and after API 21):
<CheckBox
android:id="@+id/checkbox"
android:layout_width="40dp"
android:layout_height="40dp"
android:text=""
android:gravity="center"
android:background="@drawable/checkbox_selector"
android:button="@null"
app:buttonCompat="@null" />
Finally, I found a solution to this problem without reinstalling npm and I'm posting it because in future it will help someone, Most of the time this error occurs javascript heap went out of the memory. As the error says itself this is not a problem with npm. Only we have to do is
instead of,
npm run build -prod
extend the javascript memory by following,
node --max_old_space_size=4096 node_modules/@angular/cli/bin/ng build --prod
You don't need to have unique id
for the elements, you can access them by their name
attribute:
If you're using name="Choose"
, then:
With jQuery it is as simple as:
$('input[name=Choose]').attr('checked',false);
or in pure JavaScript:
var ele = document.getElementsByName("Choose"); for(var i=0;i<ele.length;i++) ele[i].checked = false;
To directly answer the OP, take a look at this guy's site: Thomas Hunter Notepad++ Tidy for XML. Simple steps to follow and you get very nice formatting of your XML right inside NPP. So far the only anomaly I've found is with nested self closing elements EG:
<OuterTag>Text for outer element<SelfClosingTag/></OuterTag>
Will be tidied up to:
<OuterTag>Text for outer element
<SelfClosingTag/></OuterTag>
There may be a way to fix this, but for the time being, it's managed to reduce the number of lines in my document by 300k and this particular anomaly can be worked around.
It happens when upgrading to el capitan from yosemite. Virtual box needs to be installed again. Reinstalling geny motion does nothing. You will keep all your virtual devices unchanged.
I had a similar problem and was able to solve it by addressing my mysql with 127.0.0.1
instead of localhost
.
This probably means I've got something wrong in my hosts setup, but this quick fix get's me going for right now.
In this sample in catch block i change the value of counter and it will break while block:
class TestBreak {
public static void main(String[] a) {
int counter = 0;
while(counter<5) {
try {
counter++;
int x = counter/0;
}
catch(Exception e) {
counter = 1000;
}
}
}
}k
When trying to generate a random password you are trying to :
First generate a cryptographically secure set of random bytes
Second is turning those random bytes into a printable string
Now, there are multiple way to generate random bytes in php like :
$length = 32;
//PHP 7+
$bytes= random_bytes($length);
//PHP < 7
$bytes= openssl_random_pseudo_bytes($length);
Then you want to turn these random bytes into a printable string :
You can use bin2hex :
$string = bin2hex($bytes);
or base64_encode :
$string = base64_encode($bytes);
However, note that you do not control the length of the string if you use base64. You can use bin2hex to do that, using 32 bytes will turn into a 64 char string. But it will only work like so in an EVEN string.
So basically you can just do :
$length = 32;
if(PHP_VERSION>=7){
$bytes= random_bytes($length);
}else{
$bytes= openssl_random_pseudo_bytes($length);
}
$string = bin2hex($bytes);
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.
For those not willing to use jQuery here is a Vanilla Javascript way of doing the same using classList:
function runOnScroll() {
var element = document.getElementsByTagName('nav') ;
if(document.body.scrollTop >= 50) {
element[0].classList.add('shrink')
} else {
element[0].classList.remove('shrink')
}
console.log(topMenu[0].classList)
};
There might be a nicer way of doing it using toggle, but the above works fine in Chrome
Consider this to get a fully unique jar file:
Basic debugging using Spring's DebugFilter
can be configured like this:
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.debug(true);
}
}
var link = $(element); var offset = link.offset(); var top = offset.top; var left = offset.left; var bottom = top + link.outerHeight(); var right = left + link.outerWidth();
If you are using GCC to compile it for Windows, it's possible that the error is because dependent libraries can't be found.
Using the -static flag if linking with GCC might fix that.
Here is my modification of the currently accepted answer, which I believe it's a little faster and shorter:
private static Random random = new Random();
private string RandomString(int size) {
StringBuilder builder = new StringBuilder(size);
for (int i = 0; i < size; i++)
builder.Append((char)random.Next(0x41, 0x5A));
return builder.ToString();
}
Notice I didn't use all the multiplication, Math.floor()
, Convert
etc.
EDIT: random.Next(0x41, 0x5A)
can be changed to any range of Unicode characters.
To expand on Sandip’s answer, I had a bunch of strings showing up in the logs that were mis-coded in bit.ly. They meant to code just the URL but put a twitter handle and some other stuff after a space. It looked like this
? productID =26%20via%20@LFS
Normally, that would‘t be a problem, but I’m getting a lot of SQL injection attempts, so I redirect anything that isn’t a valid ID to a 404. I used the preg_replace method to make the invalid productID string into a valid productID.
$productID=preg_replace('/[\s]+.*/','',$productID);
I look for a space in the URL and then remove everything after it.
To everyone who said that this is a bad idea I want to say it is not always a bad one. Sometimes it is very boring to have to zoom out to see all the content. For example when you type on an input on iOS it zooms to get it in the center of the screen. You have to zoom out after that cause closing the keyboard does not do the work. Also I agree that when you put many I hours in making a great layout and user experience you don't want it to be messed up by a zoom.
But the other argument is valuable as well for people with vision issues. However In my opinion if you have issues with your eyes you are already using the zooming features of the system so there is no need to disturb the content.
I stumbled across this article looking for a similar answer. I read @vsync example Using javascript's Number.prototype.toLocaleString: and it appeared to work well. The only complaint I had was that if you had more than a single input type="currency"
within your page it would only modify the first instance of it.
As he mentions in his comments it was only designed as an example for stackoverflow.
However, the example worked well for me and although I have little experience with JS I figured out how to modify it so that it will work with multiple input type="currency"
on the page using the document.querySelectorAll
rather than document.querySelector
and adding a for loop.
I hope this can be useful for someone else. ( Credit for the bulk of the code is @vsync )
var currencyInput = document.querySelectorAll( 'input[type="currency"]' );
for ( var i = 0; i < currencyInput.length; i++ ) {
var currency = 'GBP'
onBlur( {
target: currencyInput[ i ]
} )
currencyInput[ i ].addEventListener( 'focus', onFocus )
currencyInput[ i ].addEventListener( 'blur', onBlur )
function localStringToNumber( s ) {
return Number( String( s ).replace( /[^0-9.-]+/g, "" ) )
}
function onFocus( e ) {
var value = e.target.value;
e.target.value = value ? localStringToNumber( value ) : ''
}
function onBlur( e ) {
var value = e.target.value
var options = {
maximumFractionDigits: 2,
currency: currency,
style: "currency",
currencyDisplay: "symbol"
}
e.target.value = ( value || value === 0 ) ?
localStringToNumber( value ).toLocaleString( undefined, options ) :
''
}
}
var currencyInput = document.querySelectorAll( 'input[type="currency"]' );
for ( var i = 0; i < currencyInput.length; i++ ) {
var currency = 'GBP'
onBlur( {
target: currencyInput[ i ]
} )
currencyInput[ i ].addEventListener( 'focus', onFocus )
currencyInput[ i ].addEventListener( 'blur', onBlur )
function localStringToNumber( s ) {
return Number( String( s ).replace( /[^0-9.-]+/g, "" ) )
}
function onFocus( e ) {
var value = e.target.value;
e.target.value = value ? localStringToNumber( value ) : ''
}
function onBlur( e ) {
var value = e.target.value
var options = {
maximumFractionDigits: 2,
currency: currency,
style: "currency",
currencyDisplay: "symbol"
}
e.target.value = ( value || value === 0 ) ?
localStringToNumber( value ).toLocaleString( undefined, options ) :
''
}
}
_x000D_
.input_date {
margin:1px 0px 50px 0px;
font-family: 'Roboto', sans-serif;
font-size: 18px;
line-height: 1.5;
color: #111;
display: block;
background: #ddd;
height: 50px;
border-radius: 5px;
border: 2px solid #111111;
padding: 0 20px 0 20px;
width: 100px;
}
_x000D_
<label for="cost_of_sale">Cost of Sale</label>
<input class="input_date" type="currency" name="cost_of_sale" id="cost_of_sale" value="0.00">
<label for="sales">Sales</label>
<input class="input_date" type="currency" name="sales" id="sales" value="0.00">
<label for="gm_pounds">GM Pounds</label>
<input class="input_date" type="currency" name="gm_pounds" id="gm_pounds" value="0.00">
_x000D_
Does playsinline
attribute help?
Here's what I have:
<video autoplay loop muted playsinline class="video-background ">
<source src="videos/intro-video3.mp4" type="video/mp4">
</video>
See the comment on playsinline
here: https://webkit.org/blog/6784/new-video-policies-for-ios/
For Windows 7 and above go to C:\Users\USERNAME\.android folder and follow below steps:
repositories.cfg
For my own future reference:
With cx_Oracle use cursor.setinputsize(...):
mycursor = connection.cursor();
mycursor.setinputsize( mytimestamp=cx_Oracle.TIMESTAMP );
params = { 'mytimestamp': timestampVar };
cusrsor.execute("INSERT INTO mytable (timestamp_field9 VALUES(:mytimestamp)", params);
No converting in the db needed. See Oracle Documentation
OffsetDateTime.parse ( "2010-01-01T12:00:00+01:00" )
The new java.time package in Java 8 and later was inspired by Joda-Time.
The OffsetDateTime
class represents a moment on the timeline with an offset-from-UTC but not a time zone.
OffsetDateTime odt = OffsetDateTime.parse ( "2010-01-01T12:00:00+01:00" );
Calling toString
generates a string in standard ISO 8601 format:
2010-01-01T12:00+01:00
To see the same value through the lens of UTC, extract an Instant
or adjust the offset from +01:00
to 00:00
.
Instant instant = odt.toInstant();
…or…
OffsetDateTime odtUtc = odt.withOffsetSameInstant( ZoneOffset.UTC );
Adjust into a time zone if desired. A time zone is a history of offset-from-UTC values for a region, with a set of rules for handling anomalies such as Daylight Saving Time (DST). So apply a time zone rather than a mere offset whenever possible.
ZonedDateTime zonedDateTimeMontréal = odt.atZoneSameInstant( ZoneId.of( "America/Montreal" ) );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Chances are you are struggling with the node.js dying whenever the server you are calling refuses to connect. Try this:
process.on('uncaughtException', function (err) {
console.log(err);
});
This keeps your server running and also give you a place to attach the debugger and look for a deeper problem.
I do not pretend the right to be right, but lets see this small example:
public interface CarConstants {
static final String ENGINE = "mechanical";
static final String WHEEL = "round";
// ...
}
public interface ToyotaCar extends CarConstants //, ICar, ... {
void produce();
}
public interface FordCar extends CarConstants //, ICar, ... {
void produce();
}
// and this is implementation #1
public class CamryCar implements ToyotaCar {
public void produce() {
System.out.println("the engine is " + ENGINE );
System.out.println("the wheel is " + WHEEL);
}
}
// and this is implementation #2
public class MustangCar implements FordCar {
public void produce() {
System.out.println("the engine is " + ENGINE );
System.out.println("the wheel is " + WHEEL);
}
}
ToyotaCar doesnt know anything about FordCar, and FordCar doesnt know about ToyotaCar. principle CarConstants should be changed, but...
Constants should not be changed, because the wheel is round and egine is mechanical, but... In the future Toyota's research engineers invented electronic engine and flat wheels! Lets see our new interface
public interface InnovativeCarConstants {
static final String ENGINE = "electronic";
static final String WHEEL = "flat";
// ...
}
and now we can change our abstraction:
public interface ToyotaCar extends CarConstants
to
public interface ToyotaCar extends InnovativeCarConstants
And now if we ever need to change the core value if the ENGINE or WHEEL we can change the ToyotaCar Interface on abstraction level, dont touching implementations
Its NOT SAFE, I know, but I still want to know that do you think about this
JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?
To get value you can use now different ways:
console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?
new DecimalFormat("#0.##").format(bd)
As a newbie in React world, I came across a similar issues where I could not edit
the textarea and struggled
with binding. It's worth knowing about controlled
and uncontrolled
elements when it comes to react.
The value of the following uncontrolled textarea
cannot be changed because of value
<textarea type="text" value="some value"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following uncontrolled textarea
can be changed because of use of defaultValue
or no value attribute
<textarea type="text" defaultValue="sample"
onChange={(event) => this.handleOnChange(event)}></textarea>
<textarea type="text"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following controlled textarea
can be changed because of how
value is mapped to a state as well as the onChange
event listener
<textarea value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
Here is my solution using different syntax. I prefer the auto-bind
than manual binding however, if I were to not use {(event) => this.onXXXX(event)}
then that would cause the content of textarea
to be not editable OR the event.preventDefault()
does not work as expected. Still a lot to learn I suppose.
class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
textareaValue: ''
}
}
handleOnChange(event) {
this.setState({
textareaValue: event.target.value
})
}
handleOnSubmit(event) {
event.preventDefault();
this.setState({
textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
})
}
render() {
return <div>
<form onSubmit={(event) => this.handleOnSubmit(event)}>
<textarea rows={10} cols={30} value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
<br/>
<input type="submit" value="Save"/>
</form>
</div>
}
}
ReactDOM.render(<Editor />, document.getElementById("content"));
The versions of libraries are
"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4"
$(document).ready(function(){
$("#send").click(function()
{
$.ajax({
type: "POST",
url: base_url + "chat/post_action",
data: {textbox: $("#textbox").val()},
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
});// you have missed this bracket
return false;
});
});
Ok, I solved it. Writing it for anyone who might be tired after a full day of non-stop coding & miss such a silly thing.
@RequestMapping(value="/fetch" , method=RequestMethod.GET)
public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
//Content goes here
}
Yes, it's simple. Just add the DateTimeFormat annotation.
To bash into a running container, type this:
docker exec -t -i container_name /bin/bash
or
docker exec -ti container_name /bin/bash
or
docker exec -ti container_name sh
If you remove [DataType(DataType.Date)]
from your model, the input field in Chrome is rendered as type="datetime"
and won't show the datepicker either.
assuming input[row][col]
rows = len(input)
cols = len(list(zip(*input)))
import javax.swing.JOptionPane;
import javax.swing.JFrame;
/*Some piece of code*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (JOptionPane.showConfirmDialog(frame,
"Are you sure you want to close this window?", "Close Window?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
If you also want to prevent the window from closing unless the user chooses 'Yes', you can add:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
You can use the request object to find the logged in user
def my_view(request):
username = None
if request.user.is_authenticated():
username = request.user.username
According to https://docs.djangoproject.com/en/2.0/releases/1.10/
In version Django 2.0 the syntax has changed to
request.user.is_authenticated
First I recommand you can try use print and observe the action:
for i in range(0, 5, 1):
print i
the result:
0
1
2
3
4
You can understand the function principle.
In fact, range
scan range is from 0
to 5-1
.
It equals 0 <= i < 5
When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.
You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.
for i in range(5, 0, -1):
print i
the result:
5
4
3
2
1
Thus it can be seen, it equals 5 >= i > 0
You want to implement your java code in python:
for (int index = last-1; index >= posn; index--)
It should code this:
for i in range(last-1, posn-1, -1)
In latest 5.13 there's a difference. You do like always...
font-family: "Font Awesome 5 Free";
content: "\f107";
But there's a difference now... Instead of use font-weight: 500; You are following this:
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f107";
Why is that? I figure out by finding in in .fas class, so you can figure out an updated way by looking into .fas class so you're doing the same as it has to be. Figure out if there's a font-weight and font-family. Here you go guys. That's an update answer for 5.13.
In your case both are equivalent!
Synchronizing a static method is equivalent to a synchronized block on corresponding Class object.
In fact when you declare a synchronized static method lock is obtained on the monitor corresponding to the Class object.
public static synchronized int getCount() {
// ...
}
is same as
public int getCount() {
synchronized (ClassName.class) {
// ...
}
}
Make sure that your windows host file (located at c://windows/system32/drivers/etc.host
) has following line. If not, add it at the end
127.0.0.1 localhost
::1 localhost
Sometimes mysql can not trigger Windows to force start host services if firewall blocks it, so start it manually
win+run>>services.msc, select the "MySQL_xx" where "xx" is the name you have assigned to MySQL host services during setup. Click on 'start' to start from hyperlink appeared on left side.
Use the super()
function:
class Foo(Bar):
def baz(self, arg):
return super().baz(arg)
For Python < 3, you must explicitly opt in to using new-style classes and use:
class Foo(Bar):
def baz(self, arg):
return super(Foo, self).baz(arg)
The solution is so easy. Only right click the IMAGE (destination) folder, go to properties, click the permission tab, and change others access to Create and delete files.
On Ubuntu you can install it for the system Python with
sudo apt install python3-opencv
A short summary of the above great answers:
git difftool --tool-help
git config --global diff.tool <chosen tool>
git config --global --add difftool.prompt false
Then use it by typing (optionally specifying file name as well):
git difftool
Actualy the Gabin Smith's answer needs to be changed a bit to work, because you can't resume with without an error.
Sub MyFunc()
...
For Each oSheet In ActiveWorkbook.Sheets
On Error GoTo errHandler:
Set qry = oSheet.ListObjects(1).QueryTable
oCmbBox.AddItem oSheet.name
...
NextSheet:
Next oSheet
...
Exit Sub
errHandler:
Resume NextSheet
End Sub
If your images are small, consider storing them as base64 in a plain text field.
The reason is that while base64 has an overhead of 33%, with compression that mostly goes away. (See What is the space overhead of Base64 encoding?) Your database will be bigger, but the packets your webserver sends to the client won't be. In html, you can inline base64 in an <img src=""> tag, which can possibly simplify your app because you won't have to serve up the images as binary in a separate browser fetch. Handling images as text also simplifies things when you have to send/receive json, which doesn't handle binary very well.
Yes, I understand you could store the binary in the database and convert it to/from text on the way in and out of the database, but sometimes ORMs make that a hassle. It can be simpler just to treat it as straight text just like all your other fields.
This is definitely the right way to handle thumbnails.
(OP's images are not small, so this is not really an answer to his question.)
JavaScript's Date
object tracks time in UTC internally, but typically accepts input and produces output in the local time of the computer it's running on. It has very few facilities for working with time in other time zones.
The internal representation of a Date
object is a single number, representing the number of milliseconds that have elapsed since 1970-01-01 00:00:00 UTC
, without regard to leap seconds. There is no time zone or string format stored in the Date object itself. When various functions of the Date
object are used, the computer's local time zone is applied to the internal representation. If the function produces a string, then the computer's locale information may be taken into consideration to determine how to produce that string. The details vary per function, and some are implementation-specific.
The only operations the Date
object can do with non-local time zones are:
It can parse a string containing a numeric UTC offset from any time zone. It uses this to adjust the value being parsed, and stores the UTC equivalent. The original local time and offset are not retained in the resulting Date
object. For example:
var d = new Date("2020-04-13T00:00:00.000+08:00");
d.toISOString() //=> "2020-04-12T16:00:00.000Z"
d.valueOf() //=> 1586707200000 (this is what is actually stored in the object)
In environments that have implemented the ECMASCript Internationalization API (aka "Intl"), a Date
object can produce a locale-specific string adjusted to a given time zone identifier. This is accomplished via the timeZone
option to toLocaleString
and its variations. Most implementations will support IANA time zone identifiers, such as 'America/New_York'
. For example:
var d = new Date("2020-04-13T00:00:00.000+08:00");
d.toLocaleString('en-US', { timeZone: 'America/New_York' })
//=> "4/12/2020, 12:00:00 PM"
// (midnight in China on Apring 13th is noon in New York on April 12th)
Most modern environments support the full set of IANA time zone identifiers (see the compatibility table here). However, keep in mind that the only identifier required to be supported by Intl is 'UTC'
, thus you should check carefully if you need to support older browsers or atypical environments (for example, lightweight IoT devices).
There are several libraries that can be used to work with time zones. Though they still cannot make the Date
object behave any differently, they typically implement the standard IANA timezone database and provide functions for using it in JavaScript. Modern libraries use the time zone data supplied by the Intl API, but older libraries typically have overhead, especially if you are running in a web browser, as the database can get a bit large. Some of these libraries also allow you to selectively reduce the data set, either by which time zones are supported and/or by the range of dates you can work with.
Here are the libraries to consider:
Intl-based Libraries
New development should choose from one of these implementations, which rely on the Intl API for their time zone data:
Non-Intl Libraries
These libraries are maintained, but carry the burden of packaging their own time zone data, which can be quite large.
* While Moment and Moment-Timezone were previously recommended, the Moment team now prefers users chose Luxon for new development.
Discontinued Libraries
These libraries have been officially discontinued and should no longer be used.
The TC39 Temporal Proposal aims to provide a new set of standard objects for working with dates and times in the JavaScript language itself. This will include support for a time zone aware object.
def exit(self):
self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)
This worked for me to destroy my Tkinter frame on clicking the exit button.
angle(vector.b,vector.a)=pi/2*((1+sgn(xa))*(1-sgn(ya^2))-(1+sgn(xb))*(1-sgn(yb^2)))
+pi/4*((2+sgn(xa))*sgn(ya)-(2+sgn(xb))*sgn(yb))
+sgn(xa*ya)*atan((abs(xa)-abs(ya))/(abs(xa)+abs(ya)))
-sgn(xb*yb)*atan((abs(xb)-abs(yb))/(abs(xb)+abs(yb)))
xb,yb and xa,ya are the coordinates of the two vectors
How about the quick and dirty translate function?
This will remove all occurrences of each character in string1:
SELECT translate(
translate(
translate(string1, CHR(10), '')
, CHR(13), '')
, CHR(09), '') as massaged
FROM BLAH;
Regexp_replace is an option, but you may see a performance hit depending on how complex your expression is.
For anyone else who wants to set Eclipse style goto definition, you need to create .sublime-mousemap
file in Sublime User
folder.
Windows - create Default (Windows).sublime-mousemap
in %appdata%\Sublime Text 3\Packages\User
Linux - create Default (Linux).sublime-mousemap
in ~/.config/sublime-text-3/Packages/User
Mac - create Default (OSX).sublime-mousemap
in ~/Library/Application Support/Sublime Text 3/Packages/User
Now open that file and put the following configuration inside
[
{
"button": "button1",
"count": 1,
"modifiers": ["ctrl"],
"press_command": "drag_select",
"command": "goto_definition"
}
]
You can change modifiers
key as you like.
Since Ctrl-button1
on Windows and Linux is used for multiple selections, adding a second modifier key like Alt might be a good idea if you want to use both features:
[
{
"button": "button1",
"count": 1,
"modifiers": ["ctrl", "alt"],
"press_command": "drag_select",
"command": "goto_definition"
}
]
Alternatively, you could use the right mouse button (button2
) with Ctrl alone, and not interfere with any built-in functions.
This is how I managed to do what I was trying to do:
[Test]
public void TransferHandlesDisconnect()
{
// ... set up config here
var methodTester = new Mock<Transfer>(configInfo);
methodTester.CallBase = true;
methodTester
.Setup(m =>
m.GetFile(
It.IsAny<IFileConnection>(),
It.IsAny<string>(),
It.IsAny<string>()
))
.Throws<System.IO.IOException>();
methodTester.Object.TransferFiles("foo1", "foo2");
Assert.IsTrue(methodTester.Object.Status == TransferStatus.TransferInterrupted);
}
If there is a problem with this method, I would like to know; the other answers suggest I am doing this wrong, but this was exactly what I was trying to do.
If you are looking for the diff on a specific commit and you want to use the github UI instead of the command line (say you want to link it to other folks), you can do:
https://github.com/<org>/<repo>/commit/<commit-sha>/<path-to-file>
For example:
Note the Previous and Next links at the top right that allow you to navigate through all the files in the commit.
This only works for a specific commit though, not for comparing between any two arbitrary versions.
Read this article for better insight. Note: Numpy reports the shape of 3D arrays in the order layers, rows, columns.
Here what's technet has to say about iisreset
You might need to restart Internet Information Services (IIS) before certain configuration changes take effect or when applications become unavailable. Restarting IIS is the same as first stopping IIS, and then starting it again, except it is accomplished with a single command.
$(document).ready(function () {
$('.dates li a').click(function (e) {
$('.dates li a').removeClass('active');
var $parent = $(this);
if (!$parent.hasClass('active')) {
$parent.addClass('active');
}
e.preventDefault();
});
});
Another variant:
List<MyType> items = new List<MyType>();
items.AddRange(myDico.values);
use dependency maven:
groupId: net.sf.extcos
artifactId: extcos
version: 0.4b
then use this code :
ComponentScanner scanner = new ComponentScanner();
Set classes = scanner.getClasses(new ComponentQuery() {
@Override
protected void query() {
select().from("com.leyton").returning(allExtending(DynamicForm.class));
}
});
The setReadOnly(state) is very useful for forms, we can set any field to setReadOnly(state) directly or from various condition.But I prefer to use readOnly for setting opacity to the selector otherwise the attr='disabled' also worked like the same way.
readOnly examples:
$('input').setReadOnly(true);
or through the various codition like
var same = this.checked;
$('input').setReadOnly(same);
here we are using the state boolean value to set and remove readonly attribute from the input depending on a checkbox click.
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
I think this will do it:
SELECT * FROM MyTable WHERE mydate > now()::date - 365;
DataFrame
object has powerful and flexible replace
method:
DataFrame.replace(
to_replace=None,
value=None,
inplace=False,
limit=None,
regex=False,
method='pad',
axis=None)
Note, if you need to make changes in place, use inplace
boolean argument for replace
method:
inplace: boolean, default
False
IfTrue
, in place. Note: this will modify any other views on this object (e.g. a column form a DataFrame). Returns the caller if this isTrue
.
df['BrandName'].replace(
to_replace=['ABC', 'AB'],
value='A',
inplace=True
)
Initializations with (...)
in the class body is not allowed. Use {..}
or = ...
. Unfortunately since the respective constructor is explicit
and vector
has an initializer list constructor, you need a functional cast to call the wanted constructor
vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);
As an alternative you can use constructor initializer lists
Attribute():name(5), val(5, 0) {}
If you are sure you want to remove all commit history, simply delete the .git
directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:
git init
git remote add origin [email protected]:user/repo
now commit your current version of code
git add *
git commit -am 'message'
and finally force the update to GitHub:
git push -f origin master
However, I suggest backing up the history (the .git
folder in the repository) before taking these steps!
Careful:
$array = (array) $object;
does a shallow conversion ($object->innerObject = new stdClass() remains an object) and converting back and forth using json works but it's not a good idea if performance is an issue.
If you need all objects to be converted to associative arrays here is a better way to do that (code ripped from I don't remember where):
function toArray($obj)
{
if (is_object($obj)) $obj = (array)$obj;
if (is_array($obj)) {
$new = array();
foreach ($obj as $key => $val) {
$new[$key] = toArray($val);
}
} else {
$new = $obj;
}
return $new;
}
If the mouse over for all over the component is your option, you can directly is @hostListener
to handle the events to perform the mouse over al below.
import {HostListener} from '@angular/core';
@HostListener('mouseenter') onMouseEnter() {
this.hover = true;
this.elementRef.nativeElement.addClass = 'edit';
}
@HostListener('mouseleave') onMouseLeave() {
this.hover = false;
this.elementRef.nativeElement.addClass = 'un-edit';
}
Its available in @angular/core
. I tested it in angular 4.x.x
char*
is a mutable pointer to a mutable character/string.
const char*
is a mutable pointer to an immutable character/string. You cannot change the contents of the location(s) this pointer points to. Also, compilers are required to give error messages when you try to do so. For the same reason, conversion from const char *
to char*
is deprecated.
char* const
is an immutable pointer (it cannot point to any other location) but the contents of location at which it points are mutable.
const char* const
is an immutable pointer to an immutable character/string.
Actually for some reason wireshark uses two different kind of filter syntax one on display filter and other on capture filter. Display filter is only useful to find certain traffic just for display purpose only. its like you are interested in all trafic but for now you just want to see specific.
but if you are interested only in certian traffic and does not care about other at all then you use the capture filter.
The Syntax for display filter is (as mentioned earlier)
ip.addr = x.x.x.x
or
ip.src = x.x.x.x
or
ip.dst = x.x.x.x
but above syntax won't work in capture filters, following are the filters
host x.x.x.x
see more example on wireshark wiki page
You can use JSON.stringify() method to convert JSON object to String.
var j={"name":"hello world"};
JSON.stringify(j);
To convert this string back to json object, you can use JSON.parse() method.
replace all seperator: (\W)
with seperator + new_seperator: (\W;)
split by the new_seperator: (;)
def split_and_keep(seperator, s):
return re.split(';', re.sub(seperator, lambda match: match.group() + ';', s))
print('\W', 'foo/bar spam\neggs')
I liked @mate64's answer so I am going to reuse that with slight modifications to create a slide down and up animations below:
var $slider = document.getElementById('slider');_x000D_
var $toggle = document.getElementById('toggle');_x000D_
_x000D_
$toggle.addEventListener('click', function() {_x000D_
var isOpen = $slider.classList.contains('slide-in');_x000D_
_x000D_
$slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');_x000D_
});
_x000D_
#slider {_x000D_
position: absolute;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: blue;_x000D_
transform: translateY(-100%);_x000D_
-webkit-transform: translateY(-100%);_x000D_
}_x000D_
_x000D_
.slide-in {_x000D_
animation: slide-in 0.5s forwards;_x000D_
-webkit-animation: slide-in 0.5s forwards;_x000D_
}_x000D_
_x000D_
.slide-out {_x000D_
animation: slide-out 0.5s forwards;_x000D_
-webkit-animation: slide-out 0.5s forwards;_x000D_
}_x000D_
_x000D_
@keyframes slide-in {_x000D_
100% { transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-in {_x000D_
100% { -webkit-transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@keyframes slide-out {_x000D_
0% { transform: translateY(0%); }_x000D_
100% { transform: translateY(-100%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-out {_x000D_
0% { -webkit-transform: translateY(0%); }_x000D_
100% { -webkit-transform: translateY(-100%); }_x000D_
}
_x000D_
<div id="slider" class="slide-in">_x000D_
<ul>_x000D_
<li>Lorem</li>_x000D_
<li>Ipsum</li>_x000D_
<li>Dolor</li>_x000D_
</ul>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
I believe this would be somewhere close.
INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs
Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max)
. It was not tested with image as data type.
Yes:
git rev-parse --show-toplevel
If you want to replicate the Git command more directly, you can create an alias:
git config --global alias.root 'rev-parse --show-toplevel'
and now git root
will function just as hg root
.
Note: In a submodule this will display the root directory of the submodule and not the parent repository. If you are using Git >=2.13 or above, there is a way that submodules can show the superproject's root directory. If your git is older than that, see this other answer.
Using control-z suspends the process (see the output from stty -a
which lists the key stroke under susp
). That leaves it running, but in suspended animation (so it is not using any CPU resources). It can be resumed later.
If you want to stop a program permanently, then any of interrupt (often control-c) or quit (often control-\) will stop the process, the latter producing a core dump (unless you've disabled them). You might also use a HUP or TERM signal (or, if really necessary, the KILL signal, but try the other signals first) sent to the process from another terminal; or you could use control-z to suspend the process and then send the death threat from the current terminal, and then bring the (about to die) process back into the foreground (fg
).
Note that all key combinations are subject to change via the stty
command or equivalents; the defaults may vary from system to system.
New and neat in Python 3.5:
[*map(chr, [66, 53, 0, 94])]
Thanks to Additional Unpacking Generalizations
UPDATE
Always seeking for shorter ways, I discovered this one also works:
*map(chr, [66, 53, 0, 94]),
Unpacking works in tuples too. Note the comma at the end. This makes it a tuple of 1 element. That is, it's equivalent to (*map(chr, [66, 53, 0, 94]),)
It's shorter by only one char from the version with the list-brackets, but, in my opinion, better to write, because you start right ahead with the asterisk - the expansion syntax, so I feel it's softer on the mind. :)
You can test the unsigned-apk only on Emulator. And as its step of application deployment and distribution, you should read this article atleast once, i suggest: http://developer.android.com/guide/publishing/app-signing.html.
For your question, you can find the below line in above article:
All applications must be signed. The system will not install an application that is not signed.
so you have to have signed-apk before the distribution of your application.
To generate Signed-apk of your application, there is a simple wizard procedure, click on File -> Export -> Android -> Export Android application.
Here is the configuration for those trying to accomplish the original goal (wildcards all pointing to same codebase -- install nothing, dev environment ie, XAMPP)
file: /etc/hosts (non-windows)
127.0.0.1 example.local
file: /XAMPP/etc/httpd.conf
# Virtual hosts
Include etc/extra/httpd-vhosts.conf
file: XAMPP/etc/extra/httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/path_to_XAMPP/htdocs"
ServerName example.local
ServerAlias *.example.local
# SetEnv APP_ENVIRONMENT development
# ErrorLog "logs/example.local-error_log"
# CustomLog "logs/example.local-access_log" common
</VirtualHost>
restart apache
save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)
function FindProxyForURL(url, host) {
if (shExpMatch(host, "*example.local")) {
return "PROXY example.local";
}
return "DIRECT";
}
You could try attaching handlers to various events of BitmapImage:
They might tell you a little about what's going on, as far as the image is concerned.
you can read this doc .this concept is well explained here http://developer.android.com/training/basics/fragments/communicating.html
Here is the code for it.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="@+id/static_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp" />
<Spinner
android:id="@+id/dynamic_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Ahotbrew.com - Dropdown</string>
<string-array name="brew_array">
<item>Cappuccino</item>
<item>Espresso</item>
<item>Mocha</item>
<item>Caffè Americano</item>
<item>Cafe Zorro</item>
</string-array>
MainActivity
Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
// Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
.createFromResource(this, R.array.brew_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
staticAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
staticSpinner.setAdapter(staticAdapter);
Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);
String[] items = new String[] { "Chai Latte", "Green Tea", "Black Tea" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
dynamicSpinner.setAdapter(adapter);
dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
This example is from http://www.ahotbrew.com/android-dropdown-spinner-example/
I also noticed that you can provide a group of coroutines in wait() by simply specifying the list:
result=loop.run_until_complete(asyncio.wait([
say('first hello', 2),
say('second hello', 1),
say('third hello', 4)
]))
Whereas grouping in gather() is done by just specifying multiple coroutines:
result=loop.run_until_complete(asyncio.gather(
say('first hello', 2),
say('second hello', 1),
say('third hello', 4)
))
In case anyone else needs to add padding to something with background-image and background-size: contain or cover, I used the following which is a nice way of doing it. You can replace the border-width with 10% or 2vw or whatever you like.
.bg-image {
background: url("/image/logo.png") no-repeat center #ffffff / contain;
border: inset 10px transparent;
box-sizing: border-box;
}
This means you don't have to define a width.
You can manipulate :disabled
attribute in vue.js.
It will accept a boolean, if it's true, then the input gets disabled, otherwise it will be enabled...
Something like structured like below in your case for example:
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="validated ? false : true">
Also read this below:
Conditionally Disabling Input Elements via JavaScript Expression
You can conditionally disable input elements inline with a JavaScript expression. This compact approach provides a quick way to apply simple conditional logic. For example, if you only needed to check the length of the password, you may consider doing something like this.
<h3>Change Your Password</h3>
<div class="form-group">
<label for="newPassword">Please choose a new password</label>
<input type="password" class="form-control" id="newPassword" placeholder="Password" v-model="newPassword">
</div>
<div class="form-group">
<label for="confirmPassword">Please confirm your new password</label>
<input type="password" class="form-control" id="confirmPassword" placeholder="Password" v-model="confirmPassword" v-bind:disabled="newPassword.length === 0 ? true : false">
</div>
To make a global variable, just declare it without the var
keyword. (Generally speaking this isn't best practice, but in some cases it can be useful - just be careful as it will make the variable available everywhere.)
Here's an example from visionmedia/screenshot-app
file app.js:
/**
* Module dependencies.
*/
var express = require('express')
, stylus = require('stylus')
, redis = require('redis')
, http = require('http');
app = express();
//... require() route files
file routes/main.js
//we can now access 'app' without redeclaring it or passing it in...
/*
* GET home page.
*/
app.get('/', function(req, res, next){
res.render('index');
});
//...
With ggplot2
:
p<-qplot(spray,count,data=InsectSprays,geom='boxplot')
p<-p+stat_summary(fun.y=mean,shape=1,col='red',geom='point')
print(p)
All links to the Azure Active Directory Connection page now seem to be invalid.
I had an older version of Azure AD installed too, this is what worked for me. Install this.
Run these in an elevated PS session:
uninstall-module AzureAD # this may or may not be needed
install-module AzureAD
install-module AzureADPreview
install-module MSOnline
I was then able to log in and run what I needed.
In some cases you should use:
req.path
This gives you the path, instead of the complete requested URL. For example, if you are only interested in which page the user requested and not all kinds of parameters the url:
/myurl.htm?allkinds&ofparameters=true
req.path will give you:
/myurl.html
This code example that follows shows a basic UILabel
configuration.
let lbl = UILabel(frame: CGRectMake(0, 0, 300, 200))
lbl.text = "yourString"
// Enum type, two variations:
lbl.textAlignment = NSTextAlignment.Right
lbl.textAlignment = .Right
lbl.textColor = UIColor.red
lbl.shadowColor = UIColor.black
lbl.font = UIFont(name: "HelveticaNeue", size: CGFloat(22))
self.view.addSubview(lbl)
How about :
SQL> select * from all_users;
it will return list of all users/schemas, their ID's and date created in DB :
USERNAME USER_ID CREATED
------------------------------ ---------- ---------
SCHEMA1 120 09-SEP-15
SCHEMA2 119 09-SEP-15
SCHEMA3 118 09-SEP-15
You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.
The best solution is the attribute selector in CSS (input[type="text"]
) as the others suggested.
But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.
In this case your only option seems to be to define classes on input elements.
<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...
and target them with a class selector:
input.input-box, textarea { background: cyan; }
One way would be:
while read NAME
do
echo "$NAME"
done < names.txt
EDIT:
Note that the loop gets executed in a sub-shell, so any modified variables will be local, except if you declare them with declare
outside the loop.
Dennis Williamson is right. Sorry, must have used piped constructs too often and got confused.
It's broken in the exact same way decimal (base-10) notation is broken, just for base-2.
To understand, think about representing 1/3 as a decimal value. It's impossible to do exactly! In the same way, 1/10 (decimal 0.1) cannot be represented exactly in base 2 (binary) as a "decimal" value; a repeating pattern after the decimal point goes on forever. The value is not exact, and therefore you can't do exact math with it using normal floating point methods.
command > file >&1