The only difference between files that causing the issue is the 8th byte of file
CA FE BA BE 00 00 00 33 - Java 7
vs.
CA FE BA BE 00 00 00 32 - Java 6
Setting -XX:-UseSplitVerifier
resolves the issue. However, the cause of this issue is https://bugs.eclipse.org/bugs/show_bug.cgi?id=339388
check it in mdpi device.. If the ad displays correctly, the error should be in "px" to "dip" conversion..
If its a maven project, add the below dependency in your pom file
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.4</version>
</dependency>
One thing you might try is using -Xverify:all
which will verify bytecode on load and sometimes gives helpful error messages if the bytecode is invalid.
USE:
>>> a[[0,1,3]][:,[0,2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
OR:
>>> a[[0,1,3],::2]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
Use the function GetSize
from the module cv
with your image as parameter. It returns width, height as a tuple with 2 elements:
width, height = cv.GetSize(src)
As Peter and Amro illustrate, you have to convert numeric values to formatted strings first in order to display them or concatenate them with other character strings. You can do this using the functions FPRINTF, SPRINTF, NUM2STR, and INT2STR.
With respect to getting ans = 3
as an output, it is probably because you are not assigning the output from answer
to a variable. If you want to get all of the output values, you will have to call answer
in the following way:
[out1,out2,out3] = answer(1,2);
This will place the value d
in out1
, the value e
in out2
, and the value f
in out3
. When you do the following:
answer(1,2)
MATLAB will automatically assign the first output d
(which has the value 3 in this case) to the default workspace variable ans
.
With respect to suggesting a good resource for learning MATLAB, you shouldn't underestimate the value of the MATLAB documentation. I've learned most of what I know on my own using it. You can access it online, or within your copy of MATLAB using the functions DOC, HELP, or HELPWIN.
the_input = raw_input("Enter input: ")
And that's it.
Moreover, if you want to make a list of inputs, you can do something like:
a = []
for x in xrange(1,10):
a.append(raw_input("Enter Data: "))
In that case, you'll be asked for data 10 times to store 9 items in a list.
Output:
Enter data: 2
Enter data: 3
Enter data: 4
Enter data: 5
Enter data: 7
Enter data: 3
Enter data: 8
Enter data: 22
Enter data: 5
>>> a
['2', '3', '4', '5', '7', '3', '8', '22', '5']
You can search that list the fundamental way with something like (after making that list):
if '2' in a:
print "Found"
else: print "Not found."
You can replace '2' with "raw_input()" like this:
if raw_input("Search for: ") in a:
print "Found"
else:
print "Not found"
If you want to take the input from a file you feed through commandline (which is normally what you need when doing code problems for competitions, like Google Code Jam or the ACM/IBM ICPC):
example.py
while(True):
line = raw_input()
print "input data: %s" % line
In command line interface:
example.py < input.txt
Hope that helps.
Also note, if you have explicitly granted:
CONNECT ON DATABASE xxx TO GROUP
,
you will need to revoke this separately from DROP OWNED BY, using:
REVOKE CONNECT ON DATABASE xxx FROM GROUP
It's a reserved keyword (like return, filter, function, break).
Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:
But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.
Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:
PS C:\> function ex{exit}
PS C:\> new-alias ^D ex
No, you do not need to check whether you’re already on the main thread. By dispatching the block to the main queue, you’re just scheduling the block to be executed serially on the main thread, which happens when the corresponding run loop is run.
If you already are on the main thread, the behaviour is the same: the block is scheduled, and executed when the run loop of the main thread is run.
I just added the environment variable Boost_INCLUDE_DIR or add it to the cmake command -DBoost_INCLUDE_DIR and point to the include folder.
One would use @classmethod
when he/she would want to change the behaviour of the method based on which subclass is calling the method. remember we have a reference to the calling class in a class method.
While using static you would want the behaviour to remain unchanged across subclasses
Example:
class Hero:
@staticmethod
def say_hello():
print("Helllo...")
@classmethod
def say_class_hello(cls):
if(cls.__name__=="HeroSon"):
print("Hi Kido")
elif(cls.__name__=="HeroDaughter"):
print("Hi Princess")
class HeroSon(Hero):
def say_son_hello(self):
print("test hello")
class HeroDaughter(Hero):
def say_daughter_hello(self):
print("test hello daughter")
testson = HeroSon()
testson.say_class_hello() #Output: "Hi Kido"
testson.say_hello() #Outputs: "Helllo..."
testdaughter = HeroDaughter()
testdaughter.say_class_hello() #Outputs: "Hi Princess"
testdaughter.say_hello() #Outputs: "Helllo..."
just pass the columnName as parameter of YEAR
SELECT YEAR(ASOFDATE) from PSASOFDATE;
another is to use DATE_FORMAT
SELECT DATE_FORMAT(ASOFDATE, '%Y') from PSASOFDATE;
UPDATE 1
I bet the value is varchar with the format MM/dd/YYYY, it that's the case,
SELECT YEAR(STR_TO_DATE('11/15/2012', '%m/%d/%Y'));
LAST RESORT if all the queries fail
use SUBSTRING
SELECT SUBSTRING('11/15/2012', 7, 4)
Quoting the sqlite documentation:
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a colum, remove a column, or add or remove constraints from a table.
What you can do of course is, create a new table with the new layout, SELECT * FROM old_table
, and fill the new table with the values you'll receive.
To display image from local folder, you need to write down code:
<Image source={require('../assets/self.png')}/>
Here I have put my image in asset folder.
The best solution is the attribute selector in CSS (input[type="text"]
) as the others suggested.
But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.
In this case your only option seems to be to define classes on input elements.
<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...
and target them with a class selector:
input.input-box, textarea { background: cyan; }
The variable set by varStatus
is a LoopTagStatus
object, not an int. Use:
<div id="divIDNo${theCount.index}">
To clarify:
${theCount.index}
starts counting at 0
unless you've set the begin
attribute${theCount.count}
starts counting at 1
If you are using SQL Server 2005 the following will work:
select *
from sys.procedures
where is_ms_shipped = 0
1.) left <= root < right
2.) left < root <= right
3.) left < root < right, such that no duplicate keys exist.
I might have to go and dig out my algorithm books, but off the top of my head (3) is the canonical form.
(1) or (2) only come about when you start to allow duplicates nodes and you put duplicate nodes in the tree itself (rather than the node containing a list).
You forgot the HTTP part:
window.location.href = "http://example.com/Registration/Success/";
Basically mentioned this in pyserial documentation https://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.list_ports
import serial.tools.list_ports
ports = serial.tools.list_ports.comports()
for port, desc, hwid in sorted(ports):
print("{}: {} [{}]".format(port, desc, hwid))
Result :
COM1: Communications Port (COM1) [ACPI\PNP0501\1]
COM7: MediaTek USB Port (COM7) [USB VID:PID=0E8D:0003 SER=6 LOCATION=1-2.1]
The
RecyclerView
is a new ViewGroup that is prepared to render any adapter-based view in a similar way. It is supossed to be the successor ofListView and GridView
, and it can be found in thelatest support-v7 version
. TheRecyclerView
has been developed with extensibility in mind, so it is possible to create any kind of layout you can think of, but not without a little pain-in-the-ass dose.
Answer taken from Antonio leiva
compile 'com.android.support:recyclerview-v7:27.0.0'
RecyclerView
is indeed a powerful view
than ListView
.
For more details you can visit This page.
I know this is an old topic. But I see a comment to the question asking if it could be done in SQL
rather than using PL/SQL
. So thought to post a solution.
The below demonstration is to Search for a VALUE in all COLUMNS of all TABLES in an entire SCHEMA:
Let's look for the value KING
in SCOTT
schema.
SQL> variable val varchar2(10)
SQL> exec :val := 'KING'
PL/SQL procedure successfully completed.
SQL> SELECT DISTINCT SUBSTR (:val, 1, 11) "Searchword",
2 SUBSTR (table_name, 1, 14) "Table",
3 SUBSTR (column_name, 1, 14) "Column"
4 FROM cols,
5 TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '
6 || column_name
7 || ' from '
8 || table_name
9 || ' where upper('
10 || column_name
11 || ') like upper(''%'
12 || :val
13 || '%'')' ).extract ('ROWSET/ROW/*') ) ) t
14 ORDER BY "Table"
15 /
Searchword Table Column
----------- -------------- --------------
KING EMP ENAME
SQL>
Let's look for the value 20
in SCOTT
schema.
SQL> variable val NUMBER
SQL> exec :val := 20
PL/SQL procedure successfully completed.
SQL> SELECT DISTINCT SUBSTR (:val, 1, 11) "Searchword",
2 SUBSTR (table_name, 1, 14) "Table",
3 SUBSTR (column_name, 1, 14) "Column"
4 FROM cols,
5 TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '
6 || column_name
7 || ' from '
8 || table_name
9 || ' where upper('
10 || column_name
11 || ') like upper(''%'
12 || :val
13 || '%'')' ).extract ('ROWSET/ROW/*') ) ) t
14 ORDER BY "Table"
15 /
Searchword Table Column
----------- -------------- --------------
20 DEPT DEPTNO
20 EMP DEPTNO
20 EMP HIREDATE
20 SALGRADE HISAL
20 SALGRADE LOSAL
SQL>
nginx is useful for forwarding HTTP on many platforms including Windows. It's easy to setup and extend with more advanced configuration. A basic configuration could look something like this:
events {}
http {
server {
listen 192.168.1.111:4422;
location / {
proxy_pass http://192.168.2.33:80/;
}
}
}
run postgres -D /usr/local/var/postgres
and you should see something like:
FATAL: lock file "postmaster.pid" already exists
HINT: Is another postmaster (PID 379) running in data directory "/usr/local/var/postgres"?
Then run kill -9 PID
in HINT
And you should be good to go.
Better result for me:
ls -1 | xargs -L1 -d "\n" CMD
Why...
This is likely overkill for most people's needs, but, it addresses a number of things that each individual answer above does not. Of the items it addresses, three of them were needed for my needs. With tight bracketing and dropping the comments, this could still remain readable at only 13 lines of code.
This addresses the following:
Usage:
Send original string, search char/string, "R"/"L" for start on right or left side, true/false for case sensitivity. For example, search for "here" case insensitive, in string, start right side.
echo TruncStringAfterString("Now Here Are Some Words Here Now","here","R",false);
Output would be "Now Here Are Some Words ". Changing the "R" to an "L" would output: "Now ".
Here's the function:
function TruncStringAfterString($origString,$truncChar,$startSide,$caseSensitive)
{
if ($caseSensitive==true && strstr($origString,$truncChar)!==false)
{
// IF START RIGHT SIDE:
if (strtoupper($startSide)=="R" || $startSide==false)
{ // Found, strip off all chars from truncChar to end
return substr($origString,0,strrpos($origString,$truncChar));
}
// IF START LEFT SIDE:
elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
{ // Found, strip off all chars from truncChar to end
return strstr($origString,$truncChar,true);
}
}
elseif ($caseSensitive==false && stristr($origString,$truncChar)!==false)
{
// IF START RIGHT SIDE:
if (strtoupper($startSide)=="R" || $startSide==false)
{ // Found, strip off all chars from truncChar to end
return substr($origString,0,strripos($origString,$truncChar));
}
// IF START LEFT SIDE:
elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
{ // Found, strip off all chars from truncChar to end
return stristr($origString,$truncChar,true);
}
}
else
{ // NOT found - return origString untouched
return $origString; // Nothing to do here
}
}
I have used html line break instead of "\n" . It worked fine.
As mentioned above, you can change the property of the textbox "Read Only" to "True" from the properties window.
find
them and grep
for the string:
This will find all files of your 3 types in /starting/path and grep for the regular expression '(document\.cookie|setcookie)'
. Split over 2 lines with the backslash just for readability...
find /starting/path -type f -name "*.php" -o -name "*.html" -o -name "*.js" | \
xargs egrep -i '(document\.cookie|setcookie)'
System
is a final class from the java.lang
package.
out
is a class variable of type PrintStream
declared in the System
class.
println
is a method of the PrintStream
class.
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
3# Simple scrolling library on Github
Indeed, window.location.origin works fine in browsers following standards, but guess what. IE isn't following standards.
So because of that, this is what worked for me in IE, FireFox and Chrome:
var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
but for possible future enhancements which could cause conflicts, I specified the "window" reference before the "location" object.
var full = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: '');
dateDate.Ticks
should give you what you're looking for.
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.
If you're really looking for the Linux Epoch time (seconds since Jan 1, 1970), the accepted answer for this question should be relevant.
But if you're actually trying to "compress" a string representation of the date into an int, you should ask yourself why aren't you just storing it as a string to begin with. If you still want to do it after that, Stecya's answer is the right one. Keep in mind it won't fit into an int, you'll have to use a long.
Just set this to v21/styles.xml file
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/colorPrimaryDark</item>
and be sure
<item name="android:windowTranslucentStatus">false</item>
You can use the magic constants __METHOD__
(includes the class name) or __FUNCTION__
(just function name) depending on if it's a method or a function... =)
I personally don't like atoi
function. I would suggest sscanf
:
char myarray[5] = {'-', '1', '2', '3', '\0'};
int i;
sscanf(myarray, "%d", &i);
It's very standard, it's in the stdio.h
library :)
And in my opinion, it allows you much more freedom than atoi
, arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.
EDIT
I just found this wonderful question here on the site that explains and compares 3 different ways to do it - atoi
, sscanf
and strtol
. Also, there is a nice more-detailed insight into sscanf
(actually, the whole family of *scanf
functions).
EDIT2
Looks like it's not just me personally disliking the atoi
function. Here's a link to an answer explaining that the atoi
function is deprecated and should not be used in newer code.
It may be useful package list-to-tree Install:
bower install list-to-tree --save
or
npm install list-to-tree --save
For example, have list:
var list = [
{
id: 1,
parent: 0
}, {
id: 2,
parent: 1
}, {
id: 3,
parent: 1
}, {
id: 4,
parent: 2
}, {
id: 5,
parent: 2
}, {
id: 6,
parent: 0
}, {
id: 7,
parent: 0
}, {
id: 8,
parent: 7
}, {
id: 9,
parent: 8
}, {
id: 10,
parent: 0
}
];
Use package list-to-tree:
var ltt = new LTT(list, {
key_id: 'id',
key_parent: 'parent'
});
var tree = ltt.GetTree();
Result:
[{
"id": 1,
"parent": 0,
"child": [
{
"id": 2,
"parent": 1,
"child": [
{
"id": 4,
"parent": 2
}, {
"id": 5, "parent": 2
}
]
},
{
"id": 3,
"parent": 1
}
]
}, {
"id": 6,
"parent": 0
}, {
"id": 7,
"parent": 0,
"child": [
{
"id": 8,
"parent": 7,
"child": [
{
"id": 9,
"parent": 8
}
]
}
]
}, {
"id": 10,
"parent": 0
}];
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
Array.prototype.map()
index:One can access the index Array.prototype.map()
via the second argument of the callback function. Here is an example:
const array = [1, 2, 3, 4];_x000D_
_x000D_
_x000D_
const map = array.map((x, index) => {_x000D_
console.log(index);_x000D_
return x + index;_x000D_
});_x000D_
_x000D_
console.log(map);
_x000D_
Array.prototype.map()
:Array.map()
is a object which will be the this
value for the callback function. Keep in mind that you have to use the regular function
keyword in order to declare the callback since an arrow function doesn't have its own binding to the this
keyword.For example:
const array = [1, 2, 3, 4];_x000D_
_x000D_
const thisObj = {prop1: 1}_x000D_
_x000D_
_x000D_
const map = array.map( function (x, index, array) {_x000D_
console.log(array);_x000D_
console.log(this)_x000D_
}, thisObj);
_x000D_
This works for vertical and horizontal:
#myContent{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
And if you want make an element center of the parent, set the position of the parent relative:
#parentElement{
position: relative
}
For vertical center align, set the height to your element. Thanks to Raul.
If you want make an element center of the parent, set the position of the parent to relative
This is a bit late, but this is the best solution I found. You make a look-up dictionary for the form name and its class, you also have to add an attribute to identify the form, and in your views you have to add it as a hidden field, with the form.formlabel
.
# form holder
form_holder = {
'majeur': {
'class': FormClass1,
},
'majsoft': {
'class': FormClass2,
},
'tiers1': {
'class': FormClass3,
},
'tiers2': {
'class': FormClass4,
},
'tiers3': {
'class': FormClass5,
},
'tiers4': {
'class': FormClass6,
},
}
for key in form_holder.keys():
# If the key is the same as the formlabel, we should use the posted data
if request.POST.get('formlabel', None) == key:
# Get the form and initate it with the sent data
form = form_holder.get(key).get('class')(
data=request.POST
)
# Validate the form
if form.is_valid():
# Correct data entries
messages.info(request, _(u"Configuration validée."))
if form.save():
# Save succeeded
messages.success(
request,
_(u"Données enregistrées avec succès.")
)
else:
# Save failed
messages.warning(
request,
_(u"Un problème est survenu pendant l'enregistrement "
u"des données, merci de réessayer plus tard.")
)
else:
# Form is not valid, show feedback to the user
messages.error(
request,
_(u"Merci de corriger les erreurs suivantes.")
)
else:
# Just initiate the form without data
form = form_holder.get(key).get('class')(key)()
# Add the attribute for the name
setattr(form, 'formlabel', key)
# Append it to the tempalte variable that will hold all the forms
forms.append(form)
I hope this will help in the future.
To disable next line:
// eslint-disable-next-line no-use-before-define
var thing = new Thing();
Or use the single line syntax:
var thing = new Thing(); // eslint-disable-line no-use-before-define
See the eslint docs
If you're using 0
and an empty string ''
and null
to designate undefined you've got a data problem. Just update the columns and fix your schema.
UPDATE pt.incentive_channel
SET pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';
This will make joining and selecting substantially easier moving forward.
Try CSS:
<h2 style="color:#069">Process Report</h2>
If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:
<style type="text/css">
h2 {
color:#069;
}
</style>
In my case I had to wait for a user interaction, so I set a click
or touchend
listener.
const isMobile = navigator.maxTouchPoints || "ontouchstart" in document.documentElement;
function play(){
audioEl.play()
}
document.body.addEventListener(isMobile ? "touchend" : "click", play, { once: true });
You only have one row to serialize. Try something like this :
List<results> resultRows = new List<results>
resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});
string json = JavaScriptSerializer.Serialize(new { results = resultRows});
** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer
the above code produces this result :
{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}
Imagine you've thread A and thread B. They are both synchronised
on the same object and inside this block there's a global variable they are both updating;
static boolean commonVar = false;
Object lock = new Object;
...
void threadAMethod(){
...
while(commonVar == false){
synchornized(lock){
...
commonVar = true
}
}
}
void threadBMethod(){
...
while(commonVar == true){
synchornized(lock){
...
commonVar = false
}
}
}
So, when thread A enters in the while
loop and holds the lock, it does what it has to do and set the commonVar
to true
. Then thread B comes in, enters in the while
loop and since commonVar
is true
now, it is be able to hold the lock. It does so, executes the synchronised
block, and sets commonVar
back to false
. Now, thread A again gets it's new CPU window, it was about to quit the while
loop but thread B has just set it back to false
, so the cycle repeats over again. Threads do something (so they're not blocked in the traditional sense) but for pretty much nothing.
It maybe also nice to mention that livelock does not necessarily have to appear here. I'm assuming that the scheduler favours the other thread once the synchronised
block finish executing. Most of the time, I think it's a hard-to-hit expectation and depends on many things happening under the hood.
Step 1, to update margin
The basic idea is to get margin out and then update it. The update will be applies automatically and you do not need to set it back. To get the layout parameters, simply call this method:
LayoutParams layoutParams = (LayoutParams) yourView.findViewById(R.id.THE_ID).getLayoutParams();
The LayoutParams
comes from the layout of your view. If the view is from a linear layout, you need to import LinearLayout.LayoutParams
. If you use relative layout, import LinearLayout.LayoutParams
, etc.
Now, if you set the margin using Layout_marginLeft
, Right
, etc, you need to update margin in this way
layoutParams.setMargins(left, top, right, bottom);
If you set margin using the new layout_marginStart
, you need to update margin in this way
layoutParams.setMarginStart(start);
layoutParams.setMarginEnd(end);
Step 2, to update margin in dp
All two ways of updating margin above are updating in pixels. You need to do a translation of dp to pixels.
float dpRatio = context.getResources().getDisplayMetrics().density;
int pixelForDp = (int)dpValue * dpRatio;
Now put the calculated value to the above margin update functions and you should be all set
The direct reason for the error is that yes, it's impossible to use git-add
with a bare repository. A bare repository, by definition, has no work tree. git-add
takes files from the work tree and adds them to the index, in preparation for committing.
You may need to put a bit of thought into your setup here, though. GIT_DIR is the repository directory used for all git commands. Are you really trying to create a single repository for everything you track, maybe things all over your system? A git repository by nature tracks the contents of a single directory. You'll need to set GIT_WORK_TREE
to a path containing everything you want to track, and then you'll need a .gitignore
to block out everything you're not interested in tracking.
Maybe you're trying to create a repository which will track just c:\www
? Then you should put it in c:\www
(don't set GIT_DIR). This is the normal usage of git, with the repository in the .git directory of the top-level directory of your "module".
Unless you have a really good reason, I'd recommend sticking with the way git likes to work. If you have several things to track, you probably want several repositories!
Just to summarize the available options:
Tools
Browsers
Other
Please feel free to edit/add new items
I needed to do a similar operation for a Stream
, but couldn't find a good example. Here's what I came up with.
public static <T> boolean areUnique(final Stream<T> stream) {
final Set<T> seen = new HashSet<>();
return stream.allMatch(seen::add);
}
This has the advantage of short-circuiting when duplicates are found early rather than having to process the whole stream and isn't much more complicated than just putting everything in a Set
and checking the size. So this case would roughly be:
List<T> list = ...
boolean allDistinct = areUnique(list.stream());
The practical solution is to use CSS to actually hide the input.
To take this to its natural conclusion, you can write two html inputs for each actual input (one enabled, and one disabled) and then use javascript to control the CSS to show and hide them.
You can also use df.icol(n)
to access a column by integer.
Update: icol
is deprecated and the same functionality can be achieved by:
df.iloc[:, n] # to access the column at the nth position
You can do it like what I did with my website:
background-repeat: no-repeat;
background-size: cover;
If you're looking to capture everything up to "abc":
/^(.*?)abc/
Explanation:
( )
capture the expression inside the parentheses for access using $1
, $2
, etc.
^
match start of line
.*
match anything, ?
non-greedily (match the minimum number of characters required) - [1]
[1] The reason why this is needed is that otherwise, in the following string:
whatever whatever something abc something abc
by default, regexes are greedy, meaning it will match as much as possible. Therefore /^.*abc/
would match "whatever whatever something abc something ". Adding the non-greedy quantifier ?
makes the regex only match "whatever whatever something ".
most collections have a useful toString()
in java these days (Java7/8).
So there is no need to do stream operations to concatenate what you need, just override toString
of your value class in the collection and you get what you need.
both AbstractMap and AbstractCollection implement toString() by calling toString per element.
below is a testclass to show behaviour.
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public class ToString {
static class Foo {
int i;
public Foo(int i) { this.i=i; }
@Override
public String toString() {
return "{ i: " + i + " }";
}
}
public static void main(String[] args) {
List<Foo> foo = new ArrayList<>();
foo.add(new Foo(10));
foo.add(new Foo(12));
foo.add(new Foo(13));
foo.add(new Foo(14));
System.out.println(foo.toString());
// prints: [{ i: 10 }, { i: 12 }, { i: 13 }, { i: 14 }]
Map<Integer, Foo> foo2 = new HashMap<>();
foo2.put(10, new Foo(10));
foo2.put(12, new Foo(12));
foo2.put(13, new Foo(13));
foo2.put(14, new Foo(14));
System.out.println(foo2.toString());
// prints: {10={ i: 10 }, 12={ i: 12 }, 13={ i: 13 }, 14={ i: 14 }}
}
}
Records are now a preview feature not requiring you to override toString()
if your class only holds data. Records implement a data contract, giving public readonly access to it's fields and implementing default functions for your convience, like comparison, toString and hashcode.
so once could implement Foo
as follows with the behavior:
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public class ToString {
static record Foo(int i) { }
public static void main(String[] args) {
Foo f = new Foo(10);
System.out.println(f.toString());
// prints: Foo[i=10]
List<Foo> foo = new ArrayList<>();
foo.add(new Foo(10));
foo.add(new Foo(12));
foo.add(new Foo(13));
foo.add(new Foo(14));
System.out.println(foo.toString());
// prints: [Foo[i=10], Foo[i=12], Foo[i=13], Foo[i=14]]
Map<Integer, Foo> foo2 = new HashMap<>();
foo2.put(10, new Foo(10));
foo2.put(12, new Foo(12));
foo2.put(13, new Foo(13));
foo2.put(14, new Foo(14));
System.out.println(foo2.toString());
// prints: {10=Foo[i=10], 12=Foo[i=12], 13=Foo[i=13], 14=Foo[i=14]}
}
}
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>
A technique I've used in my own systems, and which I believe is employed by Struts, is to include...
<input type="hidden" name="_fieldname" value="fieldvalue"/>
...immediately next to the checkbox as part of my form creation logic.
This allows me to reconstruct which checkboxes were served in the form but not selected, with a tiny bit of extra logic to do the diff what was served and what was checked, you have the ones which were unchecked. The submission is also the same in content regardless whether you're using HTML or AJAX style submission.
Depending on the technology you're using server-side then you may wish to use this syntax...
<input type="hidden" name="_fieldname[]" value="fieldvalue"/>
...to make it easy to grab these values as a list.
Here is the Koltin style, I use this in my project and it works very well:
this.yourview.setOnTouchListener(View.OnTouchListener { _, event ->
val x = event.x
val y = event.y
when(event.action) {
MotionEvent.ACTION_DOWN -> {
Log.d(TAG, "ACTION_DOWN \nx: $x\ny: $y")
}
MotionEvent.ACTION_MOVE -> {
Log.d(TAG, "ACTION_MOVE \nx: $x\ny: $y")
}
MotionEvent.ACTION_UP -> {
Log.d(TAG, "ACTION_UP \nx: $x\ny: $y")
}
}
return@OnTouchListener true
})
If .java
file contains top level (not nested) public
class, it have same name as that public class. So if you have class like public class A{...}
it needs to be placed in A.java
file. Because of that we can't have two public classes in one .java
file.
If having two public classes would be allowed then, and lets say aside from public A
class file would also contain public class B{}
it would require from A.java
file to be also named as B.java
but files can't have two (or more) names (at least in all systems on which Java can be run).
So assuming your code is placed in StaticDemoShow.java
file you have two options:
If you want to have other class in same file make them non-public (lack of visibility modifier will represent default/package-private visibility)
class StaticDemo { // It can no longer public
static int a = 3;
static int b = 4;
static {
System.out.println("Voila! Static block put into action");
}
static void show() {
System.out.println("a= " + a);
System.out.println("b= " + b);
}
}
public class StaticDemoShow { // Only one top level public class in same .java file
public static void main() {
StaticDemo.show();
}
}
Move all public classes to their own .java
files. So in your case you would need to split it into two files:
StaticDemo.java
public class StaticDemo { // Note: same name as name of file
static int a = 3;
static int b = 4;
static {
System.out.println("Voila! Static block put into action");
}
static void show() {
System.out.println("a= " + a);
System.out.println("b= " + b);
}
}
StaticDemoShow.java
public class StaticDemoShow {
public static void main() {
StaticDemo.show();
}
}
Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT
i.e 204 No Content as in place of HttpStatus.OK
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
Any value of T will be ignored for 204, but not for 404
public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$
if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
} else {
LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
}
}
Another thing you can do is just drag a folder from your computer into the GitHub repository page. This folder does have to have at least 1 item in it, though.
In the SQL-92 Standard, COUNT(*)
specifically means "the cardinality of the table expression" (could be a base table, `VIEW, derived table, CTE, etc).
I guess the idea was that COUNT(*)
is easy to parse. Using any other expression requires the parser to ensure it doesn't reference any columns (COUNT('a')
where a
is a literal and COUNT(a)
where a
is a column can yield different results).
In the same vein, COUNT(*)
can be easily picked out by a human coder familiar with the SQL Standards, a useful skill when working with more than one vendor's SQL offering.
Also, in the special case SELECT COUNT(*) FROM MyPersistedTable;
, the thinking is the DBMS is likely to hold statistics for the cardinality of the table.
Therefore, because COUNT(1)
and COUNT(*)
are semantically equivalent, I use COUNT(*)
.
print("Hello, World!")
You are probably using Python 3.0, where print
is now a function (hence the parenthesis) instead of a statement.
Strangely setting a transparent border solved this for me:
@media print {
div {
border: 1px solid rgba(0,0,0,0)
}
}
Maybe it will suffice to set the border on the container element. <- Untestet.
You can also use String.format("%3.3s", "abcdefgh")
. The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So
System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");
will produce
'abc' ' a'
(you can remove quotes, obviously).
You can do this by taking a Frame layout as parent Layout and then put linear layout inside it. Here is a example:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="16sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="16sp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="16sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="16sp"/>
</LinearLayout>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="bottom"
/>
</FrameLayout>
Old post, but I have a solution that could be usefull for next people. Why not just use file length to know what is the progression? Of course, lines has to be almost the same size, but it works very well for big files:
public static void main(String[] args) throws IOException {
File file = new File("yourfilehere");
double fileSize = file.length();
System.out.println("=======> File size = " + fileSize);
InputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "iso-8859-1");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
int totalRead = 0;
try {
while (bufferedReader.ready()) {
String line = bufferedReader.readLine();
// LINE PROCESSING HERE
totalRead += line.length() + 1; // we add +1 byte for the newline char.
System.out.println("Progress ===> " + ((totalRead / fileSize) * 100) + " %");
}
} finally {
bufferedReader.close();
}
}
It allows to see the progression without doing any full read on the file. I know it depends on lot of elements, but I hope it will be usefull :).
[Edition] Here is a version with estimated time. I put some SYSO to show progress and estimation. I see that you have a good time estimation errors after you have treated enough line (I try with 10M lines, and after 1% of the treatment, the time estimation was exact at 95%). I know, some values has to be set in variable. This code is quickly written but has be usefull for me. Hope it will be for you too :).
long startProcessLine = System.currentTimeMillis();
int totalRead = 0;
long progressTime = 0;
double percent = 0;
int i = 0;
int j = 0;
int fullEstimation = 0;
try {
while (bufferedReader.ready()) {
String line = bufferedReader.readLine();
totalRead += line.length() + 1;
progressTime = System.currentTimeMillis() - startProcessLine;
percent = (double) totalRead / fileSize * 100;
if ((percent > 1) && i % 10000 == 0) {
int estimation = (int) ((progressTime / percent) * (100 - percent));
fullEstimation += progressTime + estimation;
j++;
System.out.print("Progress ===> " + percent + " %");
System.out.print(" - current progress : " + (progressTime) + " milliseconds");
System.out.print(" - Will be finished in ===> " + estimation + " milliseconds");
System.out.println(" - estimated full time => " + (progressTime + estimation));
}
i++;
}
} finally {
bufferedReader.close();
}
System.out.println("Ended in " + (progressTime) + " seconds");
System.out.println("Estimative average ===> " + (fullEstimation / j));
System.out.println("Difference: " + ((((double) 100 / (double) progressTime)) * (progressTime - (fullEstimation / j))) + "%");
Feel free to improve this code if you think it's a good solution.
mach_absolute_time()
can be used to get precise measurements.
See http://developer.apple.com/qa/qa2004/qa1398.html
Also available is CACurrentMediaTime()
, which is essentially the same thing but with an easier-to-use interface.
(Note: This answer was written in 2009. See Pavel Alexeev's answer for the simpler POSIX clock_gettime()
interfaces available in newer versions of macOS and iOS.)
You could use -sed- and -grep- to replace or write to the xml header of each file specifying your desired sheet name, e.g., sheetname1, between any occurrence of the tags:
<Sheetnames>?sheetname1?</Sheetnames>
You can just use the error function that's built in to the math library, as stated on their website.
If you are on .NET 3.5 you can do this:
IEnumerable<int> enumerableThing = ...;
foreach (var x in enumerableThing.Reverse())
It isn't very efficient as it has to basically go through the enumerator forwards putting everything on a stack then pops everything back out in reverse order.
If you have a directly-indexable collection (e.g. IList) you should definitely use a for
loop instead.
If you are on .NET 2.0 and cannot use a for loop (i.e. you just have an IEnumerable) then you will just have to write your own Reverse function. This should work:
static IEnumerable<T> Reverse<T>(IEnumerable<T> input)
{
return new Stack<T>(input);
}
This relies on some behaviour which is perhaps not that obvious. When you pass in an IEnumerable to the stack constructor it will iterate through it and push the items onto the stack. When you then iterate through the stack it pops things back out in reverse order.
This and the .NET 3.5 Reverse()
extension method will obviously blow up if you feed it an IEnumerable which never stops returning items.
if you are using emulator to run your app for local server. mention the local ip
as 10.0.2.2
and have to give Internet permission into your app :
<uses-permission android:name="android.permission.INTERNET" />
Use xcopy /s I:\*.* N:\
This is should do.
For GlassFish Jersey JAX-RS implementation I have resolved this issue by common method is describing all common parameters. At least three of parameters have to be equal: name(="name"), path(="/") and domain(=null) :
public static NewCookie createDomainCookie(String value, int maxAgeInMinutes) {
ZonedDateTime time = ZonedDateTime.now().plusMinutes(maxAgeInMinutes);
Date expiry = time.toInstant().toEpochMilli();
NewCookie newCookie = new NewCookie("name", value, "/", null, Cookie.DEFAULT_VERSION,null, maxAgeInMinutes*60, expiry, false, false);
return newCookie;
}
And use it the common way to set cookie:
NewCookie domainNewCookie = RsCookieHelper.createDomainCookie(token, 60);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();
and to delete the cookie:
NewCookie domainNewCookie = RsCookieHelper.createDomainCookie("", 0);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();
Assert.That(myTestDelegate, Throws.ArgumentException
.With.Property("Message").EqualTo("your argument is invalid."));
This : /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i
is not working for below Gmail case
[email protected] [email protected]
Below Regex will cover all the E-mail Points: I have tried the all Possible Points and my Test case get also pass because of below regex
I found this Solution from this URL:
/(?:((?:[\w-]+(?:\.[\w-]+)*)@(?:(?:[\w-]+\.)*\w[\w-]{0,66})\.(?:[a-z]{2,6}(?:\.[a-z]{2})?));*)/g
Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.
The solution that worked for me was setting my JAVA_HOME
in /etc/environment
Though JAVA_HOME
can be set inside the /etc/profile files, the preferred location for JAVA_HOME
or any system variable is /etc/environment
.
Open /etc/environment in any text editor like nano or vim and add the following line:
JAVA_HOME="/usr/lib/jvm/your_java_directory"
Load the variables:
source /etc/environment
Check if the variable loaded correctly:
echo $JAVA_HOME
Chrome doesn't allow you to integrate two different localhost,that's why we are getting this error. You just have to include Microsoft Visual Studio Web Api Core package from nuget manager.And add the two lines of code in WebApi project's in your WebApiConfig.cs
file.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Then all done.
Since I've asked this question, I've started using python-symmetric-jsonrpc. It is quite good, can be used between python and non-python software and follow the JSON-RPC standard. But it lacks some examples.
to echo @friederbluemle, you can also just launch the SDK manager from the command line if you have the Android SDK tools installed:
$ android
and then in the UI that pops up, select the tools/repositories that need to be installed -- in your case the support library repo
DisplayMetrics displayMetrics = contaxt.getResources()
.getDisplayMetrics();
int densityDpi = (int) (displayMetrics.density * 160f);
int ratio = (densityDpi / DisplayMetrics.DENSITY_DEFAULT);
int px;
if (ratio == 0) {
px = dp;
} else {
px = Math.round(dp * ratio);
}
Kotlin
extension for showing the keyboard on focus.
This is a combination of previous responses, which where either too long or incomplete.
This extension posts a runnable on the message queue which shows the soft keyboard after requesting focus:
fun View.showSoftKeyboard() {
post {
if (this.requestFocus()) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
Call it from any view when needed afterwards:
editText.showSoftKeyboard()
Please read and strongly consider my advice in the comments of your post. That being said, if you still have a good reason to do this, check out this list of crypto modules for Node. It has modules for dealing with both sha1 and base64.
Please use if condition with while loop and try.
eg.
if ($result = $conn->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
}
/* free result set */
$result->free();
}
Below is code to put your Linearlayout at bottom and put its content at center. You have to use RelativeLayout to set Layout at bottom.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#97611F"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="View Saved Searches"
android:textSize="15dp"
android:textColor="#fff"
android:gravity="center_vertical"
android:visibility="visible" />
<TextView
android:layout_width="30dp"
android:layout_height="24dp"
android:text="12"
android:textSize="12dp"
android:textColor="#fff"
android:gravity="center_horizontal"
android:padding="1dp"
android:visibility="visible" />
</LinearLayout>
</RelativeLayout>
You would need to use the following markup. If you want to float any menu items to the right, create a separate <ul class="nav navbar-nav">
with navbar-right
class to it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Project name</a>_x000D_
</div>_x000D_
<div class="collapse navbar-collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li class="active"><a href="#">Home</a></li>_x000D_
<li><a href="#about">About</a></li>_x000D_
_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="#contact">Contact</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I was getting the same error. In the Project Facets of my Java project, the Java compile level was set to 1.7 whereas the WebSphere Application Server v7.0 had a Runtime Composition of JRE v1.6; setting the Java compile level to 1.6 in Project Facets got rid of the error. I did not have to change the Compiler compliance level though, it's still 1.7. Hope this helps!
Try this:
public interface MyService {
//Code
}
@Component("One")
public class MyServiceOne implements MyService {
//Code
}
@Component("Two")
public class MyServiceTwo implements MyService {
//Code
}
Two ways, using system default install path, usually /usr/lib/x86_64-linux-gnu/
:
find_package(Boost REQUIRED regex date_time system filesystem thread graph)
include_directories(${BOOST_INCLUDE_DIRS})
message("boost lib: ${Boost_LIBRARIES}")
message("boost inc:${Boost_INCLUDE_DIR}")
add_executable(use_boost use_boost.cpp)
target_link_libraries(use_boost
${Boost_LIBRARIES}
)
If you install Boost in a local directory or choose local install instead of system install, you can do it by this:
set( BOOST_ROOT "/home/xy/boost_install/lib/" CACHE PATH "Boost library path" )
set( Boost_NO_SYSTEM_PATHS on CACHE BOOL "Do not search system for Boost" )
find_package(Boost REQUIRED regex date_time system filesystem thread graph)
include_directories(${BOOST_INCLUDE_DIRS})
message("boost lib: ${Boost_LIBRARIES}, inc:${Boost_INCLUDE_DIR}")
add_executable(use_boost use_boost.cpp)
target_link_libraries(use_boost
${Boost_LIBRARIES}
)
Note the above dir /home/xy/boost_install/lib/
is where I install Boost:
xy@xy:~/boost_install/lib$ ll -th
total 16K
drwxrwxr-x 2 xy xy 4.0K May 28 19:23 lib/
drwxrwxr-x 3 xy xy 4.0K May 28 19:22 include/
xy@xy:~/boost_install/lib$ ll -th lib/
total 57M
drwxrwxr-x 2 xy xy 4.0K May 28 19:23 ./
-rw-rw-r-- 1 xy xy 2.3M May 28 19:23 libboost_test_exec_monitor.a
-rw-rw-r-- 1 xy xy 2.2M May 28 19:23 libboost_unit_test_framework.a
.......
xy@xy:~/boost_install/lib$ ll -th include/
total 20K
drwxrwxr-x 110 xy xy 12K May 28 19:22 boost/
If you are interested in how to use a local installed Boost, you can see this question How can I get CMake to find my alternative Boost installation?.
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
INT
representation:mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
I had a case in where I was needing to use a data frame within a for loop function. In this case, it was the "efficient", however, keep in mind that the database was small and the iterations in the loop were very simple. But maybe the code could be useful for some one with similar conditions.
The for loop purpose was to use the raster extract function along five locations (i.e. 5 Tokio, New York, Sau Paulo, Seul & Mexico city) and each location had their respective raster grids. I had a spatial point database with more than 1000 observations allocated within the 5 different locations and I was needing to extract information from 10 different raster grids (two grids per location). Also, for the subsequent analysis, I was not only needing the raster values but also the unique ID for each observations.
After preparing the spatial data, which included the following tasks:
Here the for loop code with the use of a data frame:
1. Add stacked rasters per location into a list
raslist <- list(LOC1,LOC2,LOC3,LOC4,LOC5)
2. Create an empty dataframe, this will be the output file
TB <- data.frame(VAR1=double(),VAR2=double(),ID=character())
3. Set up for loop function
L1 <- seq(1,5,1) # the location ID is a numeric variable with values from 1 to 5
for (i in 1:length(L1)) {
dat=subset(points,LOCATION==i) # select corresponding points for location [i]
t=data.frame(extract(raslist[[i]],dat),dat$ID) # run extract function with points & raster stack for location [i]
names(t)=c("VAR1","VAR2","ID")
TB=rbind(TB,t)
}
Always have easy way: Right Click > Generate > toString() > select template that you want.
In my case this worked for python 2.7:
data = read_csv(filename, encoding = "ISO-8859-1", dtype={'name_of_colum': unicode}, low_memory=False)
And for python 3, only:
data = read_csv(filename, encoding = "ISO-8859-1", low_memory=False)
As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them
You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built
Found that setting the secure property in Session_Start is sufficient, as recommended in MSDN blog "Securing Session ID: ASP/ASP.NET" with some augmentation.
protected void Session_Start(Object sender, EventArgs e)
{
SessionStateSection sessionState =
(SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
string sidCookieName = sessionState.CookieName;
if (Request.Cookies[sidCookieName] != null)
{
HttpCookie sidCookie = Response.Cookies[sidCookieName];
sidCookie.Value = Session.SessionID;
sidCookie.HttpOnly = true;
sidCookie.Secure = true;
sidCookie.Path = "/";
}
}
If you're thinking about manually removing Apple's default Python 2.7, I'd suggest you hang-fire and do-noting: Looks like Apple will very shortly do it for you:
Python 2.7- as well as Ruby & Perl- are deprecated in Catalina: (skip to section "Scripting Language Runtimes" > "Deprecations")
https://developer.apple.com/documentation/macos_release_notes/macos_catalina_10_15_release_notes
Indeed, if you do nothing at all, according to The Mac Observer, by OSX version 10.16, Python 2.7 will disappear from your system:
https://www.macobserver.com/analysis/macos-catalina-deprecates-unix-scripting-languages/
Given this revelation, I'd suggest the best course of action is do nothing and wait for Apple to wipe it for you. As Apple is imminently about to remove it for you, doesn't seem worth the risk of tinkering with your Python environment.
NOTE: I see the question relates specifically to OSX v 10.6.4, but it appears this question has become a pivot-point for all OSX folks interested in removing Python 2.7 from their systems, whatever version they're running.
Generally, using Promise.all()
runs requests "async" in parallel. Using await
can run in parallel OR be "sync" blocking.
test1 and test2 functions below show how await
can run async or sync.
test3 shows Promise.all()
that is async.
jsfiddle with timed results - open browser console to see test results
Sync behavior. Does NOT run in parallel, takes ~1800ms:
const test1 = async () => {
const delay1 = await Promise.delay(600); //runs 1st
const delay2 = await Promise.delay(600); //waits 600 for delay1 to run
const delay3 = await Promise.delay(600); //waits 600 more for delay2 to run
};
Async behavior. Runs in paralel, takes ~600ms:
const test2 = async () => {
const delay1 = Promise.delay(600);
const delay2 = Promise.delay(600);
const delay3 = Promise.delay(600);
const data1 = await delay1;
const data2 = await delay2;
const data3 = await delay3; //runs all delays simultaneously
}
Async behavior. Runs in parallel, takes ~600ms:
const test3 = async () => {
await Promise.all([
Promise.delay(600),
Promise.delay(600),
Promise.delay(600)]); //runs all delays simultaneously
};
TLDR; If you are using Promise.all()
it will also "fast-fail" - stop running at the time of the first failure of any of the included functions.
As per the hibernate
docs here,
Connection connection()
Deprecated. (scheduled for removal in 4.x). Replacement depends on need; for doing direct JDBC stuff use doWork(org.hibernate.jdbc.Work) ...
Use Hibernate Work API instead:
Session session = entityManager.unwrap(Session.class);
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// do whatever you need to do with the connection
}
});
Another simple option that updates on a click of the checkbox.
HTML:
<input type="checkbox" id="checkbox/>
<input disabled type="submit" id="item"/>
jQuery:
$('#checkbox').click(function() {
if (this.checked) {
$('#item').prop('disabled', false); // If checked enable item
} else {
$('#item').prop('disabled', true); // If checked disable item
}
});
In action: link
With Postman, to test HTTP post actions with a raw JSON data payload, select the raw
option and set the following header parameters:
Content-Type: application/json
Also, be sure to wrap any strings used as keys/values in your JSON payload in double quotes.
The body-parser
package will parse multi-line raw JSON payloads just fine.
{
"foo": "bar"
}
Tested in Chrome v37 and v41 with the Postman v0.8.4.13 extension (body-parser
v1.12.2 and express
v4.12.3) with the setup below:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// ... Your routes and methods here
Try this
void Function()
{
while (condition)
{
await Task.Delay(1);
}
}
This will make the program wait until the condition is not true. You can just invert it by adding a "!" infront of the condition so that it will wait until the condition is true.
The --force
option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.
If you tell rpm
to install all RPMs from some directory, then it does exactly this. rpm
will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.
You can remove the old RPM and rpm
will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.
If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm
to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i
(zypper in
can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.
I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles
. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify
command. It will complain for the new package if the old one has overwritten some files.
Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?
See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")
You can use the following regular expression which will match integers (e.g., 123
), floating-point numbers (12.3
), and numbers with exponents (1.2e3
):
^-?\d*\.?\d+([eE]-?\d+)?$
If you want to accept +
signs as well as -
signs (as Oracle does with TO_NUMBER()
), you can change each occurrence of -
above to [+-]
. So you might rewrite your block of code above as follows:
IF (option_id = 0021) THEN
IF NOT REGEXP_LIKE(value, '^[+-]?\d*\.?\d+([eE][+-]?\d+)?$') OR TO_NUMBER(value) < 10000 OR TO_NUMBER(value) > 7200000 THEN
ip_msg(6214,option_name);
RETURN;
END IF;
END IF;
I am not altogether certain that would handle all values so you may want to add an EXCEPTION
block or write a custom to_number()
function as @JustinCave suggests.
The original poster is quoting a GCC compiler error message, but even by reading this thread, it's not clear that the error message is properly addressed - except by @pmg's answer. (+1, btw)
This is a GCC error message that means the return-value of a function is 'void', but that you are trying to assign it to a non-void variable.
Example:
void myFunction()
{
//...stuff...
}
int main()
{
int myInt = myFunction(); //Compile error!
return 0;
}
You aren't allowed to assign void to integers, or any other type.
In the OP's situation:
int a = srand(time(NULL));
...is not allowed. srand()
, according to the documentation, returns void.
This question is a duplicate of:
I am responding, despite it being duplicates, because this is the top result on Google for this error message. Because this thread is the top result, it's important that this thread gives a succinct, clear, and easily findable result.
Generally you don't want to mix the default touch and non-touch (click) api. Once you move into the world of touch it easier to deal only with the touch related functions. Below is some pseudo code that would do what you want it to.
If you connect in the touchmove event and track the locations you can add more items in the doTouchLogic function to detect gestures and whatnot.
var touchStartTime;
var touchStartLocation;
var touchEndTime;
var touchEndLocation;
$thing.bind('touchstart'), function() {
var d = new Date();
touchStartTime = d.getTime();
touchStartLocation = mouse.location(x,y);
});
$thing.bind('touchend'), function() {
var d = new Date();
touchEndTime= d.getTime();
touchEndLocation= mouse.location(x,y);
doTouchLogic();
});
function doTouchLogic() {
var distance = touchEndLocation - touchStartLocation;
var duration = touchEndTime - touchStartTime;
if (duration <= 100ms && distance <= 10px) {
// Person tapped their finger (do click/tap stuff here)
}
if (duration > 100ms && distance <= 10px) {
// Person pressed their finger (not a quick tap)
}
if (duration <= 100ms && distance > 10px) {
// Person flicked their finger
}
if (duration > 100ms && distance > 10px) {
// Person dragged their finger
}
}
Since Hadoop 3.0.0 - Alpha 1 there was a Change in the port configuration:
http://localhost:50070
was moved to
http://localhost:9870
modelBuilder.Property(x => x.FirstName).IsUnicode().IsRequired().HasMaxLength(50);
The best way to get filetype-specific indentation is to use filetype plugin indent on
in your vimrc. Then you can specify things like set sw=4 sts=4 et
in .vim/ftplugin/c.vim, for example, without having to make those global for all files being edited and other non-C type syntaxes will get indented correctly, too (even lisps).
white-space: nowrap;
: Will never break text, will keep other defaults
white-space: pre;
: Will never break text, will keep multiple spaces after one another as multiple spaces, will break if explicitly written to break(pressing enter in html etc)
You can project into anonymous type, and then from it to model type
public IEnumerable<Product> GetProducts(int categoryID)
{
return (from p in Context.Set<Product>()
where p.CategoryID == categoryID
select new { Name = p.Name }).ToList()
.Select(x => new Product { Name = x.Name });
}
Edit: I am going to be a bit more specific since this question got a lot of attention.
You cannot project into model type directly (EF restriction), so there is no way around this. The only way is to project into anonymous type (1st iteration), and then to model type (2nd iteration).
Please also be aware that when you partially load entities in this manner, they cannot be updated, so they should remain detached, as they are.
I never did completely understand why this is not possible, and the answers on this thread do not give strong reasons against it (mostly speaking about partially loaded data). It is correct that in partially loaded state entity cannot be updated, but then, this entity would be detached, so accidental attempts to save them would not be possible.
Consider method I used above: we still have a partially loaded model entity as a result. This entity is detached.
Consider this (wish-to-exist) possible code:
return (from p in Context.Set<Product>()
where p.CategoryID == categoryID
select new Product { Name = p.Name }).AsNoTracking().ToList();
This could also result in a list of detached entities, so we would not need to make two iterations. A compiler would be smart to see that AsNoTracking() has been used, which will result in detached entities, so it could allow us to do this. If, however, AsNoTracking() was omitted, it could throw the same exception as it is throwing now, to warn us that we need to be specific enough about the result we want.
Solution with backward compatibility which doesn't produce Xcode warnings:
SEL requestSelector = NSSelectorFromString(@"requestWhenInUseAuthorization");
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined &&
[self.locationManager respondsToSelector:requestSelector]) {
((void (*)(id, SEL))[self.locationManager methodForSelector:requestSelector])(self.locationManager, requestSelector);
[self.locationManager startUpdatingLocation];
} else {
[self.locationManager startUpdatingLocation];
}
Setup NSLocationWhenInUseUsageDescription
key in your Info.plist
.
For iOS version 11.0+ :
Setup NSLocationAlwaysAndWhenInUseUsageDescription
key in your Info.plist
. along with other 2 keys.
I had to move the folders inside a folder named "default" to the android-## folder so Eclipse could see the images.
After getting feedback, It seems the original solution didn't work. That's why updated the answer as one of the suggestions.
def float_of_2_decimal(float_n)
float_n.to_d.round(2, :truncate).to_f
end
Other answers may work, if you want to have rounded numbers of 2 decimal places. But, If you want to have floating point numbers with first two decimal places without rounding, Those answers won't help.
So, to get a floating point number with first two decimal places, I used this technique. Doesn't work in some cases
def float_of_2_decimal(float_n)
float_n.round(3).to_s[0..3].to_f
end
with 5.666666666666666666666666
, it will return 5.66
instead of rounded 5.67
. Hope it will help someone
I use this code:
<?php
{
//foreach (glob("images/*.jpg") as $large)
foreach (glob("*.xml") as $filename) {
//echo "$filename\n";
//echo str_replace("","","$filename\n");
echo str_replace("","","<a href='$filename'>$filename</a>\n");
}
}
?>
It works for me:
>>> def pyth_test (x1, x2):
... print x1 + x2
...
>>> pyth_test(1,2)
3
Make sure you define the function before you call it.
declare @hours int = 5;
select dateadd(hour,@hours,getdate())
@mayabelle you can create IHttpActionResult concrete and wrapped those code like this:
public class NotFoundPlainTextActionResult : IHttpActionResult
{
public NotFoundPlainTextActionResult(HttpRequestMessage request, string message)
{
Request = request;
Message = message;
}
public string Message { get; private set; }
public HttpRequestMessage Request { get; private set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(ExecuteResult());
}
public HttpResponseMessage ExecuteResult()
{
var response = new HttpResponseMessage();
if (!string.IsNullOrWhiteSpace(Message))
//response.Content = new StringContent(Message);
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception(Message));
response.RequestMessage = Request;
return response;
}
}
Let's answer your questions one by one.
To Remove some element from Listview in android then it will remove your specific element and Bind it to listview.
BookinhHistory_adapter.this.productPojoList.remove(position);
BookinhHistory_adapter.this.notifyDataSetChanged();
A simple workaround:
If a container has only one top level child, then you can specify alignment property for the child and give it any available value. it'll fill all the space in the container.
Container(color:Colors.white,height:200.0,width:200.0,
child:Container(
color: Colors.yellow,
alignment:Alignment.[any_available_option] // make the yellow child match the parent size
)
)
Another way:
Container(color:Colors.white,height:200.0,width:200.0,
child:Container(
color: Colors.yellow,
constraints: BoxConstraints.expand(height: 100.0), // height will be 100 dip and width will be match parent
)
)
If your markup is bound to a controller, directive or anything else with a $scope:
console.log($scope.movie);
If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.
This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):
public class MyAshxClass : IHttpHandler, IRequiresSessionState
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
Assuming you want to show an Image thumbnail which is 50x50 pixels and link to the the actual image you can do
<a href="path/to/image.jpg" alt="Image description" target="_blank" style="display: inline-block; width: 50px; height; 50px; background-image: url('path/to/image.jpg');"></a>
Of course it's best to give that link a class or id and put it in your css
You can set the default like this:
b = models.CharField(max_length=7,default="foobar")
and then you can hide the field with your model's Admin class like this:
class SomeModelAdmin(admin.ModelAdmin):
exclude = ("b")
Some good answers here but just adding an approach that won't be affected by borders and padding:
<style type="text/css">
html, body{width: 100%; height: 100%; padding: 0; margin: 0}
div{position: absolute; padding: 1em; border: 1px solid #000}
#nw{background: #f09; top: 0; left: 0; right: 50%; bottom: 50%}
#ne{background: #f90; top: 0; left: 50%; right: 0; bottom: 50%}
#sw{background: #009; top: 50%; left: 0; right: 50%; bottom: 0}
#se{background: #090; top: 50%; left: 50%; right: 0; bottom: 0}
</style>
<div id="nw">test</div>
<div id="ne">test</div>
<div id="sw">test</div>
<div id="se">test</div>
If you are not worried about security and you're simply looking to start a docker container on the host from within another docker container like the OP, you can share the docker server running on the host with the docker container by sharing it's listen socket.
Please see https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface and see if your personal risk tolerance allows this for this particular application.
You can do this by adding the following volume args to your start command
docker run -v /var/run/docker.sock:/var/run/docker.sock ...
or by sharing /var/run/docker.sock within your docker compose file like this:
version: '3'
services:
ci:
command: ...
image: ...
volumes
- /var/run/docker.sock:/var/run/docker.sock
When you run the docker start command within your docker container, the docker server running on your host will see the request and provision the sibling container.
credit: http://jpetazzo.github.io/2015/09/03/do-not-use-docker-in-docker-for-ci/
No way to do that other than validate file extension with JavaScript when input path is populated by the file picker. To implement anything fancier you need to write your own component for whichever browser you want (activeX or XUL)
There's an "accept" attribute in HTML4.01 but I'm not aware of any browser supporting it - e.g. accept="image/gif,image/jpeg
- so it's a neat but impractical spec
I think the result for those two should always be the same. The difference is that you need an instance of the class to use isInstance
but just the Class
object to use isAssignableFrom
.
A Simple program in java for arrays having unique elements:
import java.util.*;
public class ArrayPairSum {
public static void main(String[] args) {
int []a = {2,4,7,3,5,1,8,9,5};
sumPairs(a,10);
}
public static void sumPairs(int []input, int k){
Set<Integer> set = new HashSet<Integer>();
for(int i=0;i<input.length;i++){
if(set.contains(input[i]))
System.out.println(input[i] +", "+(k-input[i]));
else
set.add(k-input[i]);
}
}
}
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
take a look at xp_sprintf. example below.
DECLARE @ret_string varchar (255)
EXEC xp_sprintf @ret_string OUTPUT,
'INSERT INTO %s VALUES (%s, %s)', 'table1', '1', '2'
PRINT @ret_string
Result looks like this:
INSERT INTO table1 VALUES (1, 2)
Just found an issue with the max size (255 char limit) of the string with this so there is an alternative function you can use:
create function dbo.fnSprintf (@s varchar(MAX),
@params varchar(MAX), @separator char(1) = ',')
returns varchar(MAX)
as
begin
declare @p varchar(MAX)
declare @paramlen int
set @params = @params + @separator
set @paramlen = len(@params)
while not @params = ''
begin
set @p = left(@params+@separator, charindex(@separator, @params)-1)
set @s = STUFF(@s, charindex('%s', @s), 2, @p)
set @params = substring(@params, len(@p)+2, @paramlen)
end
return @s
end
To get the same result as above you call the function as follows:
print dbo.fnSprintf('INSERT INTO %s VALUES (%s, %s)', 'table1,1,2', default)
I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.
ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl)
REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back
However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)
Try using the data
option of the $.ajax
function. More info here.
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>',
data: { 'id' : selectedId, 'comments' : comments },
type: "post",
cache: false,
success: function (savingStatus) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
I normally use
grep searchstring file -C n # n for number of lines of context up and down
Many of the tools like grep also have really great man files too. I find myself referring to grep's man page a lot because there is so much you can do with it.
man grep
Many GNU tools also have an info page that may have more useful information in addition to the man page.
info grep
In MySQL itself, you can specify CSV output like:
SELECT order_id,product_name,qty
FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
From http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/
-qscale:v
to control qualityUse -qscale:v
(or the alias -q:v
) as an output option.
-qmin 1
output option (because the default is -qmin 2
).ffmpeg -i input.mp4 -qscale:v 2 output_%03d.jpg
See the image muxer documentation for more options involving image outputs.
ffmpeg -ss 60 -i input.mp4 -qscale:v 4 -frames:v 1 output.jpg
Add attributed text color in swift code.
Swift 4:
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
label.attributedText = attributedString
for Swift 3:
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
label.attributedText = attributedString
None of these answers solved my problem, which was that the items weren't the same width in my makeshift flexbox table when it was shrunk to a width too small.
The solution for me was simply to put overflow: hidden;
on the flex-grow: 1;
cells.
As the commenters have stated the best option is to fix the errors, but with limited time or knowledge, that's not always possible. In your php.ini change
error_reporting = E_ALL
to
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT
If you don't have access to the php.ini, you can potentially put this in your .htaccess file:
php_value error_reporting 30711
This is the E_ALL value (32767) and the removing the E_STRICT (2048) and E_NOTICE (8) values.
If you don't have access to the .htaccess file or it's not enabled, you'll probably need to put this at the top of the PHP section of any script that gets loaded from a browser call:
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
One of those should help you be able to use the software. The notices and strict stuff are indicators of problems or potential problems though and you may find some of the code is not working correctly in PHP 5.4.
Another case that could cause this error is
>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index
Using the actual shape will fix it.
>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>
**
**
You can do it for macOS, too. Ok, not through code, but with some simple steps:
Actually it is a general thing not specific to electron. You can change the icon of many macOS apps like this.
In answer to the question in how to write to a file in PHP you can use the following as an example:
$fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
if ($fp) {
fwrite ($fp, $text); //$text is what you are writing to the file
fclose ($fp);
$writeSuccess = "Yes";
#echo ("File written");
}
else {
$writeSuccess = "No";
#echo ("File was not written");
}
Both means "every item in a set of two things". The two things being "left" and "right"
In windows, specified protocol for application can be registered in Registry. In this msdn doc shows Registering an Application to a URI Scheme.
For example, an executable files 'alert.exe' is to be started. The following item can be registered.
HKEY_CLASSES_ROOT
alert
(Default) = "URL:Alert Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "alert.exe,1"
shell
open
command
(Default) = "C:\Program Files\Alert\alert.exe"
Then you can write a html to test
<head>
<title>alter</title>
</head>
<body>
<a href="alert:" >alert</a>
<body>
Looks like you are missing a leading slash. Perhaps try:
Scanner s = new Scanner(new File("/home/me/java/ex.txt"));
(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)
No expensive forks, no pipes, no bashisms:
$ set -- $STRING
$ eval echo \${$N}
three
But beware of globbing.
Here's a short version:
$('#ddlCodes').change(function() {
$('#txtEntry2').text($(this).find(":selected").text());
});
karim79 made a good catch, judging by your element name txtEntry2
may be a textbox, if it's any kind of input, you'll need to use .val()
instead or .text()
like this:
$('#txtEntry2').val($(this).find(":selected").text());
For the "what's wrong?" part of the question: .text()
doesn't take a selector, it takes text you want it set to, or nothing to return the text already there. So you need to fetch the text you want, then put it in the .text(string)
method on the object you want to set, like I have above.
CSS relates to visual styling and not behaviour, so the answer is no really.
You could however either use javascript to modify the behaviour or change the styling of the span in question so that it doesn't have the pointy finger, underline, etc. Styling it like that will still leave it clickable.
Even better, change your markup so that it reflects what you want it to do.
Whats the value for the SqlException.ErrorCode property? Can you work with that?
When having timeouts, it may be worth checking the code for -2146232060.
I would set this up as a static const in your data code.
You need to export the User.name
field so that the json
package can see it. Rename the name
field to Name
.
package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
}
func main() {
user := &User{Name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
Output:
{"Name":"Frank"}
Install the readr
package, then use library(readr)
.
To make it work you only need two things. Check if you are missing:
You need to add dependency for jersey-json if you are missing.For your reference I added this dependency into my pom.xml.
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.17.1</version>
</dependency>
Since JPA 2.0 a TypedQuery
can be used:
TypedQuery<SimpleEntity> q =
em.createQuery("select t from SimpleEntity t", SimpleEntity.class);
List<SimpleEntity> listOfSimpleEntities = q.getResultList();
for (SimpleEntity entity : listOfSimpleEntities) {
// do something useful with entity;
}
What if you want to use both id and name in the dropdown? Here is the code for that:
$mysqli = new mysqli($servername, $username, $password, $dbname);
$sqlSelect = "SELECT BrandID, BrandName FROM BrandMaster";
$result = $mysqli -> query ($sqlSelect);
echo "<select id='brandId' name='brandName'>";
while ($row = mysqli_fetch_array($result)) {
unset($id, $name);
$id = $row['BrandID'];
$name = $row['BrandName'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
A little optimization of the class before. In this version the files are not totally loaded into memory.
Security advice: a check for the boundary is missing, if the file contains the bounday it will crash.
namespace WindowsFormsApplication1
{
public static class FormUpload
{
private static string NewDataBoundary()
{
Random rnd = new Random();
string formDataBoundary = "";
while (formDataBoundary.Length < 15)
{
formDataBoundary = formDataBoundary + rnd.Next();
}
formDataBoundary = formDataBoundary.Substring(0, 15);
formDataBoundary = "-----------------------------" + formDataBoundary;
return formDataBoundary;
}
public static HttpWebResponse MultipartFormDataPost(string postUrl, IEnumerable<Cookie> cookies, Dictionary<string, string> postParameters)
{
string boundary = NewDataBoundary();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
// Set up the request properties
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.UserAgent = "PhasDocAgent 1.0";
request.CookieContainer = new CookieContainer();
foreach (var cookie in cookies)
{
request.CookieContainer.Add(cookie);
}
#region WRITING STREAM
using (Stream formDataStream = request.GetRequestStream())
{
foreach (var param in postParameters)
{
if (param.Value.StartsWith("file://"))
{
string filepath = param.Value.Substring(7);
// Add just the first part of this param, since we will write the file data directly to the Stream
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
Path.GetFileName(filepath) ?? param.Key,
MimeTypes.GetMime(filepath));
formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, header.Length);
// Write the file data directly to the Stream, rather than serializing it to a string.
byte[] buffer = new byte[2048];
FileStream fs = new FileStream(filepath, FileMode.Open);
for (int i = 0; i < fs.Length; )
{
int k = fs.Read(buffer, 0, buffer.Length);
if (k > 0)
{
formDataStream.Write(buffer, 0, k);
}
i = i + k;
}
fs.Close();
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
boundary,
param.Key,
param.Value);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, postData.Length);
}
}
// Add the end of the request
byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
formDataStream.Write(footer, 0, footer.Length);
request.ContentLength = formDataStream.Length;
formDataStream.Close();
}
#endregion
return request.GetResponse() as HttpWebResponse;
}
}
}
Be wary, too, of inheriting workspace settings in your projects for Java Compiler/Compliance settings. I had a project that was imported into Eclipse. Eclipse generated the project with a J2SE 1.4 JRE, compiler, and compliance settings.
When I went in and manually updated these settings and un-checked the "Enable project specific settings" box, I was still receiving build errors relating to 1.5 level compliance (even though the workspace settings were clearly 1.6). It wasn't until I re-checked the "Enable project specific settings" box and manually set the compiler/compliance levels to 1.6 did the errors go away.
Let's say your script is called my_script.py
and you have put it in your Downloads folder.
There are many ways of installing Python, but homebrew is the easiest.
0) Open Terminal.app
1) Install homebrew (by pasting the following text into Terminal.app and pressing the Enter key)
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
2) Install Python using homebrew
brew install python
3) cd
into the directory that contains your Python script (as an example I'm using the Downloads (Downloads
) folder in your home (~
) folder):
cd ~/Downloads
4) Run the script using the python3
executable
python3 my_script.py
You can also skip step 3 and give python3
an absolute path instead
python3 ~/Downloads/my_script.py
Instead of typing out that whole thing (~/Downloads/my_script.py
), you can find the .py
file in Finder.app and just drag it into the Terminal.app window which should type out the path for you.
If you have spaces or certain other symbols somewhere in your filename you need to enclose the file name in quotes:
python3 "~/Downloads/some directory with spaces/and a filename with a | character.py"
Note that you need to install it as brew install python
but later use the command python3
(with a 3
at the end).
In date '?'
, the '?'
is a literal string with value ?
, not a parameter placeholder, so your query does not have any parameters. The date
is a shorthand cast from (literal) string to date. You need to replace date '?'
with ?
to actually have a parameter.
Also if you know it is a date, then use setDate(..)
and not setString(..)
to set the parameter.
Or since Objective C is just C with some OO layer on top you can use the posix conterparts:
int execl(const char *path, const char *arg0, ..., const char *argn, (char *)0);
int execle(const char *path, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
int execlp(const char *file, const char *arg0, ..., const char *argn, (char *)0);
int execlpe(const char *file, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
int execv(const char *path, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]);
They are included from unistd.h header file.
wxHexEditor is the only GUI disk editor for linux. to google "wxhexeditor site:archive.getdeb.net" and download the .deb file to install
Suppose source code copy from other places.
Sometime, if you use Virtual Directory in your application url like:
http://localhost:50385/myapp/#/
No route will pick up the request.
solution:
Explicitly click the button 'create a virtual directory' in your project file.
Yes it is possible if you bind events using tag attribute onclick="sayHi()"
directly in template similar like your <body onload="start()">
- this approach similar to frameworks angular/vue/react/etc. You can also use <template>
to operate on 'dynamic' html like here. It is not strict unobtrusive js however it is acceptable for small projects
function start() {_x000D_
mydiv.innerHTML += "bar";_x000D_
}_x000D_
_x000D_
function sayHi() {_x000D_
alert("hi");_x000D_
}
_x000D_
<body onload="start()">_x000D_
<div id="mydiv" style="border: solid red 2px">_x000D_
<span id="myspan" onclick="sayHi()">foo</span>_x000D_
</div>_x000D_
</body>
_x000D_
If column A contains the amounts to be reimbursed, and column B contains the "yes/no" indicating whether the reimbursement has been made, then either of the following will work, though the first option is recommended:
=SUMIF(B:B,"No",A:A)
or
=SUMIFS(A:A,B:B,"No")
Here is an example that will display the amounts paid and outstanding for a small set of sample data.
A B C D
Amount Reimbursed? Total Paid: =SUMIF(B:B,"Yes",A:A)
$100 Yes Total Outstanding: =SUMIF(B:B,"No",A:A)
$200 No
$300 No
$400 Yes
$500 No
This problem is basically seen because of case sensitive file name. for example if you save file as index.jadge than its mane on route it should be "index" not "Index" in windows this is okay but in linux like server this will create issue.
1) if file name is index.jadge
app.get('/', function(req, res){
res.render("index");
});
2) if file name is Index.jadge
app.get('/', function(req, res){
res.render("Index");
});
I faced a similar problem. I had a string which contained path to a folder in Windows e.g. C:\Users\
The problem is that \
is an escape character and so in order to use it in strings you need to add one more \
.
Incorrect: C:\Users\
Correct: C:\\\Users\\\
<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">
When you post that data, it is stored as an array in $_POST
.
You could optionally do something like:
<input name="arrayname[item1]">
<input name="arrayname[item2]">
<input name="arrayname[item3]">
Then:
$item1 = $_POST['arrayname']['item1'];
$item2 = $_POST['arrayname']['item2'];
$item3 = $_POST['arrayname']['item3'];
But I fail to see the point.
Traversal over the large map entrySet()
is much better than the keySet()
. Check this tutorial how they optimise the traversal over the large object with the help of entrySet(
) and how it helps for performance tuning.
Try:
java -cp . Echo "hello"
Assuming that you compiled with:
javac Echo.java
Then there is a chance that the "current" directory is not in your classpath ( where java looks for .class definitions )
If that's the case and listing the contents of your dir displays:
Echo.java
Echo.class
Then any of this may work:
java -cp . Echo "hello"
or
SET CLASSPATH=%CLASSPATH;.
java Echo "hello"
And later as Fredrik points out you'll get another error message like.
Exception in thread "main" java.lang.NoSuchMethodError: main
When that happens, go and read his answer :)
$('#div1').scrollTop($('#div1')[0].scrollHeight);
Or animated:
$("#div1").animate({ scrollTop: $('#div1')[0].scrollHeight}, 1000);
For ubuntu users, this error may arise because setuptool is not installed system-wide. Simply install setuptool using the command:
sudo apt-get install -y python-setuptools
For python3:
sudo apt-get install -y python3-setuptools
After that, install your package again normally, using
sudo python setup.py install
That's all.
The following code (in Kotlin) works from API 21 until at least current API version (API 29). The function getWifiState() returns one of 3 possible values for the WiFi network state: Disable, EnabledNotConnected and Connected that were defined in an enum class. This allows to take more granular decisions like informing the user to enable WiFi or, if already enabled, to connect to one of the available networks. But if all that is needed is a boolean indicating if the WiFi interface is connected to a network, then the other function isWifiConnected() will give you that. It uses the previous one and compares the result to Connected.
It's inspired in some of the previous answers but trying to solve the problems introduced by the evolution of Android API's or the slowly increasing availability of IP V6. The trick was to use:
wifiManager.connectionInfo.bssid != null
instead of:
According to the documentation: https://developer.android.com/reference/kotlin/android/net/wifi/WifiInfo.html#getbssid it will return null if not connected to a network. And even if we do not have permission to get the real value, it will still return something other than null if we are connected.
Also have the following in mind:
On releases before android.os.Build.VERSION_CODES#N, this object should only be obtained from an Context#getApplicationContext(), and not from any other derived context to avoid memory leaks within the calling process.
In the Manifest, do not forget to add:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Proposed code is:
class MyViewModel(application: Application) : AndroidViewModel(application) {
// Get application context
private val myAppContext: Context = getApplication<Application>().applicationContext
// Define the different possible states for the WiFi Connection
internal enum class WifiState {
Disabled, // WiFi is not enabled
EnabledNotConnected, // WiFi is enabled but we are not connected to any WiFi network
Connected, // Connected to a WiFi network
}
// Get the current state of the WiFi network
private fun getWifiState() : WifiState {
val wifiManager : WifiManager = myAppContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
return if (wifiManager.isWifiEnabled) {
if (wifiManager.connectionInfo.bssid != null)
WifiState.Connected
else
WifiState.EnabledNotConnected
} else {
WifiState.Disabled
}
}
// Returns true if we are connected to a WiFi network
private fun isWiFiConnected() : Boolean {
return (getWifiState() == WifiState.Connected)
}
}
I found this official tool from facebook developer page, this page will you following information related to access token - App ID, Type, App-Scoped,User last installed this app via, Issued, Expires, Data Access Expires, Valid, Origin, Scopes. Just need access token.
var timeConvert = function(n){
var minutes = n%60
var hours = (n - minutes) / 60
console.log(hours + ":" + minutes)
}
timeConvert(65)
this will log 1:5 to the console. It is a short and simple solution that should be easy to understand and no jquery plugin is necessary...
You can find a whole bunch of Linq examples in visual studio.
Just select Help -> Samples
, and then unzip the Linq samples.
Open the linq samples solution and open the LinqSamples.cs of the SampleQueries project.
The answer you are looking for is in method Linq14:
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var pairs =
from a in numbersA
from b in numbersB
where a < b
select new {a, b};
sys.path
to find all modules (except builtin ones)./usr/lib/pythonX.X/site-packages
(again, see sys.path
). And consider using native Python package management (via pip
or easy_install
, plus yolk
) instead, packages in Linux distros-maintained repositories tend to be outdated.I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:
#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;
A digit in the range 1-9 followed by zero or more other digits:
^[1-9]\d*$
To allow numbers with an optional decimal point followed by digits. A digit in the range 1-9 followed by zero or more other digits then optionally followed by a decimal point followed by at least 1 digit:
^[1-9]\d*(\.\d+)?$
Notes:
The ^
and $
anchor to the start and end basically saying that the whole string must match the pattern
()?
matches 0 or 1 of the whole thing between the brackets
Update to handle commas:
In regular expressions .
has a special meaning - match any single character. To match literally a .
in a string you need to escape the .
using \.
This is the meaning of the \.
in the regexp above. So if you want to use comma instead the pattern is simply:
^[1-9]\d*(,\d+)?$
Further update to handle commas and full stops
If you want to allow a . between groups of digits and a , between the integral and the fractional parts then try:
^[1-9]\d{0,2}(\.\d{3})*(,\d+)?$
i.e. this is a digit in the range 1-9 followed by up to 2 other digits then zero or more groups of a full stop followed by 3 digits then optionally your comma and digits as before.
If you want to allow a . anywhere between the digits then try:
^[1-9][\.\d]*(,\d+)?$
i.e. a digit 1-9 followed by zero or more digits or full stops optionally followed by a comma and one or more digits.
Why :not just use two :not
:
input:not([type="radio"]):not([type="checkbox"])
Yes, it is intentional
The ==
token in C# is used for two different equality-check operators. When the compiler encounters that token, it will check whether either of the types being compared has implemented an equality-operator overload for either the specific combination types being compared(*), or for a combination of types to which both types can be converted. If the compiler finds such an overload it will use it. Otherwise, if the two types are both reference types and they are not unrelated classes (either may be an interface, or they may be related classes), the compiler will regard ==
as a reference-comparison operator. If neither condition applies, compilation will fail.
Note that some other languages use separate tokens for the two equality-check operators. In VB.NET, for example, the =
token is used within expressions solely for the overloadable equality-check operator, and Is
is used as a reference-test or null-test operator. An to use =
on a type which does not override the equality-check operator will fail, as will attempting to use Is
for any purpose other than testing reference equality or nullity.
(*)Types generally only overload equality for comparison with themselves, but it may be useful for types to overload the equality operator for comparison with other particular types; for example, int
could have (and IMHO should have but didn't) defined an equality operators for comparison with float
, so that 16777217 would not report itself equal to 16777216f. As it is, since no such operator is defined, C# will promote the int
to float
, rounding it to 16777216f before the equality-check operator sees it; that operator then sees two equal floating-point numbers and reports them as equal, unaware of the rounding that took place.
Some handy script:
hour = df['assess_time'].dt.hour.values[0]
Many C APIs use a null pointer to indicate "use the default", e.g. mosquittopp. Here is the pattern I am using, based on David Cormack's answer:
mosqpp::tls_set(
MqttOptions->CAFile.length() > 0 ? MqttOptions->CAFile.c_str() : NULL,
MqttOptions->CAPath.length() > 0 ? MqttOptions->CAPath.c_str() : NULL,
MqttOptions->CertFile.length() > 0 ? MqttOptions->CertFile.c_str() : NULL,
MqttOptions->KeyFile.length() > 0 ? MqttOptions->KeyFile.c_str() : NULL
);
It is a little cumbersome, but allows one to keep everything as a std::string
up until the API call itself.
You can see it like this:
A Primary Key IS Unique
A Unique value doesn't have to be the Representaion of the Element
Meaning?; Well a primary key is used to identify the element, if you have a "Person" you would like to have a Personal Identification Number ( SSN or such ) which is Primary to your Person.
On the other hand, the person might have an e-mail which is unique, but doensn't identify the person.
I always have Primary Keys, even in relationship tables ( the mid-table / connection table ) I might have them. Why? Well I like to follow a standard when coding, if the "Person" has an identifier, the Car has an identifier, well, then the Person -> Car should have an identifier as well!
This article:
may be if interest to you.
In a couple of words, this query:
SELECT d1.short_code
FROM domain1 d1
LEFT JOIN
domain2 d2
ON d2.short_code = d1.short_code
WHERE d2.short_code IS NULL
will work but it is less efficient than a NOT NULL
(or NOT EXISTS
) construct.
You can also use this:
SELECT short_code
FROM domain1
EXCEPT
SELECT short_code
FROM domain2
This is using neither NOT IN
nor WHERE
(and even no joins!), but this will remove all duplicates on domain1.short_code
if any.
You could use limitTo
filter with -1
for find the last element
Example :
<div ng-repeat="friend in friends | limitTo: -1">
{{friend.name}}
</div>
No, as of Notepad++ 5.6.2, this doesn't seem to be possible. Although column selection (Alt+Selection) is possible, multiple selections are obviously not implemented and thus also not supported by the search function.
If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:
IdentityFile ~/.foo/identity
man ssh_config
to find other config options.
In java... using for loop:
import java.util.Scanner;
/**
*
* @author MD SADDAM HUSSAIN */
public class Learn {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
char process[] = input.toCharArray();
boolean status = false;
int index = 0;
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process.length; j++) {
if (i == j) {
continue;
} else {
if (process[i] == process[j]) {
status = true;
index = i;
break;
} else {
status = false;
}
}
}
if (status) {
System.out.print("" + process[index]);
}
}
}
}
I think a Do Until
-loop is cleaner, shorter and more appropriate here:
Public Sub SelectFirstBlankCell(col As String)
Dim Column_Index as Integer
Dim Row_Counter as
Column_Index = Range(col & 1).Column
Row_Counter = 1
Do Until IsEmpty(Cells(Row_Counter, 1))
Row_Counter = Row_Counter + 1
Loop
Cells(Row_Counter, Column_Index).Select
Here is better solution if you want to make multiple text to bold. I've improved Eitan's code. thanks Eitan.
public static SpannableStringBuilder makeSectionOfTextBold(String text, String... textToBold) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
for (String textItem :
textToBold) {
if (textItem.length() > 0 && !textItem.trim().equals("")) {
//for counting start/end indexes
String testText = text.toLowerCase(Locale.US);
String testTextToBold = textItem.toLowerCase(Locale.US);
int startingIndex = testText.indexOf(testTextToBold);
int endingIndex = startingIndex + testTextToBold.length();
if (startingIndex >= 0 && endingIndex >= 0) {
builder.setSpan(new StyleSpan(Typeface.BOLD), startingIndex, endingIndex, 0);
}
}
}
return builder;
}
See man git-add
:
-f, --force
Allow adding otherwise ignored files.
So run this
git add --force my/ignore/file.foo
See:
Is there a good interactive 3D graph library out there?
The accepted answer suggests the following program, which apparently has python bindings: http://ubietylab.net/ubigraph/
Edit
I'm not sure about the interactivity of NetworkX, but you can definitely make 3D graphs. There is at least one example in the gallery:
http://networkx.lanl.gov/examples/drawing/edge_colormap.html
And another example in the 'examples'. This one, however, requires that you have Mayavi.
http://networkx.lanl.gov/examples/3d_drawing/mayavi2_spring.html
If you have a number of files in a directory and want to store those file names into a list. Use the below code.
import os as os
import glob as glob
path = 'mypath'
file_list= []
for file in glob.glob(path):
data_file_list = os.path.basename(file)
file_list.append(data_file_list)
yes, there is:
object[] x = new object[2];
x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };
you were practically there, just the declaration of the anonymous types was a little off.
You need to put the format arguments into a tuple (add parentheses):
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)
What you currently have is equivalent to the following:
intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl
Example:
>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'
https://pypi.org/project/Pillow/
pip install Pillow
If you have both Pythons installed and want to install this for Python3:
python3 -m pip install Pillow
Specify window "features" to the open
call:
window.open(url, windowName, "height=200,width=200");
When you specify a width/height, it will open it in a new window instead of a tab.
See https://developer.mozilla.org/en-US/docs/Web/API/Window.open#Position_and_size_features for all the possible features.