I was looking for a solution for this and found this great article explaining the solution Relevant excerpt
My all-time-favorite use of ROWNUM is pagination. In this case, I use ROWNUM to get rows N through M of a result set. The general form is as follows:
select * enter code here
from ( select /*+ FIRST_ROWS(n) */
a.*, ROWNUM rnum
from ( your_query_goes_here,
with order by ) a
where ROWNUM <=
:MAX_ROW_TO_FETCH )
where rnum >= :MIN_ROW_TO_FETCH;
Now with a real example (gets rows 148, 149 and 150):
select *
from
(select a.*, rownum rnum
from
(select id, data
from t
order by id, rowid) a
where rownum <= 150
)
where rnum >= 148;
Postgresql does not have an equivalent of Oracle's ROWNUM. In many cases you can achieve the same result by using LIMIT and OFFSET in your query.
Use ROW_NUMBER()
instead. ROWNUM
is a pseudocolumn and ROW_NUMBER()
is a function. You can read about difference between them and see the difference in output of below queries:
SELECT * FROM (SELECT rownum, deptno, ename
FROM scott.emp
ORDER BY deptno
)
WHERE rownum <= 3
/
ROWNUM DEPTNO ENAME
---------------------------
7 10 CLARK
14 10 MILLER
9 10 KING
SELECT * FROM
(
SELECT deptno, ename
, ROW_NUMBER() OVER (ORDER BY deptno) rno
FROM scott.emp
ORDER BY deptno
)
WHERE rno <= 3
/
DEPTNO ENAME RNO
-------------------------
10 CLARK 1
10 MILLER 2
10 KING 3
The below query helps to get the row number in oracle,
SELECT ROWNUM AS SNO,ID,NAME,EMAIL,BRANCH FROM student WHERE NAME LIKE '%ram%';
Simply:
UIView
as wrapper with auto layout to views around. UILabel
inside that wrapper. Add constraints that will stick tyour label to edges of wrapper.UIButton
inside your wrapper, then simple add the same constraints as you did for UILabel
.Worth noting that the code you see is sent to the database as is, the queries are sent separately to prevent SQL injection. AFAIK The ? marks are placeholders that are replaced by the number params by the database, not by hibernate.
Here are a couple possible solutions...
I have not tried all of these myself yet, but I will be trying them all soon.
Note: I do not have any personal or financial connection to any of these tools.
1) VB Script to EXE Converter (NOT Compiler): (Free)
vbs2exe.com.
The exe produced appears to be a true EXE.
From their website:
VBS to EXE is a free online converter that doesn't only convert your vbs files into exe but it also:
1- Encrypt your vbs file source code using 128 bit key.
2- Allows you to call win32 API
3- If you have troubles with windows vista especially when UAC is enabled then you may give VBS to EXE a try.
4- No need for wscript.exe to run your vbs anymore.
5- Your script is never saved to the hard disk like some others converters. it is a TRUE exe not an extractor.
This solution should work even if wscript/cscript is not installed on the computer.
Basically, this creates a true .EXE file. Inside the created .EXE is an "engine" that replaces wscript/cscript, and an encrypted copy of your VB Script code. This replacement engine executes your code IN MEMORY without calling wscript/cscript to do it.
2) Compile and Convert VBS to EXE...:
ExeScript
The current version is 3.5.
This is NOT a Free solution. They have a 15 day trial. After that, you need to buy a license for a hefty $44.96 (Home License/noncommercial), or $89.95 (Business License/commercial usage).
It seems to work in a similar way to the previous solution.
According to a forum post there:
Post: "A Exe file still need Windows Scripting Host (WSH) ??"
WSH is not required if "Compile" option was used, since ExeScript
implements it's own scripting host. ...
3) Encrypt the script with Microsoft's ".vbs to .vbe" encryption tool.
Apparently, this does not work for Windows 7/8, and it is possible there are ways to "decrypt" the .vbe file. At the time of writing this, I could not find a working link to download this. If I find one, I will add it to this answer.
So use the client-side loop to build a two-dimensional array of your arrays, and send the entire thing to PHP in one request.
Server-side, you'll need to have another loop which does its regular insert/update for each sub-array.
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
string str = "Data Source=HARIHARAN-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True" ;
For Python2.7 - modifying MYGz's answer to not strip milliseconds:
from datetime import datetime
d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s.%f')
d_in_ms = int(float(d)*1000)
print(d_in_ms)
print(datetime.fromtimestamp(float(d)))
Output:
1482248322760
2016-12-20 09:38:42.760000
Most answers are way too complicated in my opinion, how about this?
digits = 2 # Specify how many digits you want
fnum = '122.485221'
truncated_float = float(fnum[:fnum.find('.') + digits + 1])
>>> 122.48
Simply scanning for the index of '.' and truncate as desired (no rounding). Convert string to float as final step.
Or in your case if you get a float as input and want a string as output:
fnum = str(122.485221) # convert float to string first
truncated_float = fnum[:fnum.find('.') + digits + 1] # string output
In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime()
gives you the mentioned milliseconds).
In your solution:
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();
long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);
you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.
Another possible solution would be to utilise the static fields of the Calendar
class:
//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);
Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.
To get rid of the first column of NAs, you can do it with negative indexing (which removes indices from the R data set). For example:
output = matrix(1:6, 2, 3) # gives you a 2 x 3 matrix filled with the numbers 1 to 6
# output =
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
output = output[,-1] # this removes column 1 for all rows
# output =
# [,1] [,2]
# [1,] 3 5
# [2,] 4 6
So you can just add output = output[,-1]
after the for loop in your original code.
A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
public class ImageButton extends Button {
public void updateImages(final Image selected, final Image unselected) {
final ImageView iv = new ImageView(selected);
this.getChildren().add(iv);
iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(unselected);
}
});
iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(selected);
}
});
super.setGraphic(iv);
}
}
You need to enable the SQL Server TCP/IP Protocol in Sql Server Configuration Manager app. You can see the protocol in SQL Server Network Configuration.
The shiny
package provides the convenient functions validate()
and need()
for checking that variables are both available and valid. need()
evaluates an expression. If the expression is not valid, then an error message is returned. If the expression is valid, NULL
is returned. One can use this to check if a variable is valid. See ?need
for more information.
I suggest defining a function like this:
is.valid <- function(x) {
require(shiny)
is.null(need(x, message = FALSE))
}
This function is.valid()
will return FALSE
if x
is FALSE
, NULL
, NA
, NaN
, an empty string ""
, an empty atomic vector, a vector containing only missing values, a logical vector containing only FALSE
, or an object of class try-error
. In all other cases, it returns TRUE
.
That means, need()
(and is.valid()
) covers a really broad range of failure cases. Instead of writing:
if (!is.null(x) && !is.na(x) && !is.nan(x)) {
...
}
one can write simply:
if (is.valid(x)) {
...
}
With the check for class try-error
, it can even be used in conjunction with a try()
block to silently catch errors: (see https://csgillespie.github.io/efficientR/programming.html#communicating-with-the-user)
bad = try(1 + "1", silent = TRUE)
if (is.valid(bad)) {
...
}
Use Thread.sleep(1000)
;
1000
is the number of milliseconds that the program will pause.
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
JS Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time='+ time + '&date=' + date;
if(time=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
HTML Form
<form>
<input id="time" value="00:00:00.00"><br>
<input id="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
</div>
PHP Code
<?php
if($_POST)
{
$date=$_POST['date'];
$time=$_POST['time'];
mysql_query("SQL insert statement.......");
}else { }
?>
Taken From Here
I wrote a generic solution in C# loosely based on @Mehrdad Afshari answer:
void Example(List<MyObject> actualObjects)
{
List<TreeNode<MyObject>> treeRoots = actualObjects.BuildTree(obj => obj.ID, obj => obj.ParentID, -1);
}
public class TreeNode<T>
{
public TreeNode(T value)
{
Value = value;
Children = new List<TreeNode<T>>();
}
public T Value { get; private set; }
public List<TreeNode<T>> Children { get; private set; }
}
public static class TreeExtensions
{
public static List<TreeNode<TValue>> BuildTree<TKey, TValue>(this IEnumerable<TValue> objects, Func<TValue, TKey> keySelector, Func<TValue, TKey> parentKeySelector, TKey defaultKey = default(TKey))
{
var roots = new List<TreeNode<TValue>>();
var allNodes = objects.Select(overrideValue => new TreeNode<TValue>(overrideValue)).ToArray();
var nodesByRowId = allNodes.ToDictionary(node => keySelector(node.Value));
foreach (var currentNode in allNodes)
{
TKey parentKey = parentKeySelector(currentNode.Value);
if (Equals(parentKey, defaultKey))
{
roots.Add(currentNode);
}
else
{
nodesByRowId[parentKey].Children.Add(currentNode);
}
}
return roots;
}
}
The answer is not as easy as a simple yes or no. Check out the results of a test I recently did:
So after digging further I found this, which explains how each browser handles loading img assets based on css display: none;
Excerpt from the blog post:
- Chrome and Safari (WebKit):
WebKit downloads the file every time except when a background is applied through a non-matching media-query.- Firefox:
Firefox won't download the image called with background image if the styles are hidden but they will still download assets from img tags.- Opera:
Like Firefox does, Opera won't load useless background-images.- Internet Explorer:
IE, like WebKit will download background-images even if they have display: none; Something odd appears with IE6 : Elements with a background-image and display: none set inline won't be downloaded... But they will be if those styles aren't applied inline.
I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.
It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.
Using _blank
will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).
I believe your best shot is to declare the list as a list of objects:
List<Object> anything = new ArrayList<Object>();
Then you can put whatever you want in it, like:
anything.add(new Employee(..))
Evidently, you will not be able to read anything out of the list without a proper casting:
Employee mike = (Employee) anything.get(0);
I would discourage the use of raw types like:
List anything = new ArrayList()
Since the whole purpose of generics is precisely to avoid them, in the future Java may no longer suport raw types, the raw types are considered legacy and once you use a raw type you are not allowed to use generics at all in a given reference. For instance, take a look a this another question: Combining Raw Types and Generic Methods
I was searching an answer for this same question and found ENTRYPOINT in Dockerfile solution for me.
Dockerfile
...
ENTRYPOINT /my-script.sh ; /my-script2.sh ; /bin/bash
Now the scripts are executed when I start the container and I get the bash prompt after the scripts has been executed.
I just had the same problem with a cookie which was set to expire on "Browsing session end".
Unfortunately it did not so I played a bit with the settings of the browser.
Turned out that the feature that remembers the opened tabs when the browser is closed was the root of the problem. (The feature is named "On startup" - "Continue where I left off". At least on the current version of Chrome).
This also happens with Opera and Firefox.
(Alt + Shift + X) , then M
to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations
A slightly modified version of Sophie's answer which allows to output the *.d files to a different folder (I will only paste the interesting part that generates the dependency files):
$(OBJDIR)/%.o: %.cpp
# Generate dependency file
mkdir -p $(@D:$(OBJDIR)%=$(DEPDIR)%)
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -MM -MT $@ $< -MF $(@:$(OBJDIR)/%.o=$(DEPDIR)/%.d)
# Generate object file
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $< -o $@
Note that the parameter
-MT $@
is used to ensure that the targets (i.e. the object file names) in the generated *.d files contain the full path to the *.o files and not just the file name.
I don't know why this parameter is NOT needed when using -MMD in combination with -c (as in Sophie's version). In this combination it seems to write the full path of the *.o files into the *.d files. Without this combination, -MMD also writes only the pure file names without any directory components into the *.d files. Maybe somebody knows why -MMD writes the full path when combined with -c. I have not found any hint in the g++ man page.
There are many answers that provide removing the last commit. However, here is asked how to remove specific commits, and in this case it is to remove the last three commits, to go back to commit on November 3.
You can do this with rebase. Simply do:
git rebase -i HEAD~4
This will list your last four commits.
Now you have the option to remove commits. You do that with drop
text.
Simply hit i
on your keyboard and next to commits you want to remove write drop
instead of default pick
On the keyboard, hit exit
and :wq
To make sure that commits are removed, write:
git log
You will see that commits you saved as drop are removed.
To push those changes to your remote branch, write:
git push --force
Now that Javascript has lookbehind (as of ES2018), on newer environments, you can avoid groups entirely in situations like these. Rather, lookbehind for what comes before the group you were capturing, and lookahead for what comes after, and replace with just !NEW_ID!
:
const str = 'name="some_text_0_some_text"';
console.log(
str.replace(/(?<=name="\w+)\d+(?=\w+")/, '!NEW_ID!')
);
_x000D_
With this method, the full match is only the part that needs to be replaced.
(?<=name="\w+)
- Lookbehind for name="
, followed by word characters (luckily, lookbehinds do not have to be fixed width in Javascript!)\d+
- Match one or more digits - the only part of the pattern not in a lookaround, the only part of the string that will be in the resulting match(?=\w+")
- Lookahead for word characters followed by "
`Keep in mind that lookbehind is pretty new. It works in modern versions of V8 (including Chrome, Opera, and Node), but not in most other environments, at least not yet. So while you can reliably use lookbehind in Node and in your own browser (if it runs on a modern version of V8), it's not yet sufficiently supported by random clients (like on a public website).
Disable and re-enable "use debug mode" on your telephone
As a side note, remember that all this output is generated in the server side.
Using DBMS_OUTPUT, the text is generated in the server while it executes your query and stored in a buffer. It is then redirected to your client app when the server finishes the query data retrieval. That is, you only get this info when the query ends.
With UTL_FILE all the information logged will be stored in a file in the server. When the execution finishes you will have to navigate to this file to get the information.
Hope this helps.
Your product
class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.
As a side note: You should use Pascal casing for your class names. That is Product
, and not product
.
if you work with pandas
what solved the issue for me was that i was trying to do calculations when I had NA values, the solution was to run:
df = df.dropna()
And after that the calculation that failed.
For some reason, some of the other methods don't work until the field has been focused/blured/changed, or a submit has been attempted... this works for me.
$("#formid").data('validator').element('#element').valid();
Had to dig through the jquery.validate script to find it...
"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.
You can use JavaScript/Canvas to do the job but it is still experimental.
You can see in pg_log folder if the log configuration is enabled in postgresql.conf with this log directory name.
You need to set the password for root@localhost
to be blank. There are two ways:
The MySQL SET PASSWORD
command:
SET PASSWORD FOR root@localhost=PASSWORD('');
Using the command-line mysqladmin
tool:
mysqladmin -u root -pType_in_your_current_password_here password ''
When you implement the action in the controller, use
return View("Index");
or
return RedirectToAction("Index");
where Index.cshtml (or the page that generates the action) page is already defined. Otherwise you are likely encountering "the view or its master was not found..." error.
Source: https://blogs.msdn.microsoft.com/aspnetue/2010/09/17/best-practices-for-asp-net-mvc/
Yep, both and
and or
operators short-circuit -- see the docs.
Another workaround might be to use <div>
of the same size to wrap the <svg>
. After that, you will be able to apply "background-color"
, and "background-image"
that will affect thesvg
.
<div class="background">
<svg></svg>
</div>
<style type="text/css">
.background{
background-color: black;
/*background-image: */
}
</style>
When looking at an input with a type of number, you'll notice the spinner buttons (up/down) on the right-hand side of the input field. These spinners aren't always desirable, thus the code below removes such styling to render an input that resembles that of an input with a type of text.
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
}
As Tim Potter pointed out, setting proxy in dockerfile is horrible. When building the image, you add proxy for your corporate network but you may be deploying in cloud or a DMZ where there is no need for proxy or the proxy server is different.
Also, you cannot share your image with others outside your corporate n/w.
You need to ensure that C:\Python35\Sripts
is in your system path. Follow the top answer instructions here to do that:
You run the command in windows command prompt, not in the python interpreter that you have open.
Press:
Win + R
Type CMD
in the run window which has opened
Type pip install openpyxl
in windows command prompt.
First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-
<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>
Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-
<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>
Hope it helps.
I just found the VT char in a .pptx document at several places within a table element. But no clue about how it was inserted.
Building upon the shoulders of giants...here's a one-liner I wrote to zap all of Google's current stock data into local Bash shell variables:
stock=$1
# Fetch from Google Finance API, put into local variables
eval $(curl -s "http://www.google.com/ig/api?stock=$stock"|sed 's/</\n</g' |sed '/data=/!d; s/ data=/=/g; s/\/>/; /g; s/</GF_/g' |tee /tmp/stockprice.tmp.log)
echo "$stock,$(date +%Y-%m-%d),$GF_open,$GF_high,$GF_low,$GF_last,$GF_volume"
Then you will have variables like $GF_last $GF_open $GF_volume etc. readily available. Run env or see inside /tmp/stockprice.tmp.log
http://www.google.com/ig/api?stock=TVIX&output=csv by itself returns:
<?xml version="1.0"?>
<xml_api_reply version="1">
<finance module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
<symbol data="TVIX"/>
<pretty_symbol data="TVIX"/>
<symbol_lookup_url data="/finance?client=ig&q=TVIX"/>
<company data="VelocityShares Daily 2x VIX Short Term ETN"/>
<exchange data="AMEX"/>
<exchange_timezone data="ET"/>
<exchange_utc_offset data="+05:00"/>
<exchange_closing data="960"/>
<divisor data="2"/>
<currency data="USD"/>
<last data="57.45"/>
<high data="59.70"/>
<low data="56.85"/>
etc.
So for stock="FBM"
/tmp/stockprice.tmp.log (and your environment) will contain:
GF_symbol="FBM";
GF_pretty_symbol="FBM";
GF_symbol_lookup_url="/finance?client=ig&q=FBM";
GF_company="Focus Morningstar Basic Materials Index ETF";
GF_exchange="NYSEARCA";
GF_exchange_timezone="";
GF_exchange_utc_offset="";
GF_exchange_closing="";
GF_divisor="2";
GF_currency="USD";
GF_last="22.82";
GF_high="22.82";
GF_low="22.82";
GF_volume="100";
GF_avg_volume="";
GF_market_cap="4.56";
GF_open="22.82";
GF_y_close="22.80";
GF_change="+0.02";
GF_perc_change="0.09";
GF_delay="0";
GF_trade_timestamp="8 hours ago";
GF_trade_date_utc="20120228";
GF_trade_time_utc="184541";
GF_current_date_utc="20120229";
GF_current_time_utc="033534";
GF_symbol_url="/finance?client=ig&q=FBM";
GF_chart_url="/finance/chart?q=NYSEARCA:FBM&tlf=12";
GF_disclaimer_url="/help/stock_disclaimer.html";
GF_ecn_url="";
GF_isld_last="";
GF_isld_trade_date_utc="";
GF_isld_trade_time_utc="";
GF_brut_last="";
GF_brut_trade_date_utc="";
GF_brut_trade_time_utc="";
GF_daylight_savings="false";
The big thing about SP_EXECUTESQL is that it allows you to create parameterized queries which is very good if you care about SQL injection.
It might be too late to answer this but I just had the problem and I kept installing and uninstalling, it turns out the the problem happens when you're installing pandas
to a version of python
and trying to run the program using another python version
So to start off, run:
which python
python --version
which pip
make sure both are aligned, most probably, python is 2.7
and pip is working on 3.x
or pip is coming from anaconda's python version which is highly likely to be 3.x
as well
Incase of python
redirects to 2.7, and pip redirects to pip3, install pandas using pip install pandas
and use python3 file_name.py
to run the program.
SELECT count(*)
FROM information_schema.columns
WHERE table_name = 'tbl_ifo'
Having $line
as it is now, you can simply split the string based on at least one whitespace separator
my @answer = split(' ', $line); # creates an @answer array
then
print("@answer\n"); # print array on one line
or
print("$_\n") for (@answer); # print each element on one line
I prefer using ()
for split
, print
and for
.
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
JavaScript is case-sensitive. The b
in getElementbyId
should be capitalized.
var content = document.getElementById("edit").innerHTML;
document.forms["form_name"].getElementsByTagName("input");
You should declare in the Project structure(Ctrl+Alt+Shift+s) in the Module section mark your folders which of them are source package(blue one) and which are test ...
Yes, there are at least 2 solutions for this:
script
directive (http://docs.angularjs.org/api/ng.directive:script) to put your partials in the initially loaded HTML$templateCache
(http://docs.angularjs.org/api/ng.$templateCache) from JavaScript if needed (possibly based on result of $http
call)If you would like to use method (2) to fill in $templateCache
you can do it like this:
$templateCache.put('second.html', '<b>Second</b> template');
Of course the templates content could come from a $http
call:
$http.get('third.html', {cache:$templateCache});
Here is the plunker those techniques: http://plnkr.co/edit/J6Y2dc?p=preview
Thank you very much for the replies!
Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:
1 39.00 9.00
You'll end up with:
1 78.00 48.00
Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.
After much struggling, I think that the following query returns what I need it to:
SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
SELECT invoiceid, SUM(p.amount) amount
FROM invoicepayments ip
LEFT JOIN payments p ON ip.paymentid = p.paymentid
GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'
Would you guys concur?
Just apply width:100%; to body
This command works
Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All
Run it then agree to restart the computer when prompted.
I ran it in elevated permissions PowerShell on Windows 10, but it should also work on Win 8 or 7.
Note: If your issue is, "innodb index is marked as corrupted"! Then, the simple solution can be, just remove the indexes and add them again. That can solve pretty quickly without losing any records nor restarting or moving table contents into a temporary table and back.
Best way to send html formatted Email
This code will be in "Customer.htm"
<table>
<tr>
<td>
Dealer's Company Name
</td>
<td>
:
</td>
<td>
#DealerCompanyName#
</td>
</tr>
</table>
Read HTML file Using System.IO.File.ReadAllText. get all HTML code in string variable.
string Body = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("EmailTemplates/Customer.htm"));
Replace Particular string to your custom value.
Body = Body.Replace("#DealerCompanyName#", _lstGetDealerRoleAndContactInfoByCompanyIDResult[0].CompanyName);
call SendEmail(string Body) Function and do procedure to send email.
public static void SendEmail(string Body)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(Session["Email"].Tostring());
message.To.Add(ConfigurationSettings.AppSettings["RequesEmail"].ToString());
message.Subject = "Request from " + SessionFactory.CurrentCompany.CompanyName + " to add a new supplier";
message.IsBodyHtml = true;
message.Body = Body;
SmtpClient smtpClient = new SmtpClient();
smtpClient.UseDefaultCredentials = true;
smtpClient.Host = ConfigurationSettings.AppSettings["SMTP"].ToString();
smtpClient.Port = Convert.ToInt32(ConfigurationSettings.AppSettings["PORT"].ToString());
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings["USERNAME"].ToString(), ConfigurationSettings.AppSettings["PASSWORD"].ToString());
smtpClient.Send(message);
}
You are very close; currently you compare the row[2]
with integer 0
, make the comparison with the string "0"
. When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:
row[2]!="0":
Also, you can use the with
keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close
statements:
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != "0":
writer.writerow(row)
Note that input
is a Python builtin, so I've used another variable name instead.
Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0"
would work, so you can either use strip(row[2]) != 0
, or check against " 0"
.
The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:
$ cat test.py
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != " 0":
writer.writerow(row)
$ cat first.csv
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py
$ cat first_edit.csv
6.5, 5.4, 1, 320
The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}
Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport
struct over time.
This is just my personal opinion and folks from web API team can probably articulate it better but here is my 2c.
First of all, I think it is not a question of one over another. You can use them both depending on what you want to do in your action method but in order to understand the real power of IHttpActionResult
, you will probably need to step outside those convenient helper methods of ApiController
such as Ok
, NotFound
, etc.
Basically, I think a class implementing IHttpActionResult
as a factory of HttpResponseMessage
. With that mind set, it now becomes an object that need to be returned and a factory that produces it. In general programming sense, you can create the object yourself in certain cases and in certain cases, you need a factory to do that. Same here.
If you want to return a response which needs to be constructed through a complex logic, say lots of response headers, etc, you can abstract all those logic into an action result class implementing IHttpActionResult
and use it in multiple action methods to return response.
Another advantage of using IHttpActionResult
as return type is that it makes ASP.NET Web API action method similar to MVC. You can return any action result without getting caught in media formatters.
Of course, as noted by Darrel, you can chain action results and create a powerful micro-pipeline similar to message handlers themselves in the API pipeline. This you will need depending on the complexity of your action method.
Long story short - it is not IHttpActionResult
versus HttpResponseMessage
. Basically, it is how you want to create the response. Do it yourself or through a factory.
Quick answer:
A child scope normally prototypically inherits from its parent scope, but not always. One exception to this rule is a directive with scope: { ... }
-- this creates an "isolate" scope that does not prototypically inherit. This construct is often used when creating a "reusable component" directive.
As for the nuances, scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name. Your workarounds are
New AngularJS developers often do not realize that ng-repeat
, ng-switch
, ng-view
, ng-include
and ng-if
all create new child scopes, so the problem often shows up when these directives are involved. (See this example for a quick illustration of the problem.)
This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch
.
Having a '.' in your models will ensure that prototypal inheritance is in play. So, use
<input type="text" ng-model="someObj.prop1">
<!--rather than
<input type="text" ng-model="prop1">`
-->
Also placed on the AngularJS wiki: https://github.com/angular/angular.js/wiki/Understanding-Scopes
It is important to first have a solid understanding of prototypal inheritance, especially if you are coming from a server-side background and you are more familiar with class-ical inheritance. So let's review that first.
Suppose parentScope has properties aString, aNumber, anArray, anObject, and aFunction. If childScope prototypically inherits from parentScope, we have:
(Note that to save space, I show the anArray
object as a single blue object with its three values, rather than an single blue object with three separate gray literals.)
If we try to access a property defined on the parentScope from the child scope, JavaScript will first look in the child scope, not find the property, then look in the inherited scope, and find the property. (If it didn't find the property in the parentScope, it would continue up the prototype chain... all the way up to the root scope). So, these are all true:
childScope.aString === 'parent string'
childScope.anArray[1] === 20
childScope.anObject.property1 === 'parent prop1'
childScope.aFunction() === 'parent output'
Suppose we then do this:
childScope.aString = 'child string'
The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name. This will become very important when we discuss ng-repeat and ng-include below.
Suppose we then do this:
childScope.anArray[1] = '22'
childScope.anObject.property1 = 'child prop1'
The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created. (Note that in JavaScript arrays and functions are also objects.)
Suppose we then do this:
childScope.anArray = [100, 555]
childScope.anObject = { name: 'Mark', country: 'USA' }
The prototype chain is not consulted, and child scope gets two new object properties that hide/shadow the parentScope object properties with the same names.
Takeaways:
One last scenario:
delete childScope.anArray
childScope.anArray[1] === 22 // true
We deleted the childScope property first, then when we try to access the property again, the prototype chain is consulted.
The contenders:
scope: true
, directive with transclude: true
.scope: { ... }
. This creates an "isolate" scope instead.Note, by default, directives do not create new scope -- i.e., the default is scope: false
.
Suppose we have in our controller:
$scope.myPrimitive = 50;
$scope.myObject = {aNumber: 11};
And in our HTML:
<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>
<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>
Each ng-include generates a new child scope, which prototypically inherits from the parent scope.
Typing (say, "77") into the first input textbox causes the child scope to get a new myPrimitive
scope property that hides/shadows the parent scope property of the same name. This is probably not what you want/expect.
Typing (say, "99") into the second input textbox does not result in a new child property. Because tpl2.html binds the model to an object property, prototypal inheritance kicks in when the ngModel looks for object myObject -- it finds it in the parent scope.
We can rewrite the first template to use $parent, if we don't want to change our model from a primitive to an object:
<input ng-model="$parent.myPrimitive">
Typing (say, "22") into this input textbox does not result in a new child property. The model is now bound to a property of the parent scope (because $parent is a child scope property that references the parent scope).
For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via scope properties $parent, $$childHead and $$childTail. I normally don't show these scope properties in the diagrams.
For scenarios where form elements are not involved, another solution is to define a function on the parent scope to modify the primitive. Then ensure the child always calls this function, which will be available to the child scope due to prototypal inheritance. E.g.,
// in the parent scope
$scope.setMyPrimitive = function(value) {
$scope.myPrimitive = value;
}
Here is a sample fiddle that uses this "parent function" approach. (The fiddle was written as part of this answer: https://stackoverflow.com/a/14104318/215945.)
See also https://stackoverflow.com/a/13782671/215945 and https://github.com/angular/angular.js/issues/1267.
ng-switch scope inheritance works just like ng-include. So if you need 2-way data binding to a primitive in the parent scope, use $parent, or change the model to be an object and then bind to a property of that object. This will avoid child scope hiding/shadowing of parent scope properties.
See also AngularJS, bind scope of a switch-case?
Ng-repeat works a little differently. Suppose we have in our controller:
$scope.myArrayOfPrimitives = [ 11, 22 ];
$scope.myArrayOfObjects = [{num: 101}, {num: 202}]
And in our HTML:
<ul><li ng-repeat="num in myArrayOfPrimitives">
<input ng-model="num">
</li>
<ul>
<ul><li ng-repeat="obj in myArrayOfObjects">
<input ng-model="obj.num">
</li>
<ul>
For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope. (The name of the new property is the loop variable's name.) Here's what the Angular source code for ng-repeat actually is:
childScope = scope.$new(); // child scope prototypically inherits from parent scope
...
childScope[valueIdent] = value; // creates a new childScope property
If item is a primitive (as in myArrayOfPrimitives), essentially a copy of the value is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence child scope num
) does not change the array the parent scope references. So in the first ng-repeat above, each child scope gets a num
property that is independent of the myArrayOfPrimitives array:
This ng-repeat will not work (like you want/expect it to). Typing into the textboxes changes the values in the gray boxes, which are only visible in the child scopes. What we want is for the inputs to affect the myArrayOfPrimitives array, not a child scope primitive property. To accomplish this, we need to change the model to be an array of objects.
So, if item is an object, a reference to the original object (not a copy) is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence obj.num
) does change the object the parent scope references. So in the second ng-repeat above, we have:
(I colored one line gray just so that it is clear where it is going.)
This works as expected. Typing into the textboxes changes the values in the gray boxes, which are visible to both the child and parent scopes.
See also Difficulty with ng-model, ng-repeat, and inputs and https://stackoverflow.com/a/13782671/215945
Nesting controllers using ng-controller results in normal prototypal inheritance, just like ng-include and ng-switch, so the same techniques apply. However, "it is considered bad form for two controllers to share information via $scope inheritance" -- http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/ A service should be used to share data between controllers instead.
(If you really want to share data via controllers scope inheritance, there is nothing you need to do. The child scope will have access to all of the parent scope properties. See also Controller load order differs when loading or navigating)
scope: false
) - the directive does not create a new scope, so there is no inheritance here. This is easy, but also dangerous because, e.g., a directive might think it is creating a new property on the scope, when in fact it is clobbering an existing property. This is not a good choice for writing directives that are intended as reusable components.scope: true
- the directive creates a new child scope that prototypically inherits from the parent scope. If more than one directive (on the same DOM element) requests a new scope, only one new child scope is created. Since we have "normal" prototypal inheritance, this is like ng-include and ng-switch, so be wary of 2-way data binding to parent scope primitives, and child scope hiding/shadowing of parent scope properties.scope: { ... }
- the directive creates a new isolate/isolated scope. It does not prototypically inherit. This is usually your best choice when creating reusable components, since the directive cannot accidentally read or modify the parent scope. However, such directives often need access to a few parent scope properties. The object hash is used to set up two-way binding (using '=') or one-way binding (using '@') between the parent scope and the isolate scope. There is also '&' to bind to parent scope expressions. So, these all create local scope properties that are derived from the parent scope.
Note that attributes are used to help set up the binding -- you can't just reference parent scope property names in the object hash, you have to use an attribute. E.g., this won't work if you want to bind to parent property parentProp
in the isolated scope: <div my-directive>
and scope: { localProp: '@parentProp' }
. An attribute must be used to specify each parent property that the directive wants to bind to: <div my-directive the-Parent-Prop=parentProp>
and scope: { localProp: '@theParentProp' }
.
__proto__
references Object.
Isolate scope's $parent references the parent scope, so although it is isolated and doesn't inherit prototypically from the parent scope, it is still a child scope.
<my-directive interpolated="{{parentProp1}}" twowayBinding="parentProp2">
and
scope: { interpolatedProp: '@interpolated', twowayBindingProp: '=twowayBinding' }
scope.someIsolateProp = "I'm isolated"
transclude: true
- the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. The transcluded and the isolated scope (if any) are siblings -- the $parent property of each scope references the same parent scope. When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcluded scope. I'm not aware of any nuances with the transcluded scope.
transclude: true
This fiddle has a showScope()
function that can be used to examine an isolate and transcluded scope. See the instructions in the comments in the fiddle.
There are four types of scopes:
scope: true
scope: {...}
. This one is not prototypal, but '=', '@', and '&' provide a mechanism to access parent scope properties, via attributes.transclude: true
. This one is also normal prototypal scope inheritance, but it is also a sibling of any isolate scope.For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via properties $parent and $$childHead and $$childTail.
Diagrams were generated with graphviz "*.dot" files, which are on github. Tim Caswell's "Learning JavaScript with Object Graphs" was the inspiration for using GraphViz for the diagrams.
rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)
mysqladmin version
OR mysqladmin -V
Had the same issue and got curious about the performance of each solution.
Here's is the %timeit
:
import numpy as np
lst = [['a','b','c'], [1,2,3], ['x','y','z']]
The first numpy-way, transforming the array:
%timeit list(np.array(lst).T[0])
4.9 µs ± 163 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Fully native using list comprehension (as explained by @alecxe):
%timeit [item[0] for item in lst]
379 ns ± 23.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Another native way using zip
(as explained by @dawg):
%timeit list(zip(*lst))[0]
585 ns ± 7.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Second numpy-way. Also explained by @dawg:
%timeit list(np.array(lst)[:,0])
4.95 µs ± 179 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Surprisingly (well, at least for me) the native way using list comprehension is the fastest and about 10x faster than the numpy-way. Running the two numpy-ways without the final list
saves about one µs which is still in the 10x difference.
Note that, when I surrounded each code snippet with a call to len
, to ensure that Generators run till the end, the timing stayed the same.
Here my approach,it may be useful to others.
public static void compareArrays(int[] array1, int[] array2) {
if (array1.length != array2.length)
{
System.out.println("Not Equal");
}
else
{
int temp = 0;
for (int i = 0; i < array2.length; i++) { //Take any one of the array size
temp^ = array1[i] ^ array2[i]; //with help of xor operator to find two array are equal or not
}
if( temp == 0 )
{
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
}
}
On IntelliJ IDEA 2016.1.2
Go to Settings > Editor > General > Appearance then check the Show Line number option
There's no mention of numpy in the question. If by array you mean list, then if you treat a list as a boolean it will yield True if it has items and False if it's empty.
l = []
if l:
print "list has items"
if not l:
print "list is empty"
Plain old Java on plain old Java 7 and no other dependencies demonstrates the difference...
I put file.txt
in c:\temp\
and I put c:\temp\
on the classpath.
There is only one case where there is a difference between the two call.
class J {
public static void main(String[] a) {
// as "absolute"
// ok
System.err.println(J.class.getResourceAsStream("/file.txt") != null);
// pop
System.err.println(J.class.getClassLoader().getResourceAsStream("/file.txt") != null);
// as relative
// ok
System.err.println(J.class.getResourceAsStream("./file.txt") != null);
// ok
System.err.println(J.class.getClassLoader().getResourceAsStream("./file.txt") != null);
// no path
// ok
System.err.println(J.class.getResourceAsStream("file.txt") != null);
// ok
System.err.println(J.class.getClassLoader().getResourceAsStream("file.txt") != null);
}
}
Hey If you want to print selected area or div ,Try This.
<style type="text/css">
@media print
{
body * { visibility: hidden; }
.div2 * { visibility: visible; }
.div2 { position: absolute; top: 40px; left: 30px; }
}
</style>
Hope it helps you
assertTrue
will fail if the second parameter evaluates to false
(in other words, it ensures that the value is true). assertFalse
does the opposite.
assertTrue("This will succeed.", true);
assertTrue("This will fail!", false);
assertFalse("This will succeed.", false);
assertFalse("This will fail!", true);
As with many other things, the best way to become familiar with these methods is to just experiment :-).
For Java 7+ doc you can use this:
BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
Here are all Charsets doc
For example if your file is in CP1252, use this method
Charset.forName("windows-1252");
Here is other canonical names for Java encodings both for IO and NIO doc
If you do not know with exactly encoding you have got in a file, you may use some third-party libs like this tool from Google this which works fairly neat.
With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.
We have three models:
1) Article (belongs to user and category)
2) Category (has many articles)
3) User (has many articles)
1) Article.php
<?php
namespace App\Models;
use Eloquent;
class Article extends Eloquent{
protected $table = 'articles';
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function category()
{
return $this->belongsTo('App\Models\Category');
}
}
2) Category.php
<?php
namespace App\Models;
use Eloquent;
class Category extends Eloquent
{
protected $table = "categories";
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
3) User.php
<?php
namespace App\Models;
use Eloquent;
class User extends Eloquent
{
protected $table = 'users';
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.
For example, if you want to retrieve an article by using the user and category, you would need to write:
$article = \App\Models\Article::with(['user','category'])->first();
and you can use this like so:
//retrieve user name
$article->user->user_name
//retrieve category name
$article->category->category_name
In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:
$categories = \App\Models\Category::with('articles')->get();
$users = \App\Models\Category::with('users')->get();
You can learn more at http://laravel.com/docs/5.0/eloquent
You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.
The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.
It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.
Open Chrome Developer Tools, go to Network tab, make your request (you may need to check "Preserve Log" if the page refreshes). Find the request on the left, right-click, "Copy as cURL".
I propose this solution (which I consider the easiest and memory leaks free) which works perfectly for updating the ViewModel's selected item from the View's selected item.
Please note that changing the selected item from the ViewModel won't update the selected item of the View.
public class TreeViewEx : TreeView
{
public static readonly DependencyProperty SelectedItemExProperty = DependencyProperty.Register("SelectedItemEx", typeof(object), typeof(TreeViewEx), new FrameworkPropertyMetadata(default(object))
{
BindsTwoWayByDefault = true // Required in order to avoid setting the "BindingMode" from the XAML
});
public object SelectedItemEx
{
get => GetValue(SelectedItemExProperty);
set => SetValue(SelectedItemExProperty, value);
}
protected override void OnSelectedItemChanged(RoutedPropertyChangedEventArgs<object> e)
{
SelectedItemEx = e.NewValue;
}
}
XAML usage
<l:TreeViewEx ItemsSource="{Binding Path=Items}" SelectedItemEx="{Binding Path=SelectedItem}" >
The construction is usually used in "existence" checks
if exists(select 1 from customer_table where customer = 'xxx')
or
if exists(select * from customer_table where customer = 'xxx')
Both constructions are equivalent. In the past people said the select * was better because the query governor would then use the best indexed column. This has been proven not true.
i coded this routine that has 3 safety criteria for safer use.
package ch.ethz.idsc.queuey.util;
import java.io.File;
import java.io.IOException;
/** recursive file/directory deletion
*
* safety from erroneous use is enhanced by three criteria
* 1) checking the depth of the directory tree T to be deleted
* against a permitted upper bound "max_depth"
* 2) checking the number of files to be deleted #F
* against a permitted upper bound "max_count"
* 3) if deletion of a file or directory fails, the process aborts */
public final class FileDelete {
/** Example: The command
* FileDelete.of(new File("/user/name/myapp/recordings/log20171024"), 2, 1000);
* deletes given directory with sub directories of depth of at most 2,
* and max number of total files less than 1000. No files are deleted
* if directory tree exceeds 2, or total of files exceed 1000.
*
* abort criteria are described at top of class
*
* @param file
* @param max_depth
* @param max_count
* @return
* @throws Exception if criteria are not met */
public static FileDelete of(File file, int max_depth, int max_count) throws IOException {
return new FileDelete(file, max_depth, max_count);
}
// ---
private final File root;
private final int max_depth;
private int removed = 0;
/** @param root file or a directory. If root is a file, the file will be deleted.
* If root is a directory, the directory tree will be deleted.
* @param max_depth of directory visitor
* @param max_count of files to delete
* @throws IOException */
private FileDelete(final File root, final int max_depth, final int max_count) throws IOException {
this.root = root;
this.max_depth = max_depth;
// ---
final int count = visitRecursively(root, 0, false);
if (count <= max_count) // abort criteria 2)
visitRecursively(root, 0, true);
else
throw new IOException("more files to be deleted than allowed (" + max_count + "<=" + count + ") in " + root);
}
private int visitRecursively(final File file, final int depth, final boolean delete) throws IOException {
if (max_depth < depth) // enforce depth limit, abort criteria 1)
throw new IOException("directory tree exceeds permitted depth");
// ---
int count = 0;
if (file.isDirectory()) // if file is a directory, recur
for (File entry : file.listFiles())
count += visitRecursively(entry, depth + 1, delete);
++count; // count file as visited
if (delete) {
final boolean deleted = file.delete();
if (!deleted) // abort criteria 3)
throw new IOException("cannot delete " + file.getAbsolutePath());
++removed;
}
return count;
}
public int deletedCount() {
return removed;
}
public void printNotification() {
int count = deletedCount();
if (0 < count)
System.out.println("deleted " + count + " file(s) in " + root);
}
}
Find below 3 methods:
Checking page readyState (not reliable):
def page_has_loaded(self):
self.log.info("Checking if {} page is loaded.".format(self.driver.current_url))
page_state = self.driver.execute_script('return document.readyState;')
return page_state == 'complete'
The
wait_for
helper function is good, but unfortunatelyclick_through_to_new_page
is open to the race condition where we manage to execute the script in the old page, before the browser has started processing the click, andpage_has_loaded
just returns true straight away.
id
Comparing new page ids with the old one:
def page_has_loaded_id(self):
self.log.info("Checking if {} page is loaded.".format(self.driver.current_url))
try:
new_page = browser.find_element_by_tag_name('html')
return new_page.id != old_page.id
except NoSuchElementException:
return False
It's possible that comparing ids is not as effective as waiting for stale reference exceptions.
staleness_of
Using staleness_of
method:
@contextlib.contextmanager
def wait_for_page_load(self, timeout=10):
self.log.debug("Waiting for page to load at {}.".format(self.driver.current_url))
old_page = self.find_element_by_tag_name('html')
yield
WebDriverWait(self, timeout).until(staleness_of(old_page))
For more details, check Harry's blog.
Following are the ways
From the code (the way you have mentioned) ->
displayBox.Text += sent + "\r\n";
or
displayBox.Text += sent + Environment.NewLine;
From the UI
a) WPF
Set TextWrapping="Wrap" and AcceptsReturn="True"
Press Enter key to the textbox and new line will be created
b) Winform text box
Set TextBox.MultiLine and TextBox.AcceptsReturn to true
you can use this:
HTML
<input name="userfile" type="file" accept="application/pdf, application/vnd.ms-excel" />
support only .PDF and .XLS files
Try changing the port to 465
mail.smtp.socketFactory.port=465
mail.smtp.port=465
I hope it will be help to you
[_button.titleLabel setFont:[UIFont systemFontOfSize:15]];
good luck
In Java it is the %
operator:
15.17.3. Remainder Operator %
Note that there is also floorMod
in the java.lang.Math
class which will give a different result from %
for arguments with different signs:
here a concatenation solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 10
int main() {
char *text = calloc(1,1), buffer[BUFFERSIZE];
printf("Enter a message: \n");
while( fgets(buffer, BUFFERSIZE , stdin) ) /* break with ^D or ^Z */
{
text = realloc( text, strlen(text)+1+strlen(buffer) );
if( !text ) ... /* error handling */
strcat( text, buffer ); /* note a '\n' is appended here everytime */
printf("%s\n", buffer);
}
printf("\ntext:\n%s",text);
return 0;
}
Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.
WCF = Windows COMMUNICATION Foundation
WPF = Windows PRESENTATION Foundation.
WCF deals with communication (in simple terms - sending and receiving data as well as formatting and serialization involved), WPF deals with presentation (UI)
Click on Wamp icon and open Apache/httpd.conf and search "#LoadModule rewrite_module modules/mod_rewrite.so". Remove # as below and save it
LoadModule rewrite_module modules/mod_rewrite.so
and restart all service.
Maybe I am missing something here, but did you allocate any memory for that PString before you accessed it?
PString * initializeString() {
PString *str;
str = (PString *) malloc(sizeof(PString));
str->length = &length;
return str;
}
See os.path module for some useful functions on pathnames. To check if an existing file is executable, use os.access(path, mode), with the os.X_OK mode.
os.X_OK
Value to include in the mode parameter of access() to determine if path can be executed.
EDIT: The suggested which()
implementations are missing one clue - using os.path.join()
to build full file names.
The following solution works for ASP.NET 5 (vNext) and it uses QueryHelpers class to build a URI with parameters.
public Uri GetUri()
{
var location = _config.Get("http://iberia.com");
Dictionary<string, string> values = GetDictionaryParameters();
var uri = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(location, values);
return new Uri(uri);
}
private Dictionary<string,string> GetDictionaryParameters()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "param1", "value1" },
{ "param2", "value2"},
{ "param3", "value3"}
};
return values;
}
The result URI would have http://iberia.com?param1=value1¶m2=value2¶m3=value3
I built a formatting function based on stuff I stole off SO. I needed a way of "profiling" stuff in log messages, so I needed a fixed length duration message.
public static String GetElapsed(long aInitialTime, long aEndTime, boolean aIncludeMillis)
{
StringBuffer elapsed = new StringBuffer();
Map<String, Long> units = new HashMap<String, Long>();
long milliseconds = aEndTime - aInitialTime;
long seconds = milliseconds / 1000;
long minutes = milliseconds / (60 * 1000);
long hours = milliseconds / (60 * 60 * 1000);
long days = milliseconds / (24 * 60 * 60 * 1000);
units.put("milliseconds", milliseconds);
units.put("seconds", seconds);
units.put("minutes", minutes);
units.put("hours", hours);
units.put("days", days);
if (days > 0)
{
long leftoverHours = hours % 24;
units.put("hours", leftoverHours);
}
if (hours > 0)
{
long leftoeverMinutes = minutes % 60;
units.put("minutes", leftoeverMinutes);
}
if (minutes > 0)
{
long leftoverSeconds = seconds % 60;
units.put("seconds", leftoverSeconds);
}
if (seconds > 0)
{
long leftoverMilliseconds = milliseconds % 1000;
units.put("milliseconds", leftoverMilliseconds);
}
elapsed.append(PrependZeroIfNeeded(units.get("days")) + " days ")
.append(PrependZeroIfNeeded(units.get("hours")) + " hours ")
.append(PrependZeroIfNeeded(units.get("minutes")) + " minutes ")
.append(PrependZeroIfNeeded(units.get("seconds")) + " seconds ")
.append(PrependZeroIfNeeded(units.get("milliseconds")) + " ms");
return elapsed.toString();
}
private static String PrependZeroIfNeeded(long aValue)
{
return aValue < 10 ? "0" + aValue : Long.toString(aValue);
}
And a test class:
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import junit.framework.TestCase;
public class TimeUtilsTest extends TestCase
{
public void testGetElapsed()
{
long start = System.currentTimeMillis();
GregorianCalendar calendar = (GregorianCalendar) Calendar.getInstance();
calendar.setTime(new Date(start));
calendar.add(Calendar.MILLISECOND, 610);
calendar.add(Calendar.SECOND, 35);
calendar.add(Calendar.MINUTE, 5);
calendar.add(Calendar.DAY_OF_YEAR, 5);
long end = calendar.getTimeInMillis();
assertEquals("05 days 00 hours 05 minutes 35 seconds 610 ms", TimeUtils.GetElapsed(start, end, true));
}
}
'use strict'
var fs = require("fs");
/***
* implementation of readFileSync
*/
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
/***
* implementation of readFile
*/
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
For better understanding run the above code and compare the results..
mvn eclipse:eclipse
solved my problem
You may try
$("#addRunner input").each(function(){ ... });
Inputs are no selectors, so you do not need the :
Haven't tested it with your code. Just a fast guess!
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:
angular.module('myApp', ['myApp.directives', 'myApp.services']);
plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview
You're missing a GROUP BY clause:
SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.
None of the above methods worked for me so i'm posting the way i did
DELIMITER $$
CREATE PROCEDURE AddBrand()
BEGIN
DECLARE BrandName varchar(50);
DECLARE CategoryID,BrandID int;
SELECT BrandID = BrandID FROM tblBrand
WHERE BrandName = BrandName;
INSERT INTO tblBrandinCategory (CategoryID, BrandID)
VALUES (CategoryID, BrandID);
END$$
I noticed that every now and then I need to Google fopen all over again, just to build a mental image of what the primary differences between the modes are. So, I thought a diagram will be faster to read next time. Maybe someone else will find that helpful too.
Just use git reset
without the --hard
flag:
git reset HEAD~1
PS: On Unix based systems you can use HEAD^
which is equal to HEAD~1
. On Windows HEAD^
will not work because ^
signals a line continuation. So your command prompt will just ask you More?
.
Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:
Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.
In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.
Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.
It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath()
method. Using that method is in any case alarming.
The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location)
does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.
So, the path to the final storage location can be definied in either of the following ways:
Hardcoded:
File uploads = new File("/path/to/uploads");
Environment variable via SET UPLOAD_LOCATION=/path/to/uploads
:
File uploads = new File(System.getenv("UPLOAD_LOCATION"));
VM argument during server startup via -Dupload.location="/path/to/uploads"
:
File uploads = new File(System.getProperty("upload.location"));
*.properties
file entry as upload.location=/path/to/uploads
:
File uploads = new File(properties.getProperty("upload.location"));
web.xml
<context-param>
with name upload.location
and value /path/to/uploads
:
File uploads = new File(getServletContext().getInitParameter("upload.location"));
If any, use the server-provided location, e.g. in JBoss AS/WildFly:
File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
Either way, you can easily reference and save the file as follows:
File file = new File(uploads, "somefilename.ext");
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath());
}
Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:
File file = File.createTempFile("somefilename-", ".ext", uploads);
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
How to obtain part
in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part
in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?
Note: do not use Part#write()
as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location)
.
You can use Drawable instead of Uri.
ImageView iv=(ImageView)findViewById(R.id.imageView1);
String pathName = "/external/images/media/470939";
Drawable image = Drawable.createFromPath(pathName);
iv.setImageDrawable(image);
This would work.
Extending WebSecurityConfigurerAdapter class and overriding configure() method in your @EnableWebSecurity class would work : Below is sample class
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling();
http.headers().cacheControl();
@Override
public CorsConfiguration getCorsConfiguration(final HttpServletRequest request) {
return new CorsConfiguration().applyPermitDefaultValues();
}
});
}
}
Add the following text to your xml file.
<!--Dummy layout that gain focus -->
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical" >
</LinearLayout>
sudo nginx -t
should test all files and return errors and warnings locations
How's this for a work around (using an actual table)?
table {
border-collapse: collapse;
}
tr.row {
border-bottom: solid white 30px; /* change "white" to your background color */
}
It's not as dynamic, since you have to explicitly set the color of the border (unless there's a way around that too), but this is something I'm experimenting with on a project of my own.
Edit to include comments regarding transparent
:
tr.row {
border-bottom: 30px solid transparent;
}
Think about what
if ((state != 10) || (state != 15) || (state != 19) || (state != 22) || (state != 33) || (state != 39) || (state != 47) || (state != 48) || (state != 49) || (state != 51))
means. ||
means "or." The negation of this is (by DeMorgan's Laws):
state == 10 && state == 15 && state == 19...
In other words, the only way that this could be false if if a state
equals 10, 15, and 19 (and the rest of the numbers in your or statement) at the same time, which is impossible.
Thus, this statement will always be true. State 15 will never equal state 10, for example, so it's always true that state
will either not equal 10 or not equal 15.
Change ||
to &&
.
Also, in most languages, the following:
if (x) {
return true;
}
else {
return false;
}
is not necessary. In this case, the method returns true
exactly when x
is true and false
exactly when x
is false
. You can just do:
return x;
InputStream raw = context.getAssets().open("filename.ext");
Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
I'm learning to code and I found this same problem. I believe the easier way to solve this is literaly overwriting the list like @kerby82 said:
An item in a list in Python can be set to a value using the form
x[n] = v
Where x is the name of the list, n is the index in the array and v is the value you want to set.
In your exemple:
aList = [123, 'xyz', 'zara', 'abc']
aList[0] = 2014
print aList
>>[2014, 'xyz', 'zara', 'abc']
I thought that the best answer was the one above to just do this.
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
but I agree that it is a bit of a pain that the arrow keys and delete button snap cursor to the end of the string ( and because of that it was kicked back to me in testing)
I added in a simple change
$('.numbersOnly').keyup(function () {
if (this.value != this.value.replace(/[^0-9\.]/g, '')) {
this.value = this.value.replace(/[^0-9\.]/g, '');
}
});
this way if there is any button hit that is not going to cause the text to be changed just ignore it. With this you can hit arrows and delete without jumping to the end but it clears out any non numeric text.
Here's a small example to demonstrate this (which only applied to DataFrames, not Series, until Pandas 0.19 where it applies to both):
In [1]: df1 = pd.DataFrame([[1, 2], [3, 4]])
In [2]: df2 = pd.DataFrame([[3, 4], [1, 2]], index=[1, 0])
In [3]: df1 == df2
Exception: Can only compare identically-labeled DataFrame objects
One solution is to sort the index first (Note: some functions require sorted indexes):
In [4]: df2.sort_index(inplace=True)
In [5]: df1 == df2
Out[5]:
0 1
0 True True
1 True True
Note: ==
is also sensitive to the order of columns, so you may have to use sort_index(axis=1)
:
In [11]: df1.sort_index().sort_index(axis=1) == df2.sort_index().sort_index(axis=1)
Out[11]:
0 1
0 True True
1 True True
Note: This can still raise (if the index/columns aren't identically labelled after sorting).
I've written my own little extension for toggleText. It may come in handy.
Fiddle: https://jsfiddle.net/b5u14L5o/
jQuery Extension:
jQuery.fn.extend({
toggleText: function(stateOne, stateTwo) {
return this.each(function() {
stateTwo = stateTwo || '';
$(this).text() !== stateTwo && stateOne ? $(this).text(stateTwo)
: $(this).text(stateOne);
});
}
});
Usage:
...
<button>Unknown</button>
...
//------- BEGIN e.g. 1 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
$(this).toggleText('Show', 'Hide'); // Hide, Show, Hide ... and so on.
});
//------- END e.g. 1 -------
//------- BEGIN e.g. 2 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
$(this).toggleText('Unknown', 'Hide'); // Hide, Unknown, Hide ...
});
//------- END e.g. 2 -------
//------- BEGIN e.g. 3 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
$(this).toggleText(); // Unknown, Unknown, Unknown ...
});
//------- END e.g.3 -------
//------- BEGIN e.g.4 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
$(this).toggleText('Show'); // '', Show, '' ...
});
//------- END e.g.4 -------
Make sure it's not running in the task-manager processes. If so, end the process and then start it from a command prompt as in a previous answer. This worked for me.
This is helped for me.
For select:
$('select_tags').on('change', function() {
alert( $(this).find(":selected").val() );
});
For radio/checkbox:
$('radio_tags').on('change', function() {
alert( $(this).find(":checked").val() );
});
I just made my life simple:
CREATE VIEW another_table AS SELECT * FROM another_database.another_table;
hope it is helpful... cheers...
The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.
It seems to be a known issue. You can instruct m2e to ignore this.
Option 1: pom.xml
Add the following inside your <build/>
tag:
<pluginManagement>
<plugins>
<!-- Ignore/Execute plugin execution -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<!-- copy-dependency plugin -->
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<versionRange>[1.0.0,)</versionRange>
<goals>
<goal>copy-dependencies</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins></pluginManagement>
You will need to do Maven... -> Update Project Configuration on your project after this.
Read more: http://wiki.eclipse.org/M2E_plugin_execution_not_covered#m2e_maven_plugin_coverage_status
Option 2: Global Eclipse Override
To avoid changing your POM files, the ignore override can be applied to the whole workspace via Eclipse settings.
Save this file somewhere on the disk: https://gist.github.com/maksimov/8906462
In Eclipse/Preferences/Maven/Lifecycle Mappings
browse to this file and click OK:
Make a virtual enviroment using python3
virtualenv env_name --python="python3"
and run the following command
pip3 install opencv-python
document.location
is an object, while document.location.href
is a string. But the former has a toString
method, so you can read from it as if it was a string and get the same value as document.location.href
.
In some browsers - most modern ones, I think - you can also assign to document.location
as if it were a string. According to the Mozilla documentation however, it is better to use window.location
for this purpose as document.location
was originally read-only and so may not be as widely supported.
This code is for full screen landscape video
AndroidManifext.xml (Setting the orientation)
<activity
android:name=".Video1"
android:screenOrientation="landscape" />
Video1.java Code :
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.VideoView;
public class Video1 extends AppCompatActivity {
private VideoView videoView;
private MediaController mediaController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video1);
videoView = findViewById(R.id.videoView);
String fullScreen = getIntent().getStringExtra("fullScreenInd");
if("y".equals(fullScreen)){
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
}
Uri videoUri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.YOUR_VIDEO_NAME);
videoView.setVideoURI(videoUri);
mediaController = new FullScreenMediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.start();
}
}
FullScreenMediaControler.java Code :
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.MediaController;
public class FullScreenMediaController extends MediaController {
private ImageButton fullScreen;
private String isFullScreen;
public FullScreenMediaController(Context context) {
super(context);
}
@Override
public void setAnchorView(View view) {
super.setAnchorView(view);
//image button for full screen to be added to media controller
fullScreen = new ImageButton (super.getContext());
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
params.rightMargin = 80;
addView(fullScreen, params);
//fullscreen indicator from intent
isFullScreen = ((Activity)getContext()).getIntent().
getStringExtra("fullScreenInd");
if("y".equals(isFullScreen)){
fullScreen.setImageResource(R.drawable.ic_fullscreen_exit);
}else{
fullScreen.setImageResource(R.drawable.ic_fullscreen);
}
//add listener to image button to handle full screen and exit full screen events
fullScreen.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(),Video1.class);
if("y".equals(isFullScreen)){
intent.putExtra("fullScreenInd", "");
}else{
intent.putExtra("fullScreenInd", "y");
}
((Activity)getContext()).startActivity(intent);
}
});
}
}
MAC OS X solution :
$ sudo chmod -R 755 /usr/local/share/zsh
$ sudo chown -R root:staff /usr/local/share/zsh
Also "user:staff = default root user on OSX.
I have wondered the same thing. Basically it appears that the html spec has different content types for html and form data. Json only has a single content type.
According to the spec, a POST of json data should have the content-type:
application/json
Relevant portion of the HTML spec
6.7 Content types (MIME types)
...
Examples of content types include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic".17.13.4 Form content types
...
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows
Relevant portion of the JSON spec
- IANA Considerations
The MIME media type for JSON text is application/json.
You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.
Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.
If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.
<script type="text/javascript>
var foo = <?php echo json_encode($somePhpVar); ?>
</script>
Made a couple of additions to the above answers so that you get returned a type instead of string value.
I figured that this is primarily going to be used for UI adjustments so I didn't think it relevant to include all the sub models i.e. iPhone 5s but this could be easily extended by adding in model tests to the isDevice Array
Tested working in Swift 3.1 Xcode 8.3.2 with physical and simulator devices
Implementation:
UIDevice.whichDevice()
public enum SVNDevice {
case isiPhone4, isIphone5, isIphone6or7, isIphone6por7p, isIphone, isIpad, isIpadPro
}
extension UIDevice {
class func whichDevice() -> SVNDevice? {
let isDevice = { (comparision: Array<(Bool, SVNDevice)>) -> SVNDevice? in
var device: SVNDevice?
comparision.forEach({
device = $0.0 ? $0.1 : device
})
return device
}
return isDevice([
(UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0, SVNDevice.isiPhone4),
(UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0, SVNDevice.isIphone5),
(UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0, SVNDevice.isIphone6or7),
(UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0, SVNDevice.isIphone6por7p),
(UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0, SVNDevice.isIpad),
(UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0, SVNDevice.isIpadPro)])
}
}
private struct ScreenSize {
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
I've created a framework called SVNBootstaper which includes this and some other helper protocols, it's public and available through Carthage.
To get or set an attribute of an HTML element, you can use the element.attr()
function in jQuery.
To get the href attribute, use the following code:
var a_href = $('selector').attr('href');
To set the href attribute, use the following code:
$('selector').attr('href','http://example.com');
In both cases, please use the appropriate selector. If you have set the class for the anchor element, use '.class-name'
and if you have set the id for the anchor element, use '#element-id'
.
I've created a working CodePen example demonstrating how to do this.
Relevant HTML:
<section ng-app="app" ng-controller="MainCtrl">
<a href="#" ng-click="doSomething('#/path/{{obj.val1}}/{{obj.val2}}')">Click Me</a><br>
debug: {{debug.val}}
</section>
Relevant javascript:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.obj = {
val1: 'hello',
val2: 'world'
};
$scope.debug = {
val: ''
};
$scope.doSomething = function(input) {
$scope.debug.val = input;
};
});
mysql -u <user> -p -e "select * from schema.table"
Your method showFile() declares that it can throw an IOException. Since this is a checked exception, any call to showFile() method must handle the exception somehow. One option is to wrap the call to showFile() in a try-catch block.
try {
showFile();
}
catch(IOException e) {
// Code to handle an IOException here
}
The php_flag and php_value inside a .htaccess file are technically correct - but for PHP installed as an Apache module only. On a shared host you'll almost never find such a setup; PHP is run as a CGI instead, for reasons related to security (keeping your server neighbours out of your files) and the way phpsuexec runs scripts as 'you' instead of the apache user.
Apache is thus correct giving you a server error: it doesn't know about the meaning of php_flag unless the PHP module is loaded. A CGI binary is to Apache an external program instead, and you can't configure it from within Apache.
Now for the good news: you can set up per-directory configuration putting there a file named 'php.ini' and setting there your instructions using the same syntax as in the system's main php.ini. The PHP manual lists all settable directives: you can set those marked with PHP_INI_PERDIR or PHP_INI_ALL, while only the system administrator can set those marked PHP_INI_SYSTEM in the server-wide php.ini.
Note that such php.ini directives are not inherited by subdirectories, you'll have to give them their own php.ini.
=RIGHT(A1)
is quite sufficient (where the string is contained in A1).
Similar in nature to LEFT, Excel's RIGHT function extracts a substring from a string starting from the right-most character:
SYNTAX
RIGHT( text, [number_of_characters] )
Parameters or Arguments
text
The string that you wish to extract from.
number_of_characters
Optional. It indicates the number of characters that you wish to extract starting from the right-most character. If this parameter is omitted, only 1 character is returned.
Applies To
Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Since number_of_characters is optional and defaults to 1
it is not required in this case.
However, there have been many issues with trailing spaces and if this is a risk for the last visible character (in general):
=RIGHT(TRIM(A1))
might be preferred.
You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.
Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to
C:\apache-tomcat-7.0.8\webapps
, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the.metadata
folder, and search for "wtpwebapps". You should find something likeyour-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
(or../tmp1/wtpwebapps
if you already had another server registered in Eclipse). Go to thewtpwebapps
folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reloadhttp://localhost/
to see the Tomcat welcome page.
Source: HTTP Status 404 error in tomcat
seems like you are hit by integer arithmetic: in some languages (int)/(int) will always be evaluated as integer arithmetic. in order to force floating-point arithmetic, make sure that at least one of the operands is non-integer:
double roundOff = Math.round(a*100)/100.f;
And most important!!!
When you change a namespace in your code, also make sure you change it in web.config!
Use any. They are almost the same.
As usual, there are pros and cons.
Use std::reverse_iterator
:
operator>()
std::greater<int>()
Use std::greater
when:
As for performance, both methods are equally efficient. I tried the following benchmark:
#include <algorithm>
#include <chrono>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std::chrono;
/* 64 Megabytes. */
#define VECTOR_SIZE (((1 << 20) * 64) / sizeof(int))
/* Number of elements to sort. */
#define SORT_SIZE 100000
int main(int argc, char **argv) {
std::vector<int> vec;
vec.resize(VECTOR_SIZE);
/* We generate more data here, so the first SORT_SIZE elements are evicted
from the cache. */
std::ifstream urandom("/dev/urandom", std::ios::in | std::ifstream::binary);
urandom.read((char*)vec.data(), vec.size() * sizeof(int));
urandom.close();
auto start = steady_clock::now();
#if USE_REVERSE_ITER
auto it_rbegin = vec.rend() - SORT_SIZE;
std::sort(it_rbegin, vec.rend());
#else
auto it_end = vec.begin() + SORT_SIZE;
std::sort(vec.begin(), it_end, std::greater<int>());
#endif
auto stop = steady_clock::now();
std::cout << "Sorting time: "
<< duration_cast<microseconds>(stop - start).count()
<< "us" << std::endl;
return 0;
}
With this command line:
g++ -g -DUSE_REVERSE_ITER=0 -std=c++11 -O3 main.cpp \
&& valgrind --cachegrind-out-file=cachegrind.out --tool=cachegrind ./a.out \
&& cg_annotate cachegrind.out
g++ -g -DUSE_REVERSE_ITER=1 -std=c++11 -O3 main.cpp \
&& valgrind --cachegrind-out-file=cachegrind.out --tool=cachegrind ./a.out \
&& cg_annotate cachegrind.out
std::greater
demo
std::reverse_iterator
demo
Timings are same. Valgrind reports the same number of cache misses.
If it's in a class, you can use getattr:
class MyClass(object):
def install(self):
print "In install"
method_name = 'install' # set by the command line options
my_cls = MyClass()
method = None
try:
method = getattr(my_cls, method_name)
except AttributeError:
raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))
method()
or if it's a function:
def install():
print "In install"
method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
raise NotImplementedError("Method %s not implemented" % method_name)
method()
You cannot write data's to asset/Raw folder, since it is packed(.apk) and not expandable in size.
If your application need to download dependency files from server, you can go for APK Expansion Files provided by android (http://developer.android.com/guide/market/expansion-files.html).
Deleting the eclipse folder is equivalent to uninstalling it. In fact, if you don't want to tamper with the existing installation you can create another instance of eclipse and run from the new location.
Try adding this line to the xml parent layout
android:animateLayoutChanges="true"
Your layout will look like this
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:longClickable="false"
android:orientation="vertical"
android:weightSum="16">
.......other code here
</LinearLayout>
in the latest packages you can also use
vp.getCurrentItem()
or
vp is the viewPager ,
pageListener = new PageListener();
vp.setOnPageChangeListener(pageListener);
you have to put a page change listener for your viewPager. There is no method on viewPager to get the current page.
private int currentPage;
private static class PageListener extends SimpleOnPageChangeListener{
public void onPageSelected(int position) {
Log.i(TAG, "page selected " + position);
currentPage = position;
}
}
Python's standard library has json
and urllib2
modules.
import json
import urllib2
data = json.load(urllib2.urlopen('http://someurl/path/to/json'))
You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.
~function () {
function Smooth () {
this.$container = document.querySelector('.levit-container');
this.$placeholder = document.createElement('div');
}
Smooth.prototype.init = function () {
var instance = this;
setContainer.call(instance);
setPlaceholder.call(instance);
bindEvents.call(instance);
}
function bindEvents () {
window.addEventListener('scroll', handleScroll.bind(this), false);
}
function setContainer () {
var style = this.$container.style;
style.position = 'fixed';
style.width = '100%';
style.top = '0';
style.left = '0';
style.transition = '0.5s ease-out';
}
function setPlaceholder () {
var instance = this,
$container = instance.$container,
$placeholder = instance.$placeholder;
$placeholder.setAttribute('class', 'levit-placeholder');
$placeholder.style.height = $container.offsetHeight + 'px';
document.body.insertBefore($placeholder, $container);
}
function handleScroll () {
this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
}
var smooth = new Smooth();
smooth.init();
}();
set the height to 200
Set the Font
to a large variant (150+ px). As already mentioned, control the width using columns, and use a layout manager (or constraint) that will respect the preferred width & height.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class BigTextField {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new FlowLayout(5));
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
// Create big text fields & add them to the GUI
String s = "Hello!";
JTextField tf1 = new JTextField(s, 1);
Font bigFont = tf1.getFont().deriveFont(Font.PLAIN, 150f);
tf1.setFont(bigFont);
gui.add(tf1);
JTextField tf2 = new JTextField(s, 2);
tf2.setFont(bigFont);
gui.add(tf2);
JTextField tf3 = new JTextField(s, 3);
tf3.setFont(bigFont);
gui.add(tf3);
gui.setBackground(Color.WHITE);
JFrame f = new JFrame("Big Text Fields");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
I had the same problem and I solved by using the postcast server. You can install it locally and use it.
This has already been answered for Java, here's the C# answer:
"Integer" is not a valid type name in C# and "int" is just an alias for System.Int32. Also, unlike in Java (or C++) there aren't any special primitive types in C#, every instance of a type in C# (including int) is an object. Here's some demonstrative code:
void DoStuff()
{
System.Console.WriteLine( SomeMethod((int)5) );
System.Console.WriteLine( GetTypeName<int>() );
}
string SomeMethod(object someParameter)
{
return string.Format("Some text {0}", someParameter.ToString());
}
string GetTypeName<T>()
{
return (typeof (T)).FullName;
}
This can be implemented immutably and with a single traversal by folding through the collection as follows.
val map = c.foldLeft(Map[P, T]()) { (m, t) => m + (t.getP -> t) }
The solution works because adding to an immutable Map returns a new immutable Map with the additional entry and this value serves as the accumulator through the fold operation.
The tradeoff here is the simplicity of the code versus its efficiency. So, for large collections, this approach may be more suitable than using 2 traversal implementations such as applying map
and toMap
.
.h
) not for source files ( i.e., .cpp
). LinearNode.h:
#ifndef LINEARNODE_H
#define LINEARNODE_H
class LinearNode
{
// .....
};
#endif
LinearNode.cpp:
#include "LinearNode.h"
#include <iostream>
using namespace std;
// And now the definitions
LinkedList.h:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
class LinearNode; // Forward Declaration
class LinkedList
{
// ...
};
#endif
LinkedList.cpp
#include "LinearNode.h"
#include "LinkedList.h"
#include <iostream>
using namespace std;
// Definitions
test.cpp is source file is fine. Note that header files are never compiled. Assuming all the files are in a single folder -
g++ LinearNode.cpp LinkedList.cpp test.cpp -o exe.out
As far as i know, writing multiple matches is logical AND operation; so what your rule means is if the destination port is "59100" AND "3000" then reject connection with tcp-reset; Workaround is using -mport option. Look out for the man page.
pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.
Example code:
a = pd.Series([1,2,3,4], index=[7,2,8,9])
b = pd.Series([5,6,7,8], index=[7,2,8,9])
data = pd.DataFrame({'a': a,'b':b, 'idx_col':a.index})
Pandas allows you to create a DataFrame
from a dict
with Series
as the values and the column names as the keys. When it finds a Series
as a value, it uses the Series
index as part of the DataFrame
index. This data alignment is one of the main perks of Pandas. Consequently, unless you have other needs, the freshly created DataFrame
has duplicated value. In the above example, data['idx_col']
has the same data as data.index
.
For Mi or Xiaomi Device
1) Setting
2) Additional Setting
3) Developer option
4) Install via USB: Toggle On
It is working fine for me.
Note: Not working then try following options also
1) Sign to MI account (Not applicable to all devices)
2) Also Disable Turn on MIUI optimization: Setting -> Additional Setting -> Developer Option, near bottom we will get this option.
3) Developer option must be enabled and Link for enabling developer option: Description here
Still not working?
-> signed out from Mi Account and then created new account and enable USB Debugging.
Thanks
SELECT CONVERT( VARCHAR(24), GETDATE(), 113)
UPDATE
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))
On my system (Windows 8.1), Sublime 2 shows default font "Consolas". You can find yours by following this procedure:
view.settings().get('font_face')
You will find your default font.
Enabling Developer mode by tapping on Build Number 7 times worked for me.
You were setting BCC but then overwriting the variable with the FROM
$to = "[email protected]";
$subject .= "".$emailSubject."";
$headers .= "Bcc: ".$emailList."\r\n";
$headers .= "From: [email protected]\r\n" .
"X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';
if (mail($to, $subject, $message, $headers)) {
$sent = "Your email was sent!";
} else {
$sent = ("Error sending email.");
}
Many good solutions have been provided already. However, if he text is provided in a very simple comma delimited format or similar, and speed is of importance, then I have for you a solution with a TABLE
function (in PL/SQL). I have also provided a rundown of some other solutions.
Please see more on the Blog Entry on Parsing a CSV into multiple columns.
Here's another way using *args
(and also optionally), **kwargs
:
def a(x, y):
print x, y
def b(other, function, *args, **kwargs):
function(*args, **kwargs)
print other
b('world', a, 'hello', 'dude')
Output
hello dude
world
Note that function
, *args
, **kwargs
have to be in that order and have to be the last arguments to the function calling the function.
If it is exactly null
(as opposed to not set):
db.states.find({"cities.name": null})
(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).
If it's the case that the property is not set:
db.states.find({"cities.name": {"$exists": false}})
I've tested the above with a collection created with these two inserts:
db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})
The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or
query:
db.states.find({"$or": [
{"cities.name": null},
{"cities.name": {"$exists": false}}
]})
They're faster; unless you're loading the entire flat file into memory, a database will allow faster access in almost all cases.
They're safer; databases are easier to safely backup; they have mechanisms to check for file corruption, which flat files do not. Once corruption in your flat file migrates to your backups, you're done, and you might not even know it yet.
They have more features; databases can allow many users to read/write at the same time.
They're much less complex to work with, once they're setup.
You can pass in any CMake variable on the command line, or edit cached variables using ccmake/cmake-gui. On the command line,
cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr . && make all install
Would configure the project, build all targets and install to the /usr prefix. The type (PATH) is not strictly necessary, but would cause the Qt based cmake-gui to present the directory chooser dialog.
Some minor additions as comments make it clear that providing a simple equivalence is not enough for some. Best practice would be to use an external build directory, i.e. not the source directly. Also to use more generic CMake syntax abstracting the generator.
mkdir build && cd build && cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr .. && cmake --build . --target install --config Release
You can see it gets quite a bit longer, and isn't directly equivalent anymore, but is closer to best practices in a fairly concise form... The --config is only used by multi-configuration generators (i.e. MSVC), ignored by others.
Easiest way:
Check in your logcat window - TOP RIGHT corner PAUSE button || (Pause receiving new logcat messages)
Few clicks + eventually restart eclipse (usually works in my case)
In some browsers, fonts are set explicit for textareas and inputs, so they don’t inherit the fonts from higher elements. So, I think you need to apply the font styles for each textarea and input in the document as well (not just the body).
One idea might be to add clases to the body, then use CSS to style the document accordingly.
Works only on Windows:
import winreg
import itertools
def serial_ports() -> list:
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
ports = []
for i in itertools.count():
try:
ports.append(winreg.EnumValue(key, i)[1])
except EnvironmentError:
break
return ports
if __name__ == "__main__":
ports = serial_ports()
I would do something like this (generates all the selects you need). You can later on feed them to sqlplus:
echo "select table_name from user_tables;" | sqlplus -S user/pwd | grep -v "^--" | grep -v "TABLE_NAME" | grep "^[A-Z]" | while read sw;
do echo "desc $sw" | sqlplus -S user/pwd | grep -v "\-\-\-\-\-\-" | awk -F' ' '{print $1}' | while read nw;
do echo "select * from $sw where $nw='val'";
done;
done;
It yields:
select * from TBL1 where DESCRIPTION='val'
select * from TBL1 where ='val'
select * from TBL2 where Name='val'
select * from TBL2 where LNG_ID='val'
And what it does is - for each table_name
from user_tables
get each field (from desc) and create a select * from table where field equals 'val'.
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
function my_get_tags_sitemap(){
if ( !function_exists('wp_tag_cloud') || get_option('cb2_noposttags')) return;
$unlinkTags = get_option('cb2_unlinkTags');
echo '<div class="tags"><h2>Tags</h2>';
$ret = []; // here you need to add array which you call inside implode function
if($unlinkTags)
{
$tags = get_tags();
foreach ($tags as $tag){
$ret[]= $tag->name;
}
//ERROR OCCURS HERE
echo implode(', ', $ret);
}
else
{
wp_tag_cloud('separator=, &smallest=11&largest=11');
}
echo '</div>';
}
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
Based on your application type/size/load/no. of users ..etc - u can keep following as your production properties
spring.datasource.tomcat.initial-size=50
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=300
spring.datasource.tomcat.max-idle=150
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true
I used to encounter this same exact issue in the past with Google Admob SDK. Most recently, this happened when trying to add Validic libraries. I tried the same old good trick this time around as well and it worked in a jiffy.
1) Remove the frameworks, if already added.
2) Locate the framework in Finder and Drag & Drop them directly into the Project Navigator pane under your project tree.
3) Build the project and Whooo!
Not sure what makes the difference, but adding the frameworks by the official way of going to the section "Linked Framework & Libraries" under project settings page (TARGET) and linking from there does not work for me. Hope this helps.
Add this to your css:
html, body {
height:100%;
}
If you say height:100%, you mean '100% of the parent element'. If the parent element has no specified height, nothing will happen. You only set 100% on body, but you also need to add it to html.
Look at SignalR Tests for the feature.
Test "SendToUser" takes automatically the user identity passed by using a regular owin authentication library.
The scenario is you have a user who has connected from multiple devices/browsers and you want to push a message to all his active connections.
Accepted answer doesn't work for me, but this does. Ensure script in the location (c:\temp_ below on each remote server. servers.txt contains a list of IP addresses (one per line).
psexec @servers.txt -u <username> cmd /c "powershell -noninteractive -file C:\temp\script.ps1"
Guest additions are not available for Mac OS X. You can get features like clipboard sync and shared folders by using VNC and SMB. Here's my answer on a similar question.
Setting line-height: 0px;
fixed it for me in Chrome
A duplicate post of sorts, but check out my solution for comparing collections. It's pretty simple:
This will perform an equality comparison regardless of order:
var list1 = new[] { "Bill", "Bob", "Sally" };
var list2 = new[] { "Bob", "Bill", "Sally" };
bool isequal = list1.Compare(list2).IsSame;
This will check to see if items were added / removed:
var list1 = new[] { "Billy", "Bob" };
var list2 = new[] { "Bob", "Sally" };
var diff = list1.Compare(list2);
var onlyinlist1 = diff.Removed; //Billy
var onlyinlist2 = diff.Added; //Sally
var inbothlists = diff.Equal; //Bob
This will see what items in the dictionary changed:
var original = new Dictionary<int, string>() { { 1, "a" }, { 2, "b" } };
var changed = new Dictionary<int, string>() { { 1, "aaa" }, { 2, "b" } };
var diff = original.Compare(changed, (x, y) => x.Value == y.Value, (x, y) => x.Value == y.Value);
foreach (var item in diff.Different)
Console.Write("{0} changed to {1}", item.Key.Value, item.Value.Value);
//Will output: a changed to aaa
Original post here.
little late to the answer but seems this will add value. Looking at the error - it seems to occur in CI/CD pipeline.
Just running "dotnet build" will be sufficient enough.
dotnet build
dotnet build runs the "restore" by default.
@media print { a[href]:after { content: none !important; } }
I really like to sort the keys in one liner code:
print "$_ => $my_hash{$_}\n" for (sort keys %my_hash);
Google's own browser offers such a comprehensive solution to this problem that it warrants it's own class:
This might help, I used to fi my files like this: http://security102.blogspot.ru/2010/04/findreplace-of-nul-objects-in-notepad.html
Basically you need to replace \x00 characters with regular expressions
Please, be aware, that this error appears when your server is under attack. Just found that redis fails to write to '/etc/cron.d/web' where after correcting of permissions, new file consisting of mining algorithm with some hiding options was added.
There is no difference if we look on effect - value will be the same. However there is something more...
Solution 3:
function doSomething() {_x000D_
console.log( theId.value );_x000D_
}
_x000D_
<input id="theId" value="test" onclick="doSomething()" />
_x000D_
if DOM element has id then you can use it in js directly
You can solve your issue by using the 'contains' function within your Xpath query, as below:
var allElementsWithClassFloat =
_doc.DocumentNode.SelectNodes("//*[contains(@class,'float')]")
To reuse this in a function do something similar to the following:
string classToFind = "float";
var allElementsWithClassFloat =
_doc.DocumentNode.SelectNodes(string.Format("//*[contains(@class,'{0}')]", classToFind));
When a VS2013 C++ project is opened in VS2015, and there are warnings about "The build tools for v120... cannot be found", I simply need to edit the .vcxproj file and change <PlatformToolset>v120</PlatformToolset>
to <PlatformToolset>v140</PlatformToolset>
, and close and re-open the solution.
In both: Anaconda prompt and the old cmd.exe, you change your directory by first changing to the drive you want, by simply writing its name followed by a ':
', exe: F:
, which will take you to the drive named 'F' on your machine. Then using the command cd
to navigate your way inside that drive as you normally would.
Use this code on xml . i hope it will be work
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<stroke android:width="3dp"
android:color="#4799E8"/>
<corners android:radius="5dp" />
<gradient
android:startColor="#C8C8C8"
android:endColor="#FFFFFF"
android:type="linear"
android:angle="270"/>
</shape>
Try this
body {
max-width: max-content;
margin: auto;
}
Well, I had great trouble figuring out the non-blocking commands... But finally, I managed to rework the "Cookbook/Matplotlib/Animations - Animating selected plot elements" example, so it works with threads (and passes data between threads either via global variables, or through a multiprocess Pipe
) on Python 2.6.5 on Ubuntu 10.04.
The script can be found here: Animating_selected_plot_elements-thread.py - otherwise pasted below (with fewer comments) for reference:
import sys
import gtk, gobject
import matplotlib
matplotlib.use('GTKAgg')
import pylab as p
import numpy as nx
import time
import threading
ax = p.subplot(111)
canvas = ax.figure.canvas
# for profiling
tstart = time.time()
# create the initial line
x = nx.arange(0,2*nx.pi,0.01)
line, = ax.plot(x, nx.sin(x), animated=True)
# save the clean slate background -- everything but the animated line
# is drawn and saved in the pixel buffer background
background = canvas.copy_from_bbox(ax.bbox)
# just a plain global var to pass data (from main, to plot update thread)
global mypass
# http://docs.python.org/library/multiprocessing.html#pipes-and-queues
from multiprocessing import Pipe
global pipe1main, pipe1upd
pipe1main, pipe1upd = Pipe()
# the kind of processing we might want to do in a main() function,
# will now be done in a "main thread" - so it can run in
# parallel with gobject.idle_add(update_line)
def threadMainTest():
global mypass
global runthread
global pipe1main
print "tt"
interncount = 1
while runthread:
mypass += 1
if mypass > 100: # start "speeding up" animation, only after 100 counts have passed
interncount *= 1.03
pipe1main.send(interncount)
time.sleep(0.01)
return
# main plot / GUI update
def update_line(*args):
global mypass
global t0
global runthread
global pipe1upd
if not runthread:
return False
if pipe1upd.poll(): # check first if there is anything to receive
myinterncount = pipe1upd.recv()
update_line.cnt = mypass
# restore the clean slate background
canvas.restore_region(background)
# update the data
line.set_ydata(nx.sin(x+(update_line.cnt+myinterncount)/10.0))
# just draw the animated artist
ax.draw_artist(line)
# just redraw the axes rectangle
canvas.blit(ax.bbox)
if update_line.cnt>=500:
# print the timing info and quit
print 'FPS:' , update_line.cnt/(time.time()-tstart)
runthread=0
t0.join(1)
print "exiting"
sys.exit(0)
return True
global runthread
update_line.cnt = 0
mypass = 0
runthread=1
gobject.idle_add(update_line)
global t0
t0 = threading.Thread(target=threadMainTest)
t0.start()
# start the graphics update thread
p.show()
print "out" # will never print - show() blocks indefinitely!
Hope this helps someone,
Cheers!
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
...
}
0755
= User:rwx
Group:r-x
World:r-x
0750
= User:rwx
Group:r-x
World:---
(i.e. World: no access)
r = read
w = write
x = execute (traverse for directories)
Are you missing a function declaration?
void ac_search(uint num_patterns, uint pattern_length, const char *patterns,
uint num_records, uint record_length, const char *records, int *matches, Node* trie);
Add it just before your implementation of ac_benchmark_search.
See it might be worked -------
UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space
UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline
UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab
Thanks Subroto
Following steps can resolve the issue .....
Since not all of my clients use authenticated SMTP accounts, I resorted to using the SMTP account only if app key values are supplied in web.config file.
Here is the VB code:
sSMTPUser = ConfigurationManager.AppSettings("SMTPUser")
sSMTPPassword = ConfigurationManager.AppSettings("SMTPPassword")
If sSMTPUser.Trim.Length > 0 AndAlso sSMTPPassword.Trim.Length > 0 Then
NetClient.Credentials = New System.Net.NetworkCredential(sSMTPUser, sSMTPPassword)
sUsingCredentialMesg = "(Using Authenticated Account) " 'used for logging purposes
End If
NetClient.Send(Message)
<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>
Just use the classic ==
operator:
>>> [0,1,2] == [0,1,2]
True
>>> [0,1,2] == [0,2,1]
False
>>> [0,1] == [0,1,2]
False
Lists are equal if elements at the same index are equal. Ordering is taken into account then.
You could use a Bat to Exe
converter from here:
This will convert your batch file to an executable, then you can set the icon for the converted file.
The think best way to to it is using
Intent i = new Intent(this.myActivity, SecondActivity.class);
startActivityForResult(i, 1);
Requiring 900 weight is not a weirdness but a intentional restriction added by FontAwesome (since they share the same unicode but just different font-weight) so that you are not hacking your way into using the 'solid' and 'light' icons, most of which are available only in the paid 'Pro' version.
It seems that you have a bunch of describe
s that never have end
s keywords, starting with describe "when email format is invalid" do
until describe "when email address is already taken" do
Put an end on those guys and you're probably done =)