You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.
Without having to change your button group at all, you can do the following. Below, I assume your dropdown button
has an id
of fldCategory
.
<script type="text/javascript">
$(document).ready(function(){
$('#fldCategory').parent().find('UL LI A').click(function (e) {
var sVal = e.currentTarget.text;
$('#fldCategory').html(sVal + ' <span class="caret"></span>');
console.log(sVal);
});
});
</script>
Now, if you set the .btn-group
of this item itself to have the id
of fldCategory
, that's actually more efficient jQuery and runs a little faster:
<script type="text/javascript">
$(document).ready(function(){
$('#fldCategory UL LI A').click(function (e) {
var sVal = e.currentTarget.text;
$('#fldCategory BUTTON').html(sVal + ' <span class="caret"></span>');
console.log(sVal);
});
});
</script>
I don't have MySQL, but there are RDBMS (Postgres, among others) in which you can use the hack
SELECT id || '' FROM some_table;
The concatenate does an implicit conversion.
You can try to use:
where(date: p[:date]..Float::INFINITY)
equivalent in sql
WHERE (`date` >= p[:date])
The result is:
Note.where(user_id: current_user.id, notetype: p[:note_type], date: p[:date]..Float::INFINITY).order(:fecha, :created_at)
And I have changed too
order('date ASC, created_at ASC')
For
order(:fecha, :created_at)
make your class public
access modifier,
just add public
keyword infront of your class name
namespace Test
{
public class Delivery
{
private string name;
private string address;
private DateTime arrivalTime;
public string Name
{
get { return name; }
set { name = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public DateTime ArrivlaTime
{
get { return arrivalTime; }
set { arrivalTime = value; }
}
public string ToString()
{
{ return name + address + arrivalTime.ToString(); }
}
}
}
See it in Activity Lifecycle (at Android Developers).
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
Called after your activity has been stopped, prior to it being started again. Always followed by onStart()
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground.
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause().
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity. Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between> these two scenarios with the isFinishing() method.
When the Activity first time loads the events are called as below:
onCreate()
onStart()
onResume()
When you click on Phone button the Activity goes to the background and the below events are called:
onPause()
onStop()
Exit the phone dialer and the below events will be called:
onRestart()
onStart()
onResume()
When you click the back button OR try to finish() the activity the events are called as below:
onPause()
onStop()
onDestroy()
The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime:
These states can be broken into three main groups as follows:
Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.
Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.
Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.
*Sample activity to understand the life cycle**
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
String tag = "LifeCycleEvents";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(tag, "In the onCreate() event");
}
public void onStart()
{
super.onStart();
Log.d(tag, "In the onStart() event");
}
public void onRestart()
{
super.onRestart();
Log.d(tag, "In the onRestart() event");
}
public void onResume()
{
super.onResume();
Log.d(tag, "In the onResume() event");
}
public void onPause()
{
super.onPause();
Log.d(tag, "In the onPause() event");
}
public void onStop()
{
super.onStop();
Log.d(tag, "In the onStop() event");
}
public void onDestroy()
{
super.onDestroy();
Log.d(tag, "In the onDestroy() event");
}
}
I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.
This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
//Add the path to the list of file paths
textFilePaths.push_back(path);
int lineNumber = 1;
while(!txtFile.eof())
{
txtFile.getline(line, 200);
Line * ln = new Line(line, path, lineNumber);
lineNumber++;
myList.push_back(ln);
vector<string> words = lineParser(ln);
for(unsigned int i = 0; i < words.size(); i++)
{
index->addWord(words[i], ln);
}
}
result = true;
}
Please see the GridFS docs for details on storing such binary data.
Support for your specific language should be linked to at the bottom of the screen.
Here I have an example of Bootstrap 3 popover showing an image with the tittle above it when the mouse hovers over some text. I've put in some inline styling that you may want to take out or change.....
This also works pretty well on mobile devices because the image will popup on the first tap and the link will open on the second. html:
<h5><a href="#" title="Solid Tiles Template" target="_blank" data-image-url="http://s29.postimg.org/t5pik8lyf/tiles1_preview.jpg" class="preview" rel="popover" style="color: green; font-style: normal; font-weight: bolder; font-size: 16px;">Template Preview 1 <i class="fa fa-external-link"></i></a></h5>
<h5><a href="#" title="Clear Tiles Template" target="_blank" data-image-url="http://s9.postimg.org/rdonet7jj/tiles2_2_preview.jpg" class="preview" rel="popover" style="color: red; font-style: normal; font-weight: bolder; font-size: 16px;">Template Preview 2 <i class="fa fa-external-link"></i></a></h5>
<h5><a href="#" title="Clear Tiles Template" target="_blank" data-image-url="http://s27.postimg.org/8scrcdu9v/tiles3_3_preview.jpg" class="preview" rel="popover" style="color: blue; font-style: normal; font-weight: bolder; font-size: 16px;">Template Preview 3 <i class="fa fa-external-link"></i></a></h5>
js:
$('.preview').popover({
'trigger':'hover',
'html':true,
'content':function(){
return "<img src='"+$(this).data('imageUrl')+"'>";
}
});
A slight improvement building on FishBoy's suggestion.
It is possible to do this kind of query in one hit, rather than in two separate stages. i.e. the single query below will page distinct results correctly, and also return entities instead of just IDs.
Simply use a DetachedCriteria with an id projection as a subquery, and then add paging values on the main Criteria object.
It will look something like this:
DetachedCriteria idsOnlyCriteria = DetachedCriteria.forClass(MyClass.class);
//add other joins and query params here
idsOnlyCriteria.setProjection(Projections.distinct(Projections.id()));
Criteria criteria = getSession().createCriteria(myClass);
criteria.add(Subqueries.propertyIn("id", idsOnlyCriteria));
criteria.setFirstResult(0).setMaxResults(50);
return criteria.list();
select CONCAT(UCASE(LEFT('CHRIS', 1)),SUBSTRING(lower('CHRIS'),2));
Above statement can be used for first letter CAPS and rest as lower case.
use a proxy property in your code it should work just fine
const https = require('https');
const request = require('request');
request({
'url':'https://teamtreehouse.com/chalkers.json',
'proxy':'http://xx.xxx.xxx.xx'
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = body;
console.log(data);
}
}
);
Doing the expicit casting to the "int" solves the problem in my case. I had the same issue. So:
int count = (int)[myColors count];
You could also use
df['bar'] = df['bar'].str.cat(df['foo'].values.astype(str), sep=' is ')
Create two partial indexes:
CREATE UNIQUE INDEX favo_3col_uni_idx ON favorites (user_id, menu_id, recipe_id)
WHERE menu_id IS NOT NULL;
CREATE UNIQUE INDEX favo_2col_uni_idx ON favorites (user_id, recipe_id)
WHERE menu_id IS NULL;
This way, there can only be one combination of (user_id, recipe_id)
where menu_id IS NULL
, effectively implementing the desired constraint.
Possible drawbacks: you cannot have a foreign key referencing (user_id, menu_id, recipe_id)
, you cannot base CLUSTER
on a partial index, and queries without a matching WHERE
condition cannot use the partial index. (It seems unlikely you'd want a FK reference three columns wide - use the PK column instead).
If you need a complete index, you can alternatively drop the WHERE
condition from favo_3col_uni_idx
and your requirements are still enforced.
The index, now comprising the whole table, overlaps with the other one and gets bigger. Depending on typical queries and the percentage of NULL
values, this may or may not be useful. In extreme situations it might even help to maintain all three indexes (the two partial ones and a total on top).
Aside: I advise not to use mixed case identifiers in PostgreSQL.
What worked for me was this lazy approach, not algorithmically lazy ;)
if( JSON.stringify(object_name).indexOf("key_name") > -1 ) {
console.log("Key Found");
}
else{
console.log("Key not Found");
}
if you're using eclipse you could also open Preferences > Maven and select Download Artifact Sources, this would let the pom.xml intact and keep your sources or java docs (if selected) just for development right at your machine location ~/.m2
I was using the Font Awesome library and was able to achieve this affect by tacking on the following to any html element.
<div class="fa fa-rotate-270">
My Test Text
</div>
Your mileage may vary.
git rm -r .
git checkout HEAD~3 .
git commit
After the commit, files in the new HEAD
will be the same as they were in the revision HEAD~3
.
It is also a good idea to instruct the client browser to clear session id cookie value.
Session.Clear();
Session.Abandon();
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-10);
You'll want a Map<String, String>
. Classes that implement the Map
interface include (but are not limited to):
Each is designed/optimized for certain situations (go to their respective docs for more info). HashMap
is probably the most common; the go-to default.
For example (using a HashMap
):
Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.println(map.get("dog"));
type of animal
If you want to even support for float values (Dot separated values) then you can use this expression :
var isNumber = /^\d+\.\d+$/.test(value);
Servers tab
--> doubleclick servername
--> Server Options: tick "Publish module contexts to separate XML files"
restart your server
I haven't tried implementing a FSM in C# yet, but these all sound (or look) very complicated to the way I handled FSM's in the past in low-level languages like C or ASM.
I believe the method I've always known is called something like an "Iterative Loop". In it, you essentially have a 'while' loop that periodically exits based on events (interrupts), then returns to the main loop again.
Within the interrupt handlers, you would pass a CurrentState and return a NextState, which then overwrites the CurrentState variable in the main loop. You do this ad infinitum until the program closes (or the microcontroller resets).
What I'm seeing other answers all look very complicated compared with how a FSM is, in my mind, intended to be implemented; its beauty lies in its simplicity and FSM can be very complicated with many, many states and transitions, but they allow complicated process to be easily broken down and digested.
I realize my response shouldn't include another question, but I am forced to ask: why do these other proposed solutions appear to be so complicated?
They seem to be akin to hitting a small nail with a giant sledge hammer.
It appears that iOS 9.0.2 breaks requests to valid HTTPS endpoints. My current suspicion is that it is requiring SHA-256 certs or it fails with this error.
To reproduce, inspect your UIWebView with safari, and try navigating to an arbitrary HTTPS endpoint:
location.href = "https://d37gvrvc0wt4s1.cloudfront.net/js/v1.4/rollbar.min.js"
// [Error] Failed to load resource: An SSL error has occurred and a secure connection to the server cannot be made. (rollbar.min.js, line 0)
Now try going to google (because of course they have a SHA-256 cert):
location.href = "https://google.com"
// no problemo
Adding an exception to transport security (as outlined by @stéphane-bruckert's answer above) works to fix this. I also assume that completely disabling NSAppTransportSecurity
would work too, though I've read that completely disabling it can jeopardize your app review.
[EDIT] I've found that simply enumerating the domains I'm connecting to in the NSExceptionDomains
dict fixes this problem, even when leaving NSExceptionAllowsInsecureHTTPLoads
set to true. :\
An iterator might be perfect for this type of work:
public static IEnumerable<int> LoadFileWithProgress(string filename, StringBuilder stringData)
{
const int charBufferSize = 4096;
using (FileStream fs = File.OpenRead(filename))
{
using (BinaryReader br = new BinaryReader(fs))
{
long length = fs.Length;
int numberOfChunks = Convert.ToInt32((length / charBufferSize)) + 1;
double iter = 100 / Convert.ToDouble(numberOfChunks);
double currentIter = 0;
yield return Convert.ToInt32(currentIter);
while (true)
{
char[] buffer = br.ReadChars(charBufferSize);
if (buffer.Length == 0) break;
stringData.Append(buffer);
currentIter += iter;
yield return Convert.ToInt32(currentIter);
}
}
}
}
You can call it using the following:
string filename = "C:\\myfile.txt";
StringBuilder sb = new StringBuilder();
foreach (int progress in LoadFileWithProgress(filename, sb))
{
// Update your progress counter here!
}
string fileData = sb.ToString();
As the file is loaded, the iterator will return the progress number from 0 to 100, which you can use to update your progress bar. Once the loop has finished, the StringBuilder will contain the contents of the text file.
Also, because you want text, we can just use BinaryReader to read in characters, which will ensure that your buffers line up correctly when reading any multi-byte characters (UTF-8, UTF-16, etc.).
This is all done without using background tasks, threads, or complex custom state machines.
As of Python 3.6 you can just do
>>> strng = 'hi'
>>> f'{strng: <10}'
with literal string interpolation.
Or, if your padding size is in a variable, like this (thanks @Matt M.!):
>>> to_pad = 10
>>> f'{strng: <{to_pad}}'
I know this is very old post. I thought to share my knowledge here !
For the date Mid night today with exact Time zone you can use following
public static Date getCurrentDateWithMidnightTS(){
return new Date(System.currentTimeMillis() - (System.currentTimeMillis()%(1000*60*60*24)) - (1000*60 * 330));
}
Where (1000*60 * 330)
is being subtracted i.e. actually related to time zone for example Indian time zone i.e. kolkata differs +5:30hrs from actual . So subtracting that with converting into milliseconds.
So change last substracted number according to you. I m creating a product i.e. only based in India So just used specific timestamp.
i had the same problem, i (removed "ng-model") changed this :
<select ng-model="mapayear" id="mapayear" name="mapayear" style=" display:inline-block !important; max-width: 20%;" class="form-control">
<option id="removable" hidden> Selecione u </option>
<option selected ng-repeat="x in anos" value="{{ x.ano }}">{{ x.ano }}
</option>
</select>
to this:
<select id="mapayear" name="mapayear" style=" display:inline-block !important; max-width: 20%;" class="form-control">
<option id="removable" hidden> Selecione u </option>
<option selected ng-repeat="x in anos" value="{{ x.ano }}">{{ x.ano }}
</option>
</select>
now its working, but in my case it was cause ive deleted that scope from ng.controller, check if u didn't do the same.
I'd like to add to OJ's kind clarifications.
Virtual inheritance doesn't come without a price. Like with all things virtual, you get a performance hit. There is a way around this performance hit that is possibly less elegant.
Instead of breaking the diamond by deriving virtually, you can add another layer to the diamond, to get something like this:
B
/ \
D11 D12
| |
D21 D22
\ /
DD
None of the classes inherit virtually, all inherit publicly. Classes D21 and D22 will then hide virtual function f() which is ambiguous for DD, perhaps by declaring the function private. They'd each define a wrapper function, f1() and f2() respectively, each calling class-local (private) f(), thus resolving conflicts. Class DD calls f1() if it wants D11::f() and f2() if it wants D12::f(). If you define the wrappers inline you'll probably get about zero overhead.
Of course, if you can change D11 and D12 then you can do the same trick inside these classes, but often that is not the case.
The best way according to me is to use the Moment.js isValid() method by specifying the format and use strict parsing.
As moment.js documentation says
As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimiters.
value = '2020-05-25';
format = 'YYYY-MM-DD';
moment(value, format, true).isValid() // true
Leading on from Andrew's answer with regards to c#2 and c#3 ... you can also do them inline for a one off search function (see below).
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int> { 1, 2, 3 };
List<int> newList = list.FindAll(delegate(int arg)
{
return arg> 2;
});
}
}
Hope this helps.
Use event delegation for dynamically created elements:
$(document).on("click", '.mylink', function(event) {
alert("new link clicked!");
});
This does actually work, here's an example where I appended an anchor with the class .mylink
instead of data
- http://jsfiddle.net/EFjzG/
First of all create a model POJO
import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "class_id")
public int classId;
@Column(name = "user_name")
public String userName;
//getter,setter
}
Controller
import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;
@RestController
public class HomeController {
@PersistenceUnit
private EntityManagerFactory emf;
@GetMapping("/")
public List<StdUser> actionIndex() {
EntityManager em = emf.createEntityManager(); // Without parameter
List<StdUser> arr_cust = (List<StdUser>)em
.createQuery("SELECT c FROM StdUser c")
.getResultList();
return arr_cust;
}
@GetMapping("/paramter")
public List actionJoin() {
int id = 3;
String userName = "Suresh Shrestha";
EntityManager em = emf.createEntityManager(); // With parameter
List arr_cust = em
.createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
.setParameter("Id",id)
.setParameter("UserName",userName)
.getResultList();
return arr_cust;
}
}
In case you want to pass in a block, say, for a glyphicon button, as in the following:
<%= link_to my_url, class: "stuff" do %>
<i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>
Then passing querystrings params could be accomplished through:
<%= link_to url_for(params.merge(my_params: "value")), class: "stuff" do %>
<i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>
A one-liner solution. Result in bytes.
$size=array_sum(array_map('filesize', glob("{$dir}/*.*")));
Added bonus: you can simply change the file mask to whatever you like, and count only certain files (eg by extension).
PHP supports one error control operator: the at sign (@)
. When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
If you have set a custom error handler function with set_error_handler()
then it will still get called, but this custom error handler can (and should) call error_reporting()
which will return 0
when the call that triggered the error was preceded by an @
.
<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '$php_errormsg'");
// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.
?>
Note:-
1) The @-operator works only on expressions.
2) A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.
Warning:-
Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.
Use name
attributes for form controls (such as <input>
and <select>
), as that's the identifier used in the POST
or GET
call that happens on form submission.
Use id
attributes whenever you need to address a particular HTML element with CSS, JavaScript or a fragment identifier. It's possible to look up elements by name, too, but it's simpler and more reliable to look them up by ID.
if ($("#btn").data('events') != undefined && $("#btn").data('events').click != undefined) {
//do nothing as the click event is already there
} else {
$("#btn").click(function (e) {
alert('test');
});
}
I had this problem when missing a closing tag in the html.
So instead of:
<table></table>
..my HTML was
<table>...<table>
Tried to load jQuery after angular as mentioned above. This prevented the error message, but didn't really fix the problem. And jQuery '.find' didn't really work afterwards..
Solution was to fix the missing closing tag.
Interesting question - I don't think there's any Oracle function that does this (almost like a "which" command in Unix), but you can get the resolution order for the name by:
select * from
(
select object_name objname, object_type, 'my object' details, 1 resolveOrder
from user_objects
where object_type not like 'SYNONYM'
union all
select synonym_name obj , 'my synonym', table_owner||'.'||table_name, 2 resolveOrder
from user_synonyms
union all
select synonym_name obj , 'public synonym', table_owner||'.'||table_name, 3 resolveOrder
from all_synonyms where owner = 'PUBLIC'
)
where objname like upper('&objOfInterest')
<style="text-decoration: none">
The above code will be enough.Just paste this into the link you want to remove underline from.
You have done it correctly. The pull request will automatically update. The process is:
The pull request will automatically add the new commits at the bottom of the pull request discussion (ie, it's already there, scroll down!)
Override the paintComponent method of your panel so you can custom draw. Like this:
@Override
public void paintComponent(Graphics g) {
Graphics2D gr = (Graphics2D) g; //this is if you want to use Graphics2D
//now do the drawing here
...
}
With Postgres 9.6 this can be done using the option if not exists
ALTER TABLE table_name ADD COLUMN IF NOT EXISTS column_name INTEGER;
Based on the answer for this question, I created a static class and added these. Thought it might be useful for some people.
public static class RegexConvert
{
public static string ToAlphaNumericOnly(this string input)
{
Regex rgx = new Regex("[^a-zA-Z0-9]");
return rgx.Replace(input, "");
}
public static string ToAlphaOnly(this string input)
{
Regex rgx = new Regex("[^a-zA-Z]");
return rgx.Replace(input, "");
}
public static string ToNumericOnly(this string input)
{
Regex rgx = new Regex("[^0-9]");
return rgx.Replace(input, "");
}
}
Then the methods can be used as:
string example = "asdf1234!@#$";
string alphanumeric = example.ToAlphaNumericOnly();
string alpha = example.ToAlphaOnly();
string numeric = example.ToNumericOnly();
Use the following to insure there is no whitespace in your output:
select first_name || ',' || last_name from table x;
Output
John,Smith
Jane,Doe
There is a really informative article in the actual Oracle Java magazine about using Docker in combination with Vagrant (and Puppet):
Conclusion
Docker’s lightweight containers are faster compared with classic VMs and have become popular among developers and as part of CD and DevOps initiatives. If your purpose is isolation, Docker is an excellent choice. Vagrant is a VM manager that enables you to script configurations of individual VMs as well as do the provisioning. However, it is sill a VM dependent on VirtualBox (or another VM manager) with relatively large overhead. It requires you to have a hard drive idle that can be huge, it takes a lot of RAM, and performance can be suboptimal. Docker uses kernel cgroups and namespace isolation via LXC. This means that you are using the same kernel as the host and the same ile system. Vagrant is a level above Docker in terms of abstraction, so they are not really comparable. Configuration management tools such as Puppet are widely used for provisioning target environments. Reusing existing Puppet-based solutions is easy with Docker. You can also slice your solution, so the infrastructure is provisioned with Puppet; the middleware, the business application itself, or both are provisioned with Docker; and Docker is wrapped by Vagrant. With this range of tools, you can do what’s best for your scenario.
How to build, use and orchestrate Docker containers in DevOps http://www.javamagazine.mozaicreader.com/JulyAug2015#&pageSet=34&page=0
The CONTINUE
statement is a new feature in 11g.
Here is a related question: 'CONTINUE' keyword in Oracle 10g PL/SQL
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
The keyboard seems to pop up when the EditText gains focus. To prevent this, set focusable to false:
<EditText
...
android:focusable="false"
... />
This behavior can vary on different manufacturers' Android OS flavors, but on the devices I've tested I have found this to to be sufficient. If the keyboard still pops up, using hints instead of text seems to help as well:
myEditText.setText("My text"); // instead of this...
myEditText.setHint("My text"); // try this
Once you've done this, your on click listener should work as desired:
myEditText.setOnClickListener(new OnClickListener() {...});
Thanks for all your help! @Svetoslav Tsolov had it very close, but I was still getting an error, until I figured out the closing parenthesis was in the wrong place. Here's the final query that works:
SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID,
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
(CASE WHEN dbo.EU_Admin3.EUID IS NULL THEN dbo.EU_Admin2.EUID ELSE dbo.EU_Admin3.EUID END) AS EUID
FROM dbo.AdminID
LEFT OUTER JOIN dbo.EU_Admin2
ON dbo.AdminID.DistrictID = dbo.EU_Admin2.DistrictID
LEFT OUTER JOIN dbo.EU_Admin3
ON dbo.AdminID.ADMIN3_ID = dbo.EU_Admin3.ADMIN3_ID
This answer shows the python perspective. Jupyter supports various languages besides python.
Both Jupyter Notebook and Jupyterlab are browser compatible interactive python (i.e. python ".ipynb" files) environments, where you can divide the various portions of the code into various individually executable cells for the sake of better readability. Both of these are popular in Data Science/Scientific Computing domain.
I'd suggest you to go with Jupyterlab for the advantages over Jupyter notebooks:
I'd recommend using PIP to install Jupyterlab.
If you can't open a ".ipynb" file using Jupyterlab on Windows system, here are the steps:
The following solution worked for me in Bootstrap 3.3.4:
CSS:
/*no collapse*/
.navbar-collapse.collapse.off {
display: block!important;
}
.navbar-collapse.collapse.off ul {
margin: 0;
padding: 0;
}
.navbar-nav.no-collapse>li,
.navbar-nav.no-collapse {
float: left !important;
}
.navbar-right.no-collapse {
float: right!important;
}
then add the .no-collapse class to each of the lists and the .off class to the main container. Here is an example written in jade:
nav.navbar.navbar-default.navbar-fixed-top
.container-fluid
.collapse.navbar-collapse.off
ul.nav.navbar-nav.no-collapse
li
a(href='#' class='glyph')
i(class='glyphicon glyphicon-info-sign')
ul.nav.navbar-nav.navbar-right.no-collapse
li.dropdown
a.dropdown-toggle(href='#', data-toggle='dropdown' role='button' aria-expanded='false')
| Tools
span.caret
ul.dropdown-menu(role='menu')
li
a(href='#') Tool #1
li
a(href='#')
| Logout
Implement onFocusChange
of setOnFocusChangeListener
and there's a boolean parameter for hasFocus. When this is false, you've lost focus to another control.
EditText txtEdit = (EditText) findViewById(R.id.edittxt);
txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
}
}
});
In short:
defaultdict(int)
- the argument int indicates that the values will be int type.
defaultdict(list)
- the argument list indicates that the values will be list type.
In addition to the existing answer it is possible to set a default option as follows:
echo off
ECHO A current build of Test Harness exists.
set delBuild=n
set /p delBuild=Delete preexisting build [y/n] (default - %delBuild%)?:
This allows users to simply hit "Enter" if they want to enter the default.
As of Hive 0.14, the CSV SerDe is a standard part of the Hive install
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
(See: https://cwiki.apache.org/confluence/display/Hive/CSV+Serde)
Here my implementation based on the above example/answer.
CRAWL CLASS:
class crawler
{
protected $_url;
protected $_depth;
protected $_host;
protected $_useHttpAuth = false;
protected $_user;
protected $_pass;
protected $_seen = array();
protected $_filter = array();
public function __construct($url, $depth = 5)
{
$this->_url = $url;
$this->_depth = $depth;
$parse = parse_url($url);
$this->_host = $parse['host'];
}
protected function _processAnchors($content, $url, $depth)
{
$dom = new DOMDocument('1.0');
@$dom->loadHTML($content);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $element) {
$href = $element->getAttribute('href');
if (0 !== strpos($href, 'http')) {
$path = '/' . ltrim($href, '/');
if (extension_loaded('http')) {
$href = http_build_url($url, array('path' => $path));
} else {
$parts = parse_url($url);
$href = $parts['scheme'] . '://';
if (isset($parts['user']) && isset($parts['pass'])) {
$href .= $parts['user'] . ':' . $parts['pass'] . '@';
}
$href .= $parts['host'];
if (isset($parts['port'])) {
$href .= ':' . $parts['port'];
}
$href .= $path;
}
}
// Crawl only link that belongs to the start domain
$this->crawl_page($href, $depth - 1);
}
}
protected function _getContent($url)
{
$handle = curl_init($url);
if ($this->_useHttpAuth) {
curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($handle, CURLOPT_USERPWD, $this->_user . ":" . $this->_pass);
}
// follows 302 redirect, creates problem wiht authentication
// curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
// return the content
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
// response total time
$time = curl_getinfo($handle, CURLINFO_TOTAL_TIME);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
return array($response, $httpCode, $time);
}
protected function _printResult($url, $depth, $httpcode, $time)
{
ob_end_flush();
$currentDepth = $this->_depth - $depth;
$count = count($this->_seen);
echo "N::$count,CODE::$httpcode,TIME::$time,DEPTH::$currentDepth URL::$url <br>";
ob_start();
flush();
}
protected function isValid($url, $depth)
{
if (strpos($url, $this->_host) === false
|| $depth === 0
|| isset($this->_seen[$url])
) {
return false;
}
foreach ($this->_filter as $excludePath) {
if (strpos($url, $excludePath) !== false) {
return false;
}
}
return true;
}
public function crawl_page($url, $depth)
{
if (!$this->isValid($url, $depth)) {
return;
}
// add to the seen URL
$this->_seen[$url] = true;
// get Content and Return Code
list($content, $httpcode, $time) = $this->_getContent($url);
// print Result for current Page
$this->_printResult($url, $depth, $httpcode, $time);
// process subPages
$this->_processAnchors($content, $url, $depth);
}
public function setHttpAuth($user, $pass)
{
$this->_useHttpAuth = true;
$this->_user = $user;
$this->_pass = $pass;
}
public function addFilterPath($path)
{
$this->_filter[] = $path;
}
public function run()
{
$this->crawl_page($this->_url, $this->_depth);
}
}
USAGE:
// USAGE
$startURL = 'http://YOUR_URL/';
$depth = 6;
$username = 'YOURUSER';
$password = 'YOURPASS';
$crawler = new crawler($startURL, $depth);
$crawler->setHttpAuth($username, $password);
// Exclude path with the following structure to be processed
$crawler->addFilterPath('customer/account/login/referer');
$crawler->run();
You can use php function
apache_get_modules
and check for mod_rewrite
<pre>
<?php
print_r(apache_get_modules());
?>
</pre>
Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.
movdir = r"C:\Scans"
basedir = r"C:\Links"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
for filename in files:
# I use absolute path, case you want to move several dirs.
old_name = os.path.join( os.path.abspath(root), filename )
# Separate base from extension
base, extension = os.path.splitext(filename)
# Initial new name
new_name = os.path.join(basedir, base, filename)
# If folder basedir/base does not exist... You don't want to create it?
if not os.path.exists(os.path.join(basedir, base)):
print os.path.join(basedir,base), "not found"
continue # Next filename
elif not os.path.exists(new_name): # folder exists, file does not
shutil.copy(old_name, new_name)
else: # folder exists, file exists as well
ii = 1
while True:
new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
if not os.path.exists(new_name):
shutil.copy(old_name, new_name)
print "Copied", old_name, "as", new_name
break
ii += 1
DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
WHERE something IS NULL
and
WHERE something IS NOT NULL
I believe the REAL answer to this question is an explanation as to how you configure what editor to use by default, if you are not comfortable with Vim.
This is how to configure Notepad for example, useful in Windows:
git config --global core.editor "notepad"
Gedit, more Linux friendly:
git config --global core.editor "gedit"
You can read the current configuration like this:
git config core.editor
Some VS .NET project types don’t auto-generate a .NET (.resx) file. The following steps add a Resource file to your project:
Resources
.Now you can add a text file as a resource, for example an xml file:
Resources
has a property of type string
that is named after the included file. If the file name is e.g. RibbonManifest.xml, then the property should have the name RibbonManifest
. You find the exact name in the code file Resources.Designer.cs.string xml = Resources.RibbonManifest
. The general form is ResourceFileName.IncludedTextFileName
. Don’t use ResourceManager.GetString
since the get-function of the string property has done that already.I had the same problem of @rutherford, today the new phpMyAdmin's 3.4.11.1 GUI is different, so I figure out it's better if someone improves the answers with updated info.
Full mysql logs can be found in:
"Status"->"Binary Log"
This is the answer, doesn't matter if you're using MAMP, XAMPP, LAMP, etc.
It works far better this way (preserving responsiveness):
<!-- somewhere deep start -->
<div class="row">
<div class="center-block col-md-4" style="float: none; background-color: grey">
Hi there!
</div>
</div>
<!-- somewhere deep end -->
Action
is a Type of Delegate provided by the .NET framework. The Action
points to a method with no parameters and does not return a value.
() =>
is lambda expression syntax. Lambda expressions are not of Type Delegate
. Invoke requires Delegate
so Action
can be used to wrap the lambda expression and provide the expected Type
to Invoke()
Invoke
causes said Action
to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions
. For example, if one tries to set the Rtf
property on a RichTextBox
when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid
exception will be thrown. Check Control.InvokeRequired
before calling Invoke.
BeginInvoke
is the Asynchronous version of Invoke
. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.
%~d0
gives you the drive letter of argument 0 (the script name), %~p0
the path.
This is Christopher Lincolns idea but with correct code:
function replace(str,find,replace){
if (find != ""){
str = str.toString();
var aStr = str.split(find);
for(var i = 0; i < aStr.length; i++) {
if (i > 0){
str = str + replace + aStr[i];
}else{
str = aStr[i];
}
}
}
return str;
}
Example Usage:
var somevariable = replace('//\\\/\/sdfas/\/\/\\\////','\/sdf','replacethis\');
Javascript global string replacement is unecessarily complicated. This function solves that problem. There is probably a small performance impact, but I'm sure its negligable.
Heres an alternative function, looks much cleaner, but is on average about 25 to 20 percent slower than the above function:
function replace(str,find,replace){
if (find !== ""){
str = str.toString().split(find).join(replace);
}
return str;
}
Maybe hard-coded database names isn't the best approach always within an SQL-query. Thus, adding synonyms would be a better approach. It's not always the case that databases have the same name across several staging environments. They might consist by postfixes like PROD, UAT, SIT, QA and so forth. So be aware of hard-coded queries and make them more dynamic.
Approach #1: Use synonyms to link tables between databases on the same server.
Approach #2: Collect data separately from each database and join it in your code. Your database connection strings could be part of your App-server configuration through either a database or a config file.
I had a similar problem in a MS-Access query, and I solved it by changing my equivalent fName
to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any Group By
clause at the end.
Google Chrome released the storage API: http://developer.chrome.com/extensions/storage.html
It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
console.log('Settings saved');
});
// Read it using the storage API
chrome.storage.sync.get(['foo', 'bar'], function(items) {
message('Settings retrieved', items);
});
To use it, make sure you define it in the manifest:
"permissions": [
"storage"
],
There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"
Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.
Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.
The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:
contentscript.js
chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
console.log(response.status);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getStatus")
sendResponse({status: localStorage['status']});
else
sendResponse({}); // snub them.
});
You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.
I hope that helped solve your problem.
To be fancy and generic ...
contentscript.js
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
console.log(response.data);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
As a rule, if your "underline" is not the same color as your text [and the 'color:' is not overridden inline] it is not coming from "text-decoration:" It has to be "border-bottom:"
Don't forget to take the border off your pseudo classes too!
a, a:link, a:visited, a:active, a:hover {border:0!important;}
This snippet assumes its on an anchor, change to it's wrapper accordingly... and use specificity instead of "!important" after you track down the root cause.
Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li>
elements with class="dropdown-menu"
. It automatically displays the proper caret indicator as well.
<head>
...
<script src=".../jquery.smartmenus.min.js"></script>
<script src=".../jquery.smartmenus.bootstrap.min.js"></script>
...
<link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
...
</head>
Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html
This is a very useful question. It has 5 different helpful answers that say quite different but complementary things (surprising, eh?). This answer combines those answers into a more useful form as well as adding two more solutions.
There is no Oracle Express Edition for 64 bit Windows. See this official [but unanswered] forum thread. Therefore, these are the classes of solutions:
On Android 4.4 KitKat, I found mine in:
/sdcard/Android/data/<app.package.name>
The documentation reiterates your findings here: https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service
If my memory serves, $stateParams
was introduced later than the original $state.params
, and seems to be a simple helper injector to avoid continuously writing $state.params
.
I doubt there are any best practice guidelines, but context wins out for me. If you simply want access to the params received into the url, then use $stateParams
. If you want to know something more complex about the state itself, use $state
.
An exe is an executible program whereas A DLL is a file that can be loaded and executed by programs dynamically.
add this line end of php.ini
openssl.cafile=/opt/lampp/share/curl/curl-ca-bundle.crt
may be curl path cannot be identified by PHP
Use the reflection methods on Apache Commons EqualsBuilder and HashCodeBuilder.
Try the binascii module
from binascii import unhexlify
b = unhexlify(myhexstr)
You can also try this
<tr>
<th>Name :</th>
<td><input type="text" name="name" id="name" placeholder="Enter Your Name"><div id="name_error"></div></td>
</tr>
function register_validate()
{
var name = document.getElementById('name').value;
submit = true;
if(name == '')
{
document.getElementById('name_error').innerHTML = "Name Is Required";
return false;
}
return submit;
}
document.getElementById('name').onkeyup = removewarning;
function removewarning()
{
document.getElementById(this.id +'_error').innerHTML = "";
}
Just copy paste the code below!
-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Clona" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
//insert your editAction here
}];
editAction.backgroundColor = [UIColor blueColor];
UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
//insert your deleteAction here
}];
deleteAction.backgroundColor = [UIColor redColor];
return @[deleteAction,editAction];
}
and awk as well
awk 'NR!~/^(5|10|25)$/' file
Instead of the *
selector you can use the :not(selector)
with the >
selector and set something that definitely wont be a child.
Edit: I thought it would be faster but it turns out I was wrong. Disregard.
Example:
.container > :not(marquee){
color:red;
}
<div class="container">
<p></p>
<span></span>
<div>
you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">
$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');
The common wisdom that floating-point numbers cannot be compared for equality is inaccurate. Floating-point numbers are no different from integers: If you evaluate "a == b", you will get true if they are identical numbers and false otherwise (with the understanding that two NaNs are of course not identical numbers).
The actual problem is this: If I have done some calculations and am not sure the two numbers I have to compare are exactly correct, then what? This problem is the same for floating-point as it is for integers. If you evaluate the integer expression "7/3*3", it will not compare equal to "7*3/3".
So suppose we asked "How do I compare integers for equality?" in such a situation. There is no single answer; what you should do depends on the specific situation, notably what sort of errors you have and what you want to achieve.
Here are some possible choices.
If you want to get a "true" result if the mathematically exact numbers would be equal, then you might try to use the properties of the calculations you perform to prove that you get the same errors in the two numbers. If that is feasible, and you compare two numbers that result from expressions that would give equal numbers if computed exactly, then you will get "true" from the comparison. Another approach is that you might analyze the properties of the calculations and prove that the error never exceeds a certain amount, perhaps an absolute amount or an amount relative to one of the inputs or one of the outputs. In that case, you can ask whether the two calculated numbers differ by at most that amount, and return "true" if they are within the interval. If you cannot prove an error bound, you might guess and hope for the best. One way of guessing is to evaluate many random samples and see what sort of distribution you get in the results.
Of course, since we only set the requirement that you get "true" if the mathematically exact results are equal, we left open the possibility that you get "true" even if they are unequal. (In fact, we can satisfy the requirement by always returning "true". This makes the calculation simple but is generally undesirable, so I will discuss improving the situation below.)
If you want to get a "false" result if the mathematically exact numbers would be unequal, you need to prove that your evaluation of the numbers yields different numbers if the mathematically exact numbers would be unequal. This may be impossible for practical purposes in many common situations. So let us consider an alternative.
A useful requirement might be that we get a "false" result if the mathematically exact numbers differ by more than a certain amount. For example, perhaps we are going to calculate where a ball thrown in a computer game traveled, and we want to know whether it struck a bat. In this case, we certainly want to get "true" if the ball strikes the bat, and we want to get "false" if the ball is far from the bat, and we can accept an incorrect "true" answer if the ball in a mathematically exact simulation missed the bat but is within a millimeter of hitting the bat. In that case, we need to prove (or guess/estimate) that our calculation of the ball's position and the bat's position have a combined error of at most one millimeter (for all positions of interest). This would allow us to always return "false" if the ball and bat are more than a millimeter apart, to return "true" if they touch, and to return "true" if they are close enough to be acceptable.
So, how you decide what to return when comparing floating-point numbers depends very much on your specific situation.
As to how you go about proving error bounds for calculations, that can be a complicated subject. Any floating-point implementation using the IEEE 754 standard in round-to-nearest mode returns the floating-point number nearest to the exact result for any basic operation (notably multiplication, division, addition, subtraction, square root). (In case of tie, round so the low bit is even.) (Be particularly careful about square root and division; your language implementation might use methods that do not conform to IEEE 754 for those.) Because of this requirement, we know the error in a single result is at most 1/2 of the value of the least significant bit. (If it were more, the rounding would have gone to a different number that is within 1/2 the value.)
Going on from there gets substantially more complicated; the next step is performing an operation where one of the inputs already has some error. For simple expressions, these errors can be followed through the calculations to reach a bound on the final error. In practice, this is only done in a few situations, such as working on a high-quality mathematics library. And, of course, you need precise control over exactly which operations are performed. High-level languages often give the compiler a lot of slack, so you might not know in which order operations are performed.
There is much more that could be (and is) written about this topic, but I have to stop there. In summary, the answer is: There is no library routine for this comparison because there is no single solution that fits most needs that is worth putting into a library routine. (If comparing with a relative or absolute error interval suffices for you, you can do it simply without a library routine.)
No you wouldn't alter the "content" of the list, if you could mutate strings that way. But in Python they are not mutable. Any string operation returns a new string.
If you had a list of objects you knew were mutable, you could do this as long as you don't change the actual contents of the list.
Thus you will need to do a map of some sort. If you use a generator expression it [the operation] will be done as you iterate and you will save memory.
(You already mentioned all but the last one).
Those are the only differences to regular classes.
A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:
public interface Predicate<ARGTYPE>
{
public boolean evaluate(ARGTYPE arg);
}
And then you might have an implementation such as:
public class Tautology<E> implements Predicate<E>
{
public boolean evaluate(E arg){
return true;
}
}
To get a better conceptual understanding, you might want to read about first-order logic.
Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.
Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true
to a function instead of defining a named Tautology subclass like the above.
Since nobody so far felt fit to point out why what you're trying doesn't work:
NA == NA
doesn't return TRUE
, it returns NA
(since comparing to undefined values should yield an undefined result). apply
on an atomic vector. You can't use apply
to loop over the elements in a column. a$x
, which is just the column (an atomic vector).I'd fix up 3. to get to a$x[is.na(a$x)] <- 0
Regarding error: log4j:ERROR Element type "rollingPolicy" must be declared
log4j.dtd
defining rollingPolicy
.apache-log4j-extras-1.1.jar
The syntax you are using is new to SQL Server 2008:
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
VALUES
(1000,N'test'),(1001,N'test2')
For SQL Server 2005, you will have to use multiple INSERT
statements:
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
VALUES
(1000,N'test')
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
VALUES
(1001,N'test2')
One other option is to use UNION ALL
:
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'
for executing that you must provide full path of that for example
/home/Manuel/mywrittenscript
Further to @Kyle Kelley and @DGrady, here is the entry which can be found in the
$HOME/.ipython/profile_default/ipython_kernel_config.py
(or whichever profile you have created)
Change
# Configure matplotlib for interactive use with the default matplotlib backend.
# c.IPKernelApp.matplotlib = none
to
# Configure matplotlib for interactive use with the default matplotlib backend.
c.IPKernelApp.matplotlib = 'inline'
This will then work in both ipython qtconsole and notebook sessions.
The interrupt process is hardware and OS dependent. So you will have very different behavior depending on where you run your python script. For example, on Windows machines we have Ctrl+C (SIGINT
) and Ctrl+Break (SIGBREAK
).
So while SIGINT is present on all systems and can be handled and caught, the SIGBREAK signal is Windows specific (and can be disabled in CONFIG.SYS) and is really handled by the BIOS as an interrupt vector INT 1Bh, which is why this key is much more powerful than any other. So if you're using some *nix flavored OS, you will get different results depending on the implementation, since that signal is not present there, but others are. In Linux you can check what signals are available to you by:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGEMT 8) SIGFPE 9) SIGKILL 10) SIGBUS
11) SIGSEGV 12) SIGSYS 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGURG 17) SIGSTOP 18) SIGTSTP 19) SIGCONT 20) SIGCHLD
21) SIGTTIN 22) SIGTTOU 23) SIGIO 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGPWR 30) SIGUSR1
31) SIGUSR2 32) SIGRTMAX
So if you want to catch the CTRL+BREAK
signal on a linux system you'll have to check to what POSIX signal they have mapped that key. Popular mappings are:
CTRL+\ = SIGQUIT
CTRL+D = SIGQUIT
CTRL+C = SIGINT
CTRL+Z = SIGTSTOP
CTRL+BREAK = SIGKILL or SIGTERM or SIGSTOP
In fact, many more functions are available under Linux, where the SysRq (System Request) key can take on a life of its own...
There is one method by which int
can be converted to char
and even without using ASCII values.
Example:
int i = 2;
char ch = Integer.toString(i).charAt(0);
System.out.println(ch);
Explanation :
First the integer is converted to string and then by using String function charAt()
, character is extracted from the string. As the integer only has one single digit, the index 0
is given to charAt()
function.
A common issue often overlooked is also that there must be NO other code or extra spacing before the session_start() command.
I've had this issue before where I had a blank line before session_start() which caused it not to work properly.
It means that one of the dependent dlls is compiled with a different run-time library.
Project -> Properties -> C/C++ -> Code Generation -> Runtime Library
Go over all the libraries and see that they are compiled in the same way.
More about this error in this link:
warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs
So the query I was assigned to optimize was written with two CTEs in SQL server. It was taking 28sec.
I spent two minutes converting them to temp tables and the query took 3 seconds
I added an index to the temp table on the field it was being joined on and got it down to 2 seconds
Three minutes of work and now its running 12x faster all by removing CTE. I personally will not use CTEs ever they are tougher to debug as well.
The crazy thing is the CTEs were both only used once and still putting an index on them proved to be 50% faster.
In python 3.7 and above there is a new and easy way. here is the syntax:
name = "Eric"
age = 74
f"Hello, {name}. You are {age}."
OutPut:
Hello, Eric. You are 74.
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
Swift 4
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.barTintColor = UIColor.orange
navigationController?.navigationBar.tintColor = UIColor.white
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
}
jQuery simple solution.
Should be triggered by user's click.
$("<textarea/>").appendTo("body").val(text).select().each(function () {
document.execCommand('copy');
}).remove();
There is also tty0tty http://sourceforge.net/projects/tty0tty/ which is a real null modem emulator for linux.
It is a simple kernel module - a small source file. I don't know why it only got thumbs down on sourceforge, but it works well for me. The best thing about it is that is also emulates the hardware pins (RTC/CTS DSR/DTR). It even implements TIOCMGET/TIOCMSET and TIOCMIWAIT iotcl commands!
On a recent kernel you may get compilation errors. This is easy to fix. Just insert a few lines at the top of the module/tty0tty.c source (after the includes):
#ifndef init_MUTEX
#define init_MUTEX(x) sema_init((x),1)
#endif
When the module is loaded, it creates 4 pairs of serial ports. The devices are /dev/tnt0 to /dev/tnt7 where tnt0 is connected to tnt1, tnt2 is connected to tnt3, etc. You may need to fix the file permissions to be able to use the devices.
edit:
I guess I was a little quick with my enthusiasm. While the driver looks promising, it seems unstable. I don't know for sure but I think it crashed a machine in the office I was working on from home. I can't check until I'm back in the office on monday.
The second thing is that TIOCMIWAIT does not work. The code seems to be copied from some "tiny tty" example code. The handling of TIOCMIWAIT seems in place, but it never wakes up because the corresponding call to wake_up_interruptible() is missing.
edit:
The crash in the office really was the driver's fault. There was an initialization missing, and the completely untested TIOCMIWAIT code caused a crash of the machine.
I spent yesterday and today rewriting the driver. There were a lot of issues, but now it works well for me. There's still code missing for hardware flow control managed by the driver, but I don't need it because I'll be managing the pins myself using TIOCMGET/TIOCMSET/TIOCMIWAIT from user mode code.
If anyone is interested in my version of the code, send me a message and I'll send it to you.
Complement of information for those people who use .on() to listen to events bound on inputs inside lately loaded table cells; I managed to bind event handlers to such table cells by using delegate(), but .on() wouldn't work.
I bound the table id to .delegate() and used a selector that describes the inputs.
e.g.
HTML
<table id="#mytable">
<!-- These three lines below were loaded post-DOM creation time, using a live callback for example -->
<tr><td><input name="qty_001" /></td></tr>
<tr><td><input name="qty_002" /></td></tr>
<tr><td><input name="qty_003" /></td></tr>
</table>
jQuery
$('#mytable').delegate('click', 'name^=["qty_"]', function() {
console.log("you clicked cell #" . $(this).attr("name"));
});
Here is my updated code. It works fine and it can help you.
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
function go(loc) {
document.getElementById('calendar').src = loc;
}
</script>
</head>
<body>
<iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>
<form method="post">
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month
</form>
</body>
</html>
System.exit();
causes the Java VM to terminate completely.
JFrame.dispose();
causes the JFrame
window to be destroyed and cleaned up by the operating system. According to the documentation, this can cause the Java VM to terminate if there are no other Windows available, but this should really just be seen as a side effect rather than the norm.
The one you choose really depends on your situation. If you want to terminate everything in the current Java VM, you should use System.exit()
and everything will be cleaned up. If you only want to destroy the current window, with the side effect that it will close the Java VM if this is the only window, then use JFrame.dispose()
.
In the new Windows Terminal, you can click Settings and edit the line "startingDirectory" to achieve something similar.
Please note, however, that this changes the default startup directory only in Windows Terminal, and not for the command prompt globally.
If you really must output every values including the NULL ones:
select IFNULL(prereq,"") from test
I dealt with this before & had posted in the spring forums.
The advice we received was to use a type of SQlQuery. Here's an example of what we did when trying to get a value out of a DB that might not be there.
@Component
public class FindID extends MappingSqlQuery<Long> {
@Autowired
public void setDataSource(DataSource dataSource) {
String sql = "Select id from address where id = ?";
super.setDataSource(dataSource);
super.declareParameter(new SqlParameter(Types.VARCHAR));
super.setSql(sql);
compile();
}
@Override
protected Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong(1);
}
In the DAO then we just call...
Long id = findID.findObject(id);
Not clear on performance, but it works and is neat.
If you're planning on writing more than just one line of rules in .htacesss,
don't even think about trying one of those hot-fix methods to debug it.
I have wasted days setting multiple rules, without feedback from LOGs, only to finally give up.
I got Apache on my PC, copied the whole site to its HDD, and got the whole rule-set sorted out, using the logs, real fast.
Then I reviewed my old rules, which been working. I saw they were not really doing what was desired. A time bomb, given a slightly different address.
There are so many pit falls in rewrite rules, it's not a straight logic thing at all.
You can get Apache up and running in ten minutes, it's 10MB, good license, *NIX/WIN/MAC ready, even without install.
Also, check the header lines of your server and get the same version of Apache from their archive if it's old. My OP is still on 2.0; many things are not supported.
Delete old Db when uninstall the app.
Setting android:allowBackup="false" in the application tag in AndroidManifest.xml fixed the problem. It seems that for some weird reason the Android OS was restoring from a backup every time I deployed the app.
That other post is Java. You can't put methods in Enums in C#.
just do something like this:
PublishStatusses status = ...
String s = status.ToString();
If you want to use different display values for your enum values, you could use Attributes and Reflection.
cp -R t1/ t2
The trailing slash on the source directory changes the semantics slightly, so it copies the contents but not the directory itself. It also avoids the problems with globbing and invisible files that Bertrand's answer has (copying t1/*
misses invisible files, copying `t1/* t1/.*' copies t1/. and t1/.., which you don't want).
java.util.UUID.randomUUID();
Here's how you can do it in C#:
class Program
{
static void Main(string[] args)
{
if (File.Exists("test.db3"))
{
File.Delete("test.db3");
}
using (var connection = new SQLiteConnection("Data Source=test.db3;Version=3"))
using (var command = new SQLiteCommand("CREATE TABLE PHOTOS(ID INTEGER PRIMARY KEY AUTOINCREMENT, PHOTO BLOB)", connection))
{
connection.Open();
command.ExecuteNonQuery();
byte[] photo = new byte[] { 1, 2, 3, 4, 5 };
command.CommandText = "INSERT INTO PHOTOS (PHOTO) VALUES (@photo)";
command.Parameters.Add("@photo", DbType.Binary, 20).Value = photo;
command.ExecuteNonQuery();
command.CommandText = "SELECT PHOTO FROM PHOTOS WHERE ID = 1";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
byte[] buffer = GetBytes(reader);
}
}
}
}
static byte[] GetBytes(SQLiteDataReader reader)
{
const int CHUNK_SIZE = 2 * 1024;
byte[] buffer = new byte[CHUNK_SIZE];
long bytesRead;
long fieldOffset = 0;
using (MemoryStream stream = new MemoryStream())
{
while ((bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, (int)bytesRead);
fieldOffset += bytesRead;
}
return stream.ToArray();
}
}
}
Mention the url
like:
jdbc:mysql://hostname:3306/hibernatedb?autoReconnect=true&useSSL=false
But in xml configuration when you mention &
sign, the IDE shows below error:
The reference to entity "useSSL" must end with the ';' delimiter.
And then you have to explicitly use the &
instead of &
to be determined as &
by xml
thereafter in xml
you have to give the url in xml configuration like this:
<property name="connection.url">jdbc:mysql://hostname:3306/hibernatedb?autoReconnect=true&useSSL=false</property>
This works in Python 2.x.
For Python 3 look in the docs:
import urllib.request
with urllib.request.urlopen("http://www.python.org") as url:
s = url.read()
# I'm guessing this would output the html source code ?
print(s)
Could you provide a whole makefile? But right now I can tell - you should check that "install" target already exists. So, check Makefile whether it contains a
install: (anything there)
line. If not, there is no such target and so make has right. Probably you should use just "make" command to compile and then use it as is or install yourself, manually.
Install is not any standard of make, it is just a common target, that could exists, but not necessary.
fedorqui has a working solution but there is another way to do the same thing.
Chock if a variable is set
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName
from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)
class Foo:
def __init__(self):
self.__privateField = 4;
print self.__privateField # yields 4 no problem
foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'
It will be accessible through _Foo__privateField
instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.
The answer may be outdated, since there is a name
property on the UploadedFile
class. See: Uploaded Files and Upload Handlers (Django docs). So, if you bind your form with a FileField
correctly, the access should be as easy as:
if form.is_valid():
form.cleaned_data['my_file'].name
I had a similar issue, but in my case it was because storage has only SFTP, without ssh or rsync daemons on it. I could not change anything, bcs this server was provided by my customer.
rsync could not change the date and time for the file, some other utilites (like csync) showed me other errors: "Unable to create temporary file Clock skew detected". If you have access to the storage-server - just install openssh-server or launch rsync as a daemon here.
In my case - I could not do this and solution was: lftp. lftp's usage for syncronization is below:
lftp -c "open -u login,password sftp://sft.domain.tld/; mirror -c --verbose=9 -e -R -L /srs/folder /rem/folder"
/src/folder - is the folder on my PC, /rem/folder - is sftp://sft.domain.tld/rem/folder.
you may find mans by the link lftp.yar.ru/lftp-man.html
Unfortunately MSTest STILL only really has the ExpectedException attribute (just shows how much MS cares about MSTest) which IMO is pretty awful because it breaks the Arrange/Act/Assert pattern and it doesnt allow you to specify exactly which line of code you expect the exception to occur on.
When I'm using (/forced by a client) to use MSTest I always use this helper class:
public static class AssertException
{
public static void Throws<TException>(Action action) where TException : Exception
{
try
{
action();
}
catch (Exception ex)
{
Assert.IsTrue(ex.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + ex.GetType() + " was thrown instead.");
return;
}
Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown.");
}
public static void Throws<TException>(Action action, string expectedMessage) where TException : Exception
{
try
{
action();
}
catch (Exception ex)
{
Assert.IsTrue(ex.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + ex.GetType() + " was thrown instead.");
Assert.AreEqual(expectedMessage, ex.Message, "Expected exception with a message of '" + expectedMessage + "' but exception with message of '" + ex.Message + "' was thrown instead.");
return;
}
Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown.");
}
}
Example of usage:
AssertException.Throws<ArgumentNullException>(() => classUnderTest.GetCustomer(null));
Change your Main.c
like so
#include <stdlib.h>
#include <stdio.h>
#include "ClasseAusiliaria.h"
int main(void)
{
int risultato;
risultato = addizione(5,6);
printf("%d\n",risultato);
}
Create ClasseAusiliaria.h
like so
extern int addizione(int a, int b);
I then compiled and ran your code, I got an output of
11
A bit more along the same lines
attrs <- {}
attrs.a <- 1
f <- function(d) {
attrs.a <- d
}
f(20)
print(attrs.a)
will print "1"
attrs <- {}
attrs.a <- 1
f <- function(d) {
attrs.a <<- d
}
f(20)
print(attrs.a)
Will print "20"
New-style classes have an mro
method you can call which returns a list of parent classes in method resolution order.
PHP-ZIP
needs some dependancies or library missing, depends on the image from Dockerfile
you need to install them first
RUN set -eux \
&& apt-get update \
&& apt-get install -y libzip-dev zlib1g-dev \
&& docker-php-ext-install zip
In short, REST emphasizes nouns over verbs. As your API becomes more complex, you add more things, rather than more commands.
There is a simple way of doing this without writing a helper function... It can be done within the template completely.
{{#if cond1}}
{{#if con2}}
<div> and condition completed</div>
{{/if}}
{{else}}
<div> both conditions weren't true</div>
{{/if}}
Edit: Conversely you can do or's by doing this:
{{#if cond1}}
<div> or condition completed</div>
{{else}}
{{#if cond2}}
<div> or condition completed</div>
{{else}}
<div> neither of the conditions were true</div>
{{/if}}
{{/if}}
Edit/Note: From the handlebar's website: handlebarsjs.com here are the falsy values:
You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "" or [] (a "falsy" value), Then any 'cond' (like cond1 or cond2) will not be counted as true.
I used to have the same problem finding a good library to do that. Eventually, I created a library which can do that: SwipeRevealLayout
In gradle file:
dependencies {
compile 'com.chauthai.swipereveallayout:swipe-reveal-layout:1.4.0'
}
In your xml file:
<com.chauthai.swipereveallayout.SwipeRevealLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:mode="same_level"
app:dragEdge="left">
<!-- Your secondary layout here -->
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<!-- Your main layout here -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.chauthai.swipereveallayout.SwipeRevealLayout>
Then in your adapter file:
public class Adapter extends RecyclerView.Adapter {
// This object helps you save/restore the open/close state of each view
private final ViewBinderHelper viewBinderHelper = new ViewBinderHelper();
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// get your data object first.
YourDataObject dataObject = mDataSet.get(position);
// Save/restore the open/close state.
// You need to provide a String id which uniquely defines the data object.
viewBinderHelper.bind(holder.swipeRevealLayout, dataObject.getId());
// do your regular binding stuff here
}
}
you could check the files
/proc/[pid]/task/[thread ids]/status
It's really not an 'either/or' situation. AJAX stands for Asynchronous JavaScript and XML, and JQuery is a JavaScript library that takes the pain out of writing common JavaScript routines.
It's the difference between a thing (jQuery) and a process (AJAX). To compare them would be to compare apples and oranges.
Just install the updated versions of all of them.
apt-get install -y gnupg2 gnupg gnupg1
you can use:
define("PATH_ROOT", dirname(__FILE__));
include_once PATH_ROOT . "/PoliticalForum/headerSite.php";
I literally did this 1 hour ago.
Download the appropriate files for your OS. The Android SDK needs java in order to install. Once you get the Android SDK installed go get eclipse and install that. Basically download the file and unzip then in a directory. The android install is the same but it will install a lot more files. (5) Finally open eclipse and go to help > install new software >> and add the url to the plugin - I used this one https://dl-ssl.google.com/android/eclipse/
There won't be much difference. Howver version 2 is easier when you have some calculations, aggregations, etc that should be joined outside of it
--Version 2
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN
(SELECT ProductID, SUM(OrderQty) as OrderQty FROM SalesOrderDetail GROUP BY ProductID
HAVING SUM(OrderQty) >1000) s
on p.ProductID = s.ProdctId
If you are using C#3 a good tip is to create an extension method to make this even simpler. Just create a static method (preferably in a static class) like so:
public static class Extensions
{
public static string HtmlEncode(this string s)
{
return HttpUtility.HtmlEncode(s);
}
}
You can then do neat stuff like this:
string encoded = "<div>I need encoding</div>".HtmlEncode();
If you want to use special character in javascript variable value, Escape Character (\
) is required.
Backslash in your example is special character, too.
So you should do something like this,
var ttt = "aa ///\\\\\\"; // --> ///\\\
or
var ttt = "aa ///\\"; // --> ///\
But Escape Character not require for user input.
When you press /
in prompt box or input field then submit, that means single /
.
u must specify the width and height also
<section class="bg-solid-light slideContainer strut-slide-0" style="background-image: url(https://accounts.icharts.net/stage/icharts-images/chartbook-images/Chart1457601371484.png); background-repeat: no-repeat;width: 100%;height: 100%;" >
my solution is similar to the solution given by Server Themes. Do check it once:
localStorage.setItem("validNavigation", false);
$(document).on('keypress', function (e) {
if (e.keyCode == 116) {
localStorage.setItem("validNavigation", true);
}
});
// Attach the event click for all links in the page
$(document).on("click", "a", function () {
localStorage.setItem("validNavigation", true);
});
// Attach the event submit for all forms in the page
$(document).on("submit", "form", function () {
localStorage.setItem("validNavigation", true);
});
// Attach the event click for all inputs in the page
$(document).bind("click", "input[type=submit]", function () {
localStorage.setItem("validNavigation", true);
});
$(document).bind("click", "button[type=submit]", function () {
localStorage.setItem("validNavigation", true);
});
window.onbeforeunload = function (event) {
if (localStorage.getItem("validNavigation") === "false") {
event.returnValue = "Write something clever here..";
console.log("Test success!");
localStorage.setItem("validNavigation", false);
}
};
If you put the breakpoints correctly on the browser page, the if condition will be true only when the browser is about to be closed or the tab is about to be closed.
Check this link for reference: https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/
You could use viewport-percentage lenghts.
See: http://stanhub.com/how-to-make-div-element-100-height-of-browser-window-using-css-only/
It works like this:
.element{
height: 100vh; /* For 100% screen height */
width: 100vw; /* For 100% screen width */
}
More info also available through Mozilla Developer Network and W3C.
Yes, we can check this.
print_lyrics()
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all day.")
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
As BJ Homer mentioned over above comments, A general rule in Python is not that function should be defined higher in the code (as in Pascal), but that it should be defined before its usage.
Hope that helps.
Spring beans are classes. Instead of instantiating a class (using new
), you get an instance as a bean
cast to your class type from the application context, where the bean is what you configured in the application context configuration. This way, the whole application maintains singleton-scope instance throughout the application. All beans are initialized following their configuration order right after the application context is instantiated. Even if you don't get any beans in your application, all beans instances are already created the moment after you created the application context.
create example script as resp :
#!/bin/bash
http_code=200
mime=text/html
echo -e "HTTP/1.1 $http_code OK\r"
echo "Content-type: $mime"
echo
echo "Set-Cookie: name=F"
then make executable and execute like this.
./resp | nc -l -p 12346
open browser and browse URL: http://localhost:1236 you will see Cookie value which is sent by Browser
[aaa@bbbbbbbb ]$ ./resp | nc -l -p 12346 GET / HTTP/1.1 Host: xxx.xxx.xxx.xxx:12346 Connection: keep-alive Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8,ru;q=0.6 Cookie: name=F
For i = 0 To dt.Rows.Count - 1
ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)
Next
-1 is get
's way of saying you've reached the end of file. Compare it using the std::char_traits<char>::eof()
(or std::istream::traits_type::eof()
) - avoid -1, it's a magic number. (Although the other one is a bit verbose - you can always just call istream::eof
)
The EOF flag is only set once a read tries to read past the end of the file. If I have a 3 byte file, and I only read 3 bytes, EOF is false
, because I've not tried to read past the end of the file yet. While this seems confusing for files, which typically know their size, EOF is not known until a read is attempted on some devices, such as pipes and network sockets.
The second example works as inf >> foo
will always return inf
, with the side effect of attempt to read something and store it in foo
. inf
, in an if
or while
, will evaluate to true
if the file is "good": no errors, no EOF. Thus, when a read fails, inf
evaulates to false
, and your loop properly aborts. However, take this common error:
while(!inf.eof()) // EOF is false here
{
inf >> x; // read fails, EOF becomes true, x is not set
// use x // we use x, despite our read failing.
}
However, this:
while(inf >> x) // Attempt read into x, return false if it fails
{
// will only be entered if read succeeded.
}
Which is what we want.
The new urllib3 library has a nice documentation here
In order to get your desired result you shuld follow that:
Import urllib3
from bs4 import BeautifulSoup
url = 'http://www.thefamouspeople.com/singers.php'
http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data.decode('utf-8'))
The "decode utf-8" part is optional. It worked without it when i tried, but i posted the option anyway.
Source: User Guide
When using worker with -Q parameter to define queues, for example
celery worker -Q queue1,queue2,queue3
then celery purge
will not work, because you cannot pass the queue params to it. It will only delete the default queue.
The solution is to start your workers with --purge
parameter like this:
celery worker -Q queue1,queue2,queue3 --purge
This will however run the worker.
Other option is to use the amqp subcommand of celery
celery amqp queue.delete queue1
celery amqp queue.delete queue2
celery amqp queue.delete queue3
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
@Html.DropDownListFor(m => m.Departments.id, (SelectList)ViewBag.Department, "Select", htmlAttributes: new { @class = "form-control" })
I have an answer for you Yes, It is possible.
Go to
SQL Server Management Studio > select Database > click on attach
Then select and add .mdf and .ldf file. Click on OK.
If you are using webpack 4
, the following code is tree shakable.
import { has } from 'lodash-es';
The points to note;
CommonJS modules are not tree shakable so you should definitely use lodash-es
, which is the Lodash library exported as ES Modules, rather than lodash
(CommonJS).
lodash-es
's package.json contains "sideEffects": false
, which notifies webpack 4 that all the files inside the package are side effect free (see https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free).
This information is crucial for tree shaking since module bundlers do not tree shake files which possibly contain side effects even if their exported members are not used in anywhere.
Edit
As of version 1.9.0, Parcel also supports "sideEffects": false
, threrefore import { has } from 'lodash-es';
is also tree shakable with Parcel.
It also supports tree shaking CommonJS modules, though it is likely tree shaking of ES Modules is more efficient than CommonJS according to my experiment.
The 00947 message indicates that the record which you are trying to send to Oracle lacks one or more of the columns which was included at the time the table was created. The 00913 message indicates that the record which you are trying to send to Oracle includes more columns than were included at the time the table was created. You just need to check the number of columns and its type in both the tables ie the tables that are involved in the sql.
use grep -n -i null myfile.txt
to output the line number in front of each match.
I dont think grep has a switch to print the count of total lines matched, but you can just pipe grep's output into wc to accomplish that:
grep -n -i null myfile.txt | wc -l
You can try this:
/*iPad landscape oriented styles */
@media only screen and (device-width:768px)and (orientation:landscape){
.yourstyle{
}
}
/*iPad Portrait oriented styles */
@media only screen and (device-width:768px)and (orientation:portrait){
.yourstyle{
}
}
I disagree with the document.write
technique (see suggestion of Vahan Margaryan). I like document.getElementsByTagName('head')[0].appendChild(...)
(see suggestion of Matt Ball), but there is one important issue: the script execution order.
Recently, I have spent a lot of time reproducing one similar issue, and even the well-known jQuery plugin uses the same technique (see src here) to load the files, but others have also reported the issue. Imagine you have JavaScript library which consists of many scripts, and one loader.js
loads all the parts. Some parts are dependent on one another. Imagine you include another main.js
script per <script>
which uses the objects from loader.js
immediately after the loader.js
. The issue was that sometimes main.js
is executed before all the scripts are loaded by loader.js
. The usage of $(document).ready(function () {/*code here*/});
inside of main.js
script does not help. The usage of cascading onload
event handler in the loader.js
will make the script loading sequential instead of parallel, and will make it difficult to use main.js
script, which should just be an include somewhere after loader.js
.
By reproducing the issue in my environment, I can see that **the order of execution of the scripts in Internet Explorer 8 can differ in the inclusion of the JavaScript*. It is a very difficult issue if you need include scripts that are dependent on one another. The issue is described in Loading Javascript files in parallel, and the suggested workaround is to use document.writeln
:
document.writeln("<script type='text/javascript' src='Script1.js'></script>");
document.writeln("<script type='text/javascript' src='Script2.js'></script>");
So in the case of "the scripts are downloaded in parallel but executed in the order they're written to the page", after changing from document.getElementsByTagName('head')[0].appendChild(...)
technique to document.writeln
, I had not seen the issue anymore.
So I recommend that you use document.writeln
.
UPDATED: If somebody is interested, they can try to load (and reload) the page in Internet Explorer (the page uses the document.getElementsByTagName('head')[0].appendChild(...)
technique), and then compare with the fixed version used document.writeln
. (The code of the page is relatively dirty and is not from me, but it can be used to reproduce the issue).
I was about to advise to extract all the files at the same level, then to make a jar out of the result, since the package system should keep them neatly separated. That would be the manual way, I suppose the tools indicated by Steve will do that nicely.
In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:
$_SERVER['DOCUMENT_ROOT']
The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.
yourbox{
position:absolute;
right:<x>px;
top :<x>px;
}
positions it in the right corner. Note, that the position is dependent of the first ancestor-element which is not static
positioned!
EDIT:
I had this issue where on a screen orientation change, the activity finished before the AsyncTask with the progress dialog completed. I seemed to resolve this by setting the dialog to null onPause()
and then checking this in the AsyncTask before dismissing.
@Override
public void onPause() {
super.onPause();
if ((mDialog != null) && mDialog.isShowing())
mDialog.dismiss();
mDialog = null;
}
... in my AsyncTask:
protected void onPreExecute() {
mDialog = ProgressDialog.show(mContext, "", "Saving changes...",
true);
}
protected void onPostExecute(Object result) {
if ((mDialog != null) && mDialog.isShowing()) {
mDialog.dismiss();
}
}
You can not ask for instance during configuration phase - you can ask only for providers.
var app = angular.module('modx', []);
// configure stuff
app.config(function($routeProvider, $locationProvider) {
// you can inject any provider here
});
// run blocks
app.run(function($rootScope) {
// you can inject any instance here
});
See http://docs.angularjs.org/guide/module for more info.
What you want to do is a bad idea. It would require you to embed your username and password in the app. This is a very bad idea as it might be possible to reverse engineer your APK and get the username and password to this publicly facing mysql server which may contain sensitive user data.
I would suggest making a web service to act as a proxy to the mysql server. I assume users need to be logged in, so you could use their username/password to authenticate to the web service.
The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in this activestate recipe
#!/usr/bin/python
import fcntl, socket, struct
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ':'.join(['%02x' % ord(char) for char in info[18:24]])
print getHwAddr('eth0')
This is the Python 3 compatible code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import fcntl
import socket
import struct
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', bytes(ifname, 'utf-8')[:15]))
return ':'.join('%02x' % b for b in info[18:24])
def main():
print(getHwAddr('enp0s8'))
if __name__ == "__main__":
main()
Since this answer is tagged with r-faq, I felt it would be useful to share another alternative from base R: stack
.
Note, however, that stack
does not work with factor
s--it only works if is.vector
is TRUE
, and from the documentation for is.vector
, we find that:
is.vector
returnsTRUE
if x is a vector of the specified mode having no attributes other than names. It returnsFALSE
otherwise.
I'm using the sample data from @Jaap's answer, where the values in the year columns are factor
s.
Here's the stack
approach:
cbind(wide[1:2], stack(lapply(wide[-c(1, 2)], as.character)))
## Code Country values ind
## 1 AFG Afghanistan 20,249 1950
## 2 ALB Albania 8,097 1950
## 3 AFG Afghanistan 21,352 1951
## 4 ALB Albania 8,986 1951
## 5 AFG Afghanistan 22,532 1952
## 6 ALB Albania 10,058 1952
## 7 AFG Afghanistan 23,557 1953
## 8 ALB Albania 11,123 1953
## 9 AFG Afghanistan 24,555 1954
## 10 ALB Albania 12,246 1954
In case you'd happen to be using rails and the angular-rails gem then the problem is easily corrected by adding this missing line to application.js (or what ever is applicable in your situation):
//= require angular-resource
I surprise no one had mentioned this possible easy approach in visual studio code.
Install VS Code and Apache maven ( just as mentioned by @Steve Chambers)
After installing this extension vscode:extension/vscjava.vscode-java-pack
In the java overview page , there is a an option which reads 'Create Maven Project' which further takes to a simple wizard to generate maven project.
Its pretty quick which is intutitive enough, even newbies can very well start with a Maven project.
If you are able to copy the actual SQLite database file to your desktop, you can use this tools to browse the data.
First all need to do is start hadoop nodes and Trackers, simply by typing start-all.sh on ur terminal. To check all the trackers and nodes are started write 'jps' command. if everything is fine and working, go to your browser type the following url http://localhost:50070
Try this, it also handles the single quote which is failed to parse by JSON.parse() method and also supports the UTF-8 character code.
parseJSON = function() {
var data = {};
var reader = new FileReader();
reader.onload = function() {
try {
data = JSON.parse(reader.result.replace(/'/g, "\""));
} catch (ex) {
console.log('error' + ex);
}
};
reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}
You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.
...I have a string "-9o0-9909" and I want to replace it with another string.
The code below will do that.
var str = '-9o0-9909';
str = 'new string';
Jokes aside, replacing text nodes is not trivial with JavaScript.
I've written a post about this: Replacing text with JavaScript.
You should use view models and forget about ViewBag
Think of it as if it didn't exist. You will see how easier things will become. So define a view model:
public class MyViewModel
{
public int SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
and then populate this view model from the controller:
public ActionResult NewsEdit(int ID, dms_New dsn)
{
var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
var categories = (from b in dc.dms_NewsCategories select b).ToList();
var model = new MyViewModel
{
SelectedCategoryId = dsn.NewsCategoriesID,
Categories = categories.Select(x => new SelectListItem
{
Value = x.NewsCategoriesID.ToString(),
Text = x.NewsCategoriesName
})
};
return View(model);
}
and finally in your view use the strongly typed DropDownListFor
helper:
@model MyViewModel
@Html.DropDownListFor(
x => x.SelectedCategoryId,
Model.Categories
)
In most browsers, there's a slightly more succinct way of removing an element from the DOM than calling .removeChild(element)
on its parent, which is to just call element.remove()
. In due course, this will probably become the standard and idiomatic way of removing an element from the DOM.
The .remove()
method was added to the DOM Living Standard in 2011 (commit), and has since been implemented by Chrome, Firefox, Safari, Opera, and Edge. It was not supported in any version of Internet Explorer.
If you want to support older browsers, you'll need to shim it. This turns out to be a little irritating, both because nobody seems to have made a all-purpose DOM shim that contains these methods, and because we're not just adding the method to a single prototype; it's a method of ChildNode
, which is just an interface defined by the spec and isn't accessible to JavaScript, so we can't add anything to its prototype. So we need to find all the prototypes that inherit from ChildNode
and are actually defined in the browser, and add .remove
to them.
Here's the shim I came up with, which I've confirmed works in IE 8.
(function () {
var typesToPatch = ['DocumentType', 'Element', 'CharacterData'],
remove = function () {
// The check here seems pointless, since we're not adding this
// method to the prototypes of any any elements that CAN be the
// root of the DOM. However, it's required by spec (see point 1 of
// https://dom.spec.whatwg.org/#dom-childnode-remove) and would
// theoretically make a difference if somebody .apply()ed this
// method to the DOM's root node, so let's roll with it.
if (this.parentNode != null) {
this.parentNode.removeChild(this);
}
};
for (var i=0; i<typesToPatch.length; i++) {
var type = typesToPatch[i];
if (window[type] && !window[type].prototype.remove) {
window[type].prototype.remove = remove;
}
}
})();
This won't work in IE 7 or lower, since extending DOM prototypes isn't possible before IE 8. I figure, though, that on the verge of 2015 most people needn't care about such things.
Once you've included them shim, you'll be able to remove a DOM element element
from the DOM by simply calling
element.remove();
Suppose your application has package name as com.company.myproject
. Then you can set the logging level for classes inside your project as given below in application.properties files
logging.level.com.company.myproject = DEBUG
logging.level.org.springframework.web = DEBUG
and logging.level.org.hibernate = DEBUG
will set logging level for classes of Spring framework web and Hibernate only.
For setting the logging file location use
logging.file = /home/ubuntu/myproject.log
$ git clone --bare https://github.com/example
This command will make the new "example
" directory itself the $GIT_DIR (instead of example/.git
). Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping. When this option is used, neither remote-tracking branches nor the related configuration variables are created.
$ git clone --mirror https://github.com/example
As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references (including remote-tracking branches, notes etc.) will be overwritten each time you fetch, so it will always be the same as the original repository.
I got the same error and ended up using a pre-built distribution of numpy available in SourceForge (similarly, a distribution of matplotlib can be obtained).
Builds for both 32-bit 2.7 and 3.3/3.4 are available.
PyCharm detected them straight away, of course.
awk
awk '{gsub(/two.*/,"")}1' file
Ruby
ruby -ne 'print $_.gsub(/two.*/,"")' file
I realize the question might be rather old, but you say the backend is running on the same server. That means on a different port, probably other than the default port 80.
I've read that when you use the "connectionManagement" configuration element, you need to specify the port number if it differs from the default 80.
LINK: maxConnection setting may not work even autoConfig = false in ASP.NET
Secondly, if you choose to use the default configuration (address="*") extended with your own backend specific value, you might consider putting the specific value first! Otherwise, if a request is made, the * matches first and the default of 2 connections is taken. Just like when you use the section in web.config.
LINK: <remove> Element for connectionManagement (Network Settings)
Hope it helps someone.
Historically (we're talking the 1980s and early 1990s), there were some architectures in which this was true. The root issue is that integer comparison is inherently implemented via integer subtractions. This gives rise to the following cases.
Comparison Subtraction
---------- -----------
A < B --> A - B < 0
A = B --> A - B = 0
A > B --> A - B > 0
Now, when A < B
the subtraction has to borrow a high-bit for the subtraction to be correct, just like you carry and borrow when adding and subtracting by hand. This "borrowed" bit was usually referred to as the carry bit and would be testable by a branch instruction. A second bit called the zero bit would be set if the subtraction were identically zero which implied equality.
There were usually at least two conditional branch instructions, one to branch on the carry bit and one on the zero bit.
Now, to get at the heart of the matter, let's expand the previous table to include the carry and zero bit results.
Comparison Subtraction Carry Bit Zero Bit
---------- ----------- --------- --------
A < B --> A - B < 0 0 0
A = B --> A - B = 0 1 1
A > B --> A - B > 0 1 0
So, implementing a branch for A < B
can be done in one instruction, because the carry bit is clear only in this case, , that is,
;; Implementation of "if (A < B) goto address;"
cmp A, B ;; compare A to B
bcz address ;; Branch if Carry is Zero to the new address
But, if we want to do a less-than-or-equal comparison, we need to do an additional check of the zero flag to catch the case of equality.
;; Implementation of "if (A <= B) goto address;"
cmp A, B ;; compare A to B
bcz address ;; branch if A < B
bzs address ;; also, Branch if the Zero bit is Set
So, on some machines, using a "less than" comparison might save one machine instruction. This was relevant in the era of sub-megahertz processor speed and 1:1 CPU-to-memory speed ratios, but it is almost totally irrelevant today.
If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors();
in the configure
method. The method looks like that:
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests() // authorize
.anyRequest().authenticated() // all requests are authenticated
.and()
.httpBasic();
http.cors();
}
Here is a QuickSort that I wrote for the arrays returned from the GetRows method of ADODB.Recordset.
'Author: Eric Weilnau
'Date Written: 7/16/2003
'Description: QuickSortDataArray sorts a data array using the QuickSort algorithm.
' Its arguments are the data array to be sorted, the low and high
' bound of the data array, the integer index of the column by which the
' data array should be sorted, and the string "asc" or "desc" for the
' sort order.
'
Sub QuickSortDataArray(dataArray, loBound, hiBound, sortField, sortOrder)
Dim pivot(), loSwap, hiSwap, count
ReDim pivot(UBound(dataArray))
If hiBound - loBound = 1 Then
If (sortOrder = "asc" and dataArray(sortField,loBound) > dataArray(sortField,hiBound)) or (sortOrder = "desc" and dataArray(sortField,loBound) < dataArray(sortField,hiBound)) Then
Call SwapDataRows(dataArray, hiBound, loBound)
End If
End If
For count = 0 to UBound(dataArray)
pivot(count) = dataArray(count,int((loBound + hiBound) / 2))
dataArray(count,int((loBound + hiBound) / 2)) = dataArray(count,loBound)
dataArray(count,loBound) = pivot(count)
Next
loSwap = loBound + 1
hiSwap = hiBound
Do
Do While (sortOrder = "asc" and dataArray(sortField,loSwap) <= pivot(sortField)) or sortOrder = "desc" and (dataArray(sortField,loSwap) >= pivot(sortField))
loSwap = loSwap + 1
If loSwap > hiSwap Then
Exit Do
End If
Loop
Do While (sortOrder = "asc" and dataArray(sortField,hiSwap) > pivot(sortField)) or (sortOrder = "desc" and dataArray(sortField,hiSwap) < pivot(sortField))
hiSwap = hiSwap - 1
Loop
If loSwap < hiSwap Then
Call SwapDataRows(dataArray,loSwap,hiSwap)
End If
Loop While loSwap < hiSwap
For count = 0 to Ubound(dataArray)
dataArray(count,loBound) = dataArray(count,hiSwap)
dataArray(count,hiSwap) = pivot(count)
Next
If loBound < (hiSwap - 1) Then
Call QuickSortDataArray(dataArray, loBound, hiSwap-1, sortField, sortOrder)
End If
If (hiSwap + 1) < hiBound Then
Call QuickSortDataArray(dataArray, hiSwap+1, hiBound, sortField, sortOrder)
End If
End Sub
X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!
There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.
Source: classroomm.com
you should reconfigure the phpmyadmin On terminal:
You would read from System.in
just like you would for keyboard input using, for example, InputStreamReader or Scanner.
In Rails:
"kirk douglas".titleize => "Kirk Douglas"
#this also works for 'kirk_douglas'
w/o Rails:
"kirk douglas".split(/ |\_/).map(&:capitalize).join(" ")
#OBJECT IT OUT
def titleize(str)
str.split(/ |\_/).map(&:capitalize).join(" ")
end
#OR MONKEY PATCH IT
class String
def titleize
self.split(/ |\_/).map(&:capitalize).join(" ")
end
end
w/o Rails (load rails's ActiveSupport to patch #titleize method to String
)
require 'active_support/core_ext'
"kirk douglas".titleize #=> "Kirk Douglas"
Rails's titleize
will convert things like dashes and underscores into spaces and can produce other unexpected results, especially with case-sensitive situations as pointed out by @JamesMcMahon:
"hEy lOok".titleize #=> "H Ey Lo Ok"
because it is meant to handle camel-cased code like:
"kirkDouglas".titleize #=> "Kirk Douglas"
To deal with this edge case you could clean your string with #downcase
first before running #titleize. Of course if you do that you will wipe out any camelCased word separations:
"kirkDouglas".downcase.titleize #=> "Kirkdouglas"
BadImageFormatException
, in my experience, is almost always to do with x86 versus x64 compiled assemblies. It sounds like your C++ assembly is compiled for x86 and you are running on an x64 process. Is that correct?
Instead of using AnyCPU/Mixed
as the platform. Try to manually set it to x86
and see if it will run after that.
Hope this helps.
For what you are trying to do, instead of PreparedStatement
you can use Statement
. Your code may be modified as-
String sql = "SELECT column_name from information_schema.columns where table_name='suppliers';";
Statement s = connection.createStatement();
ResultSet rs = s.executeQuery(sql);
Hope this helps.
Use
a = sorted(a, key=lambda x: x.modified, reverse=True)
# ^^^^
On Python 2.x, the sorted
function takes its arguments in this order:
sorted(iterable, cmp=None, key=None, reverse=False)
so without the key=
, the function you pass in will be considered a cmp
function which takes 2 arguments.
In javascript you have to use \. to match a dot.
Example
"blah.tests.zibri.org".match('test\\..*')
null
and
"blah.test.zibri.org".match('test\\..*')
["test.zibri.org", index: 5, input: "blah.test.zibri.org", groups: undefined]
Looks like you typed brackets instead of parenthesis by mistake.
This will make sure that the SpringBoot application is closed properly and the resources are released back to the operating system,
@Autowired
private ApplicationContext context;
@GetMapping("/shutdown-app")
public void shutdownApp() {
int exitCode = SpringApplication.exit(context, (ExitCodeGenerator) () -> 0);
System.exit(exitCode);
}
I had the same problem on a methood that returns the status of the server. The application is deployed on multiple servers. So the easiest I found is to add
@CrossOrigin(origins = "*")
@RequestMapping(value="/schedulerActive")
public String isSchedulerActive(){
//code goes here
}
This method is not secure but you can add allowCredentials
for that.
Interestingly array is randomly accessible by the index. And removing randomly an element may impact the indexes of other elements as well.
int remove_element(int*from, int total, int index) {
if((total - index - 1) > 0) {
memmove(from+i, from+i+1, sizeof(int)*(total-index-1));
}
return total-1; // return the new array size
}
Note that memcpy
will not work in this case because of the overlapping memory.
One of the efficient way (better than memory move) to remove one random element is swapping with the last element.
int remove_element(int*from, int total, int index) {
if(index != (total-1))
from[index] = from[total-1];
return total; // **DO NOT DECREASE** the total here
}
But the order is changed after the removal.
Again if the removal is done in loop operation then the reordering may impact processing. Memory move is one expensive alternative to keep the order while removing an array element. Another of the way to keep the order while in a loop is to defer the removal. It can be done by validity array of the same size.
int remove_element(int*from, int total, int*is_valid, int index) {
is_valid[index] = 0;
return total-1; // return the number of elements
}
It will create a sparse array. Finally, the sparse array can be made compact(that contains no two valid elements that contain invalid element between them) by doing some reordering.
int sparse_to_compact(int*arr, int total, int*is_valid) {
int i = 0;
int last = total - 1;
// trim the last invalid elements
for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements from last
// now we keep swapping the invalid with last valid element
for(i=0; i < last; i++) {
if(is_valid[i])
continue;
arr[i] = arr[last]; // swap invalid with the last valid
last--;
for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements
}
return last+1; // return the compact length of the array
}