The action occurs when you attempt to call an object which is not a function, as with ()
. For instance, this will produce the error:
>>> a = 5
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Class instances can also be called if they define a method __call__
One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0)
instead of [0]
Add these methods to your Activity:
private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
myServiceBinder = ((MyService.MyBinder) binder).getService();
Log.d("ServiceConnection","connected");
showServiceData();
}
public void onServiceDisconnected(ComponentName className) {
Log.d("ServiceConnection","disconnected");
myService = null;
}
};
public Handler myHandler = new Handler() {
public void handleMessage(Message message) {
Bundle data = message.getData();
}
};
public void doBindService() {
Intent intent = null;
intent = new Intent(this, BTService.class);
// Create a new Messenger for the communication back
// From the Service to the Activity
Messenger messenger = new Messenger(myHandler);
intent.putExtra("MESSENGER", messenger);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}
And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.
@Override
protected void onResume() {
Log.d("activity", "onResume");
if (myService == null) {
doBindService();
}
super.onResume();
}
@Override
protected void onPause() {
//FIXME put back
Log.d("activity", "onPause");
if (myService != null) {
unbindService(myConnection);
myService = null;
}
super.onPause();
}
Note, that when binding to a service only the onCreate()
method is called in the service class.
In your Service class you need to define the myBinder method:
private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;
@Override
public IBinder onBind(Intent arg0) {
Bundle extras = arg0.getExtras();
Log.d("service","onBind");
// Get messager from the Activity
if (extras != null) {
Log.d("service","onBind with extra");
outMessenger = (Messenger) extras.get("MESSENGER");
}
return mBinder;
}
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
After you defined these methods you can reach the methods of your service at your Activity:
private void showServiceData() {
myServiceBinder.myMethod();
}
and finally you can start your service when some event occurs like _BOOT_COMPLETED_
public class MyReciever extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("android.intent.action.BOOT_COMPLETED")) {
Intent service = new Intent(context, myService.class);
context.startService(service);
}
}
}
note that when starting a service the onCreate()
and onStartCommand()
is called in service class
and you can stop your service when another event occurs by stopService()
note that your event listener should be registerd in your Android manifest file:
<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
The easiest way to do this is just to add zero to your result.
i.e.
$A=($row['SUM'Price']+0);
echo $A;
hope this helps!!
This is the modified version that I put in my code (I'm using .Net 4.5) but I think it should work on 4.0 too.
public void AppendText(string text, Color color, bool addNewLine = false)
{
box.SuspendLayout();
box.SelectionColor = color;
box.AppendText(addNewLine
? $"{text}{Environment.NewLine}"
: text);
box.ScrollToCaret();
box.ResumeLayout();
}
Differences with original one:
non jQuery quick and dirty answer:
function setChangeListener (div, listener) {
div.addEventListener("blur", listener);
div.addEventListener("keyup", listener);
div.addEventListener("paste", listener);
div.addEventListener("copy", listener);
div.addEventListener("cut", listener);
div.addEventListener("delete", listener);
div.addEventListener("mouseup", listener);
}
var div = document.querySelector("someDiv");
setChangeListener(div, function(event){
console.log(event);
});
JSONB is a "better" version of JSON.
Let's look at an example:
SELECT '{"c":0, "a":2,"a":1}'::json, '{"c":0, "a":2,"a":1}'::jsonb;
json | jsonb
------------------------+---------------------
{"c":0, "a":2,"a":1} | {"a": 1, "c": 0}
(1 row)
In general, one should prefer JSONB , unless there are specialized needs, such as legacy assumptions about ordering of object keys.
1) in a query window in SQL Server Management Studio, run the command:
SET SHOWPLAN_ALL ON
2) run your slow query
3) your query will not run, but the execution plan will be returned. store this output
4) run your fast version of the query
5) your query will not run, but the execution plan will be returned. store this output
6) compare the slow query version output to the fast query version output.
7) if you still don't know why one is slower, post both outputs in your question (edit it) and someone here can help from there.
Another way to find it quickly via the GUI on any windows system:
create a text file, type a word or two (or random text) in it, and save it.
Right-click on the file to show Properties.
"Size on disk" = allocation unit.
When you parse the JSON representation, it'll become a JavaScript array of objects.
Because of this, you can use the .length
property of the JavaScript array to see how many elements are contained, and use a for
loop to enumerate it.
ul li + li:before
{
content:url(imgs/separator.gif);
}
I'd recommend using http://shapecatcher.com/ to help search for unicode characters. It allows you to draw the shape you're after, and then lists the closest matches to that shape.
I put the year and the number series of my app example 2014-01
To add/subtract from a DATE
, you have 2 options :
Method #1 :
The easiest way is to use +
and -
to add/subtract days, hours, minutes, seconds, etc.. from a DATE
, and ADD_MONTHS()
function to add/subtract months and years from a DATE
. Why ? That's because from days, you can get hours and any smaller unit (1 hour = 1/24 days), (1 minute = 1/1440 days), etc... But you cannot get months and years, as that depends on the month and year themselves, hence ADD_MONTHS()
and no add_years(), because from months, you can get years (1 year = 12 months).
Let's try them :
SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints current date: 19-OCT-2019 20:42:02
SELECT TO_CHAR((SYSDATE + 1/24), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 hour: 19-OCT-2019 21:42:02
SELECT TO_CHAR((SYSDATE + 1/1440), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 minute: 19-OCT-2019 20:43:02
SELECT TO_CHAR((SYSDATE + 1/86400), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 second: 19-OCT-2019 20:42:03
-- Same goes for subtraction.
SELECT SYSDATE FROM dual; -- prints current date: 19-OCT-19
SELECT ADD_MONTHS(SYSDATE, 1) FROM dual; -- prints date + 1 month: 19-NOV-19
SELECT ADD_MONTHS(SYSDATE, 12) FROM dual; -- prints date + 1 year: 19-OCT-20
SELECT ADD_MONTHS(SYSDATE, -3) FROM dual; -- prints date - 3 months: 19-JUL-19
Method #2 : Using INTERVAL
s, you can or subtract an interval (duration) from a date easily. More than that, you can combine to add or subtract multiple units at once (e.g 5 hours and 6 minutes, etc..)
Examples :
SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints current date: 19-OCT-2019 21:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' HOUR), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 hour: 19-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' MINUTE), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 minute: 19-OCT-2019 21:35:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 second: 19-OCT-2019 21:34:16
SELECT TO_CHAR((SYSDATE + INTERVAL '01:05:00' HOUR TO SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 hour and 5 minutes: 19-OCT-2019 22:39:15
SELECT TO_CHAR((SYSDATE + INTERVAL '3 01' DAY TO HOUR), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 3 days and 1 hour: 22-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE - INTERVAL '10-3' YEAR TO MONTH), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date - 10 years and 3 months: 19-JUL-2009 21:34:15
You are almost there use
mysql> \. c:/nitm.sql;
You may also access help by
mysql> \?
With async you just do:
await Task.Run(() => do some stuff);
// continue doing stuff on the same context as before.
// while it is the default it is nice to be explicit about it with:
await Task.Run(() => do some stuff).ConfigureAwait(true);
However:
await Task.Run(() => do some stuff).ConfigureAwait(false);
// continue doing stuff on the same thread as the task finished on.
In your terminal/console (only Linux, in windows you need Putty)
ssh user@ip
php -i | grep "Loaded Configuration File"
And it will show you something like this Loaded Configuration File => /etc/php.ini
.
ALTERNATIVE METHOD
You can make a php file on your website, which run: <?php phpinfo(); ?>
, and you can see the php.ini location on the line with: "Loaded Configuration File".
Update This command gives the path right away
cli_php_ini=php -i | grep /.+/php.ini -oE #ref. https://stackoverflow.com/a/15763333/248616
php_ini="${cli_php_ini/cli/apache2}" #replace cli by apache2 ref. https://stackoverflow.com/a/13210909/248616
The only valid answer would be the pause
command.
Though this does not wait specifically for the 'ENTER' key, it waits for any key that is pressed.
And just in case you want it convenient for the user, pause
is the best option.
MySQL provides comprehensive character set management that can help with this kind of problem.
SELECT whatever
FROM tableName
WHERE columnToCheck <> CONVERT(columnToCheck USING ASCII)
The CONVERT(col USING charset)
function turns the unconvertable characters into replacement characters. Then, the converted and unconverted text will be unequal.
See this for more discussion. https://dev.mysql.com/doc/refman/8.0/en/charset-repertoire.html
You can use any character set name you wish in place of ASCII. For example, if you want to find out which characters won't render correctly in code page 1257 (Lithuanian, Latvian, Estonian) use CONVERT(columnToCheck USING cp1257)
ORA-03113: end-of-file on communication channel
Is the database letting you know that the network connection is no more. This could be because:
For 1) (firewall) search tahiti.oracle.com for SQLNET.EXPIRE_TIME
. This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live.
For 1) (network) speak to your network admin (connection could be unreliable)
For 2) Check the alert.log
for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file.
Support issues can be raised at metalink.oracle.com with a suitable Customer Service Identifier (CSI)
Here is a small function I wrote to try all the colorschemes in $VIMRUNTIME/colors directory.
Add the below function to your vimrc, then open your source file and call the function from command.
function! DisplayColorSchemes()
let currDir = getcwd()
exec "cd $VIMRUNTIME/colors"
for myCol in split(glob("*"), '\n')
if myCol =~ '\.vim'
let mycol = substitute(myCol, '\.vim', '', '')
exec "colorscheme " . mycol
exec "redraw!"
echo "colorscheme = ". myCol
sleep 2
endif
endfor
exec "cd " . currDir
endfunction
I've been frustrated for long by Windows code page issues, and the C programs portability and localisation issues they cause. The previous posts have detailed the issues at length, so I'm not going to add anything in this respect.
To make a long story short, eventually I ended up writing my own UTF-8 compatibility library layer over the Visual C++ standard C library. Basically this library ensures that a standard C program works right, in any code page, using UTF-8 internally.
This library, called MsvcLibX, is available as open source at https://github.com/JFLarvoire/SysToolsLib. Main features:
More details in the MsvcLibX README on GitHub, including how to build the library and use it in your own programs.
The release section in the above GitHub repository provides several programs using this MsvcLibX library, that will show its capabilities. Ex: Try my which.exe tool with directories with non-ASCII names in the PATH, searching for programs with non-ASCII names, and changing code pages.
Another useful tool there is the conv.exe program. This program can easily convert a data stream from any code page to any other. Its default is input in the Windows code page, and output in the current console code page. This allows to correctly view data generated by Windows GUI apps (ex: Notepad) in a command console, with a simple command like: type WINFILE.txt | conv
This MsvcLibX library is by no means complete, and contributions for improving it are welcome!
Judging from your example, shouldn't it be {% url myproject.login.views.login_view %}
and end of story? (replace myproject
with your actual project name)
With the help of jquery, it can be done like this. Code:
$("input.custom-file-input").on("change",function(){if(this.files.length){var filename=this.file[0].name;if(filename.length>23){filename=filename.substr(0,11)+"..."+filename.substr(-10);}$(this).siblings(".custom-file-label").text(filename);}});
For me, i forget to add AUTO_INCREMENT to my primary field and inserted data without id.
It is not possible at this point (unless the author of the image explicitly included the Dockerfile).
However, it is definitely something useful! There are two things that will help to obtain this feature.
In order to use php in .html files, you must associate them with your PHP processor in your HTTP server's config file. In Apache, that looks like this:
AddHandler application/x-httpd-php .html
A couple ways I can think of
import {take, publish} from 'rxjs/operators'
import {concat} from 'rxjs'
//Method one
var one = someObservable.pipe(take(1));
var two = someOtherObservable.pipe(take(1));
concat(one, two).subscribe(function() {/*do something */});
//Method two, if they need to be separate for some reason
var one = someObservable.pipe(take(1));
var two = someOtherObservable.pipe(take(1), publish());
two.subscribe(function(){/*do something */});
one.subscribe(function(){/*do something */}, null, two.connect.bind(two));
[examine all threads backtraces to find the culprit]
Even fully expanded call stack can still hide the actual offending line of code from you when you use more than one thread!
Example: One thread is iterating ruby Hash, other thread is trying to modify it. BOOM! Exception! And the problem with the stack trace you get while trying to modify 'busy' hash is that it shows you chain of functions down to the place where you're trying to modify hash, but it does NOT show who's currently iterating it in parallel (who owns it)! Here's the way to figure that out by printing stack trace for ALL currently running threads. Here's how you do this:
# This solution was found in comment by @thedarkone on https://github.com/rails/rails/issues/24627
rescue Object => boom
thread_count = 0
Thread.list.each do |t|
thread_count += 1
err_msg += "--- thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace begin \n"
# Lets see if we are able to pin down the culprit
# by collecting backtrace for all existing threads:
err_msg += t.backtrace.join("\n")
err_msg += "\n---thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace end \n"
end
# and just print it somewhere you like:
$stderr.puts(err_msg)
raise # always reraise
end
The above code snippet is useful even just for educational purposes as it can show you (like x-ray) how many threads you actually have (versus how many you thought you have - quite often those two are different numbers ;)
If you want the second highest number you can use
=LARGE(E4:E9;2)
although that doesn't account for duplicates so you could get the same result as the Max
If you want the largest number that is smaller than the maximum number you can use this version
=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)
You are referring to the section "2.3.5 Deploying the demo app" of this "Ruby on Rails Tutorial ":
In section 2.3.1 Planning the application, note that they did:
$ git remote add origin [email protected]:<username>/demo_app.git
$ git push origin master
That is why a simple git push
worked (using here an ssh address).
Did you follow that step and made that first push?
www.github.com/levelone/demo_app
wouldn't be a writable URI for pushing to a GitHub repo.
https://[email protected]/levelone/demo_app.git
should be more appropriate.
Check what git remote -v returns, and if you need to replace the remote address, as described in GitHub help page, use git remote --set-url
.
git remote set-url origin https://[email protected]/levelone/demo_app.git
or
git remote set-url origin [email protected]:levelone/demo_app.git
Windows API and Windows SDK if you want to build everything yourself (or) Windows API and Visual C Express. Get the 2008 edition. This is a full blown IDE and a remarkable piece of software by Microsoft for Windows development.
All operating systems are written in C. So, any application, console/GUI you write in C is the standard way of writing for the operating system.
If the extra entries in the log bother you but an extra second of start-up time doesn't, just add this to your logging.properties
and forget about it:
org.apache.jasper.servlet.TldScanner.level = WARNING
does R stop no matter the N value you use? try to use small values and see if it's the mvrnorm function that is the issue or you could simply loop it on subsets. Insert the gc()
function in the loop to free some RAM continuously
What comes after the "Where" is a constraint on the generic type T you declared, so:
class means that the T should be a class and not a value type or a struct.
new() indicates that the T class should have a public parameter-free default constructor defined.
In my case, I was using wrong linking.
It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to "see" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]
Populate the text box values in the Page Init event as opposed to using the Postback.
protected void Page_Init(object sender, EventArgs e)
{
DropDownTitle();
}
For those using jQuery there's a convenient method: http://api.jquery.com/change/
Because the number can be up to 15 digits, you'll need to cast to an 64 bit (8-byte) integer. Try this:
SELECT * FROM table
WHERE myint = mytext::int8
The ::
cast operator is historical but convenient. Postgres also conforms to the SQL standard syntax
myint = cast ( mytext as int8)
If you have literal text you want to compare with an int
, cast the int
to text:
SELECT * FROM table
WHERE myint::varchar(255) = mytext
Even better!
long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds
Read the documentation about nanoTime()!
You know, all this stuff about the joins and the 'complex transactions' -- but it was Monty himself who, many years ago, explained away the "need" for COMMIT / ROLLBACK, saying that 'all that is done in the logic classes (and not the database) anyway' -- so it's the same thing all over again. What is needed is a dumb yet incredibly tidy and fast data storage/retrieval engine, for 99% of what the web apps do.
A classic "or" would be |
. For example, ab|de
would match either side of the expression.
However, for something like your case you might want to use the ?
quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:
\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+
This pattern will match:
\d+
: One or more numbers.\s+
: One or more whitespaces.[A-Z\s]+
: One or more uppercase characters or space characters\s+
: One or more whitespaces.[A-Z][A-Za-z\s]+
: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.If you'd like a more static check, e.g. indeed only match ABC
and A ABC
, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):
\d (?:ABC|A ABC) Street
Or another alternative using a quantifier:
\d (?:A )?ABC Street
Ubuntu 11.10 doesn't have maven3 in repo.
Follow below step to install maven3 on ubuntu 11.10
sudo add-apt-repository ppa:natecarlson/maven3
sudo apt-get update && sudo apt-get install maven3
Open terminal: mvn3 -v
if you want mvn as a binary then execute below script:
sudo ln -s /usr/bin/mvn3 /usr/bin/mvn
I hope this will help you.
Thanks, Rajam
How about the following?
irb(main):003:0> my_string = "Some text with a carriage return \r"
=> "Some text with a carriage return \r"
irb(main):004:0> my_string.gsub(/\r/,"")
=> "Some text with a carriage return "
irb(main):005:0>
Or...
irb(main):007:0> my_string = "Some text with a carriage return \r\n"
=> "Some text with a carriage return \r\n"
irb(main):008:0> my_string.gsub(/\r\n/,"\n")
=> "Some text with a carriage return \n"
irb(main):009:0>
Once you have the source trees, e.g.
diff -ENwbur repos1/ repos2/
Even better
diff -ENwbur repos1/ repos2/ | kompare -o -
and have a crack at it in a good gui tool :)
If you want to use hex codes, you should add -e
option to enable interpretation of backslash escapes by echo (but the result is the same as with echo
CtrlRCtrlB). And as wallyk said, you probably want to add -n
to prevent the output of a newline:
echo -en '\x12\x02' > /dev/ttyS0
Also make sure that /dev/ttyS0
is the port you want.
For those still getting this error, adding encode("utf-8")
to soup
will also fix this.
soup = BeautifulSoup(html_doc, 'html.parser').encode("utf-8")
print(soup)
You can increase security in authentication process by using JWT (JSON Web Tokens) and SSL/HTTPS.
The Basic Auth / Session ID can be stolen via:
By using JWT you're encrypting the user's authentication details and storing in the client, and sending it along with every request to the API, where the server/API validates the token. It can't be decrypted/read without the private key (which the server/API stores secretly) Read update.
The new (more secure) flow would be:
Updated 30.07.15:
JWT payload/claims can actually be read without the private key (secret) and it's not secure to store it in localStorage. I'm sorry about these false statements. However they seem to be working on a JWE standard (JSON Web Encryption).
I implemented this by storing claims (userID, exp) in a JWT, signed it with a private key (secret) the API/backend only knows about and stored it as a secure HttpOnly cookie on the client. That way it cannot be read via XSS and cannot be manipulated, otherwise the JWT fails signature verification. Also by using a secure HttpOnly cookie, you're making sure that the cookie is sent only via HTTP requests (not accessible to script) and only sent via secure connection (HTTPS).
Updated 17.07.16:
JWTs are by nature stateless. That means they invalidate/expire themselves. By adding the SessionID in the token's claims you're making it stateful, because its validity doesn't now only depend on signature verification and expiry date, it also depends on the session state on the server. However the upside is you can invalidate tokens/sessions easily, which you couldn't before with stateless JWTs.
For a PRIMARY KEY
, an index will be created with the following message:
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "index" for table "table"
For a FOREIGN KEY
, the constraint will not be created if there is no index on the referenced table.
An index on referencing table is not required (though desired), and therefore will not be implicitly created.
Aggregation of all postgres sessions per their status (how many are idle, how many doing something...)
select state, count(*) from pg_stat_activity where pid <> pg_backend_pid() group by 1 order by 1;
For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
The .row
is meant to be used inside a container
. Since the container
has padding to adjust the negative margin in the .row
, grid columns used inside the .row
can then adjust to the full width of the container. See the Bootstrap docs: http://getbootstrap.com/css/#grid
Here's an example to illustrate: http://bootply.com/131054
So, a better solution may for you to place your .row
inside a .container
or .container-fluid
For primitive array types, you would have to write a reverse sort algorithm:
Alternatively, you can convert your int[]
to Integer[]
and write a comparator:
public class IntegerComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
}
or use Collections.reverseOrder()
since it only works on non-primitive array types.
and finally,
Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());
//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);
Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.
I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.
EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/
Try this:
if( $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
// authenticated (NON anonymous)
}
Further information:
"Anonymous users are technically authenticated, meaning that the isAuthenticated() method of an anonymous user object will return true. To check if your user is actually authenticated, check for the IS_AUTHENTICATED_FULLY role."
I think the exception safety part of mr mpark's answer is still a valid concern. when creating a shared_ptr like this: shared_ptr< T >(new T), the new T may succeed, while the shared_ptr's allocation of control block may fail. in this scenario, the newly allocated T will leak, since the shared_ptr has no way of knowing that it was created in-place and it is safe to delete it. or am I missing something? I don't think the stricter rules on function parameter evaluation help in any way here...
composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist
And then you probably need to install all of vendor packages, so
composer install
This one-liner also handles nested objects and JSON.stringify
them as needed:
let qs = Object.entries(obj).map(([k, v]) => `${k}=${encodeURIComponent(typeof (v) === "object" ? JSON.stringify(v) : v)}`).join('&')
function final_submit1() {
var city = $("#city").val();
var airport = $("#airport").val();
var vehicle = $("#vehicle").val();
if(city && airport){
$.ajax({
type:"POST",
cache:false,
data:{"city": city,"airport": airport},
url:'http://airportLimo/ajax-car-list',
success: function (html) {
console.log(html);
//$('#add').val('data sent');
//$('#msg').html(html);
$('#pprice').html("Price: $"+html);
}
});
}
}
To assign value to a single Form control/individually, I propose to use setValue in the following way:
this.editqueForm.get('user').setValue(this.question.user);
this.editqueForm.get('questioning').setValue(this.question.questioning);
You can remove the warning by adding the below code in <intent-filter>
inside <activity>
<action android:name="android.intent.action.VIEW" />
You can pass variables using this...
$status =1;
$info = JOBS::where(function($query) use ($status){
$query->where('status',$status);
})->get();
print_r($info);
Gallery is the best solution, i have tried it. I was working on one mail app, in which mails in the inbox where displayed as listview, i wanted an horizontal view, i just converted listview to gallery and everything worked fine as i needed without any errors. For the scroll effect i enabled gesture listener for the gallery. I hope this answer may help u.
When you export a class module and open the file in Notepad, you'll notice, near the top, a bunch of hidden attributes (the VBE doesn't display them, and doesn't expose functionality to tweak most of them either). One of them is VB_PredeclaredId
:
Attribute VB_PredeclaredId = False
Set it to True
, save, and re-import the module into your VBA project.
Classes with a PredeclaredId
have a "global instance" that you get for free - exactly like UserForm
modules (export a user form, you'll see its predeclaredId attribute is set to true).
A lot of people just happily use the predeclared instance to store state. That's wrong - it's like storing instance state in a static class!
Instead, you leverage that default instance to implement your factory method:
[Employee
class]
'@PredeclaredId
Option Explicit
Private Type TEmployee
Name As String
Age As Integer
End Type
Private this As TEmployee
Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As Employee
With New Employee
.Name = emplName
.Age = emplAge
Set Create = .Self 'returns the newly created instance
End With
End Function
Public Property Get Self() As Employee
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Age() As String
Age = this.Age
End Property
Public Property Let Age(ByVal value As String)
this.Age = value
End Property
With that, you can do this:
Dim empl As Employee
Set empl = Employee.Create("Johnny", 69)
Employee.Create
is working off the default instance, i.e. it's considered a member of the type, and invoked from the default instance only.
Problem is, this is also perfectly legal:
Dim emplFactory As New Employee
Dim empl As Employee
Set empl = emplFactory.Create("Johnny", 69)
And that sucks, because now you have a confusing API. You could use '@Description
annotations / VB_Description
attributes to document usage, but without Rubberduck there's nothing in the editor that shows you that information at the call sites.
Besides, the Property Let
members are accessible, so your Employee
instance is mutable:
empl.Name = "Jane" ' Johnny no more!
The trick is to make your class implement an interface that only exposes what needs to be exposed:
[IEmployee
class]
Option Explicit
Public Property Get Name() As String : End Property
Public Property Get Age() As Integer : End Property
And now you make Employee
implement IEmployee
- the final class might look like this:
[Employee
class]
'@PredeclaredId
Option Explicit
Implements IEmployee
Private Type TEmployee
Name As String
Age As Integer
End Type
Private this As TEmployee
Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As IEmployee
With New Employee
.Name = emplName
.Age = emplAge
Set Create = .Self 'returns the newly created instance
End With
End Function
Public Property Get Self() As IEmployee
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Age() As String
Age = this.Age
End Property
Public Property Let Age(ByVal value As String)
this.Age = value
End Property
Private Property Get IEmployee_Name() As String
IEmployee_Name = Name
End Property
Private Property Get IEmployee_Age() As Integer
IEmployee_Age = Age
End Property
Notice the Create
method now returns the interface, and the interface doesn't expose the Property Let
members? Now calling code can look like this:
Dim empl As IEmployee
Set empl = Employee.Create("Immutable", 42)
And since the client code is written against the interface, the only members empl
exposes are the members defined by the IEmployee
interface, which means it doesn't see the Create
method, nor the Self
getter, nor any of the Property Let
mutators: so instead of working with the "concrete" Employee
class, the rest of the code can work with the "abstract" IEmployee
interface, and enjoy an immutable, polymorphic object.
I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.
Here's 2 sorts I came up with my roommate in college
1) Check the order 2) Maybe a miracle happened, go to 1
and
1) check if it is in order, if not 2) put each element into a packet and bounce it off a distant server back to yourself. Some of those packets will return in a different order, so go to 1
Try replacing the string literal for date '1989-12-09'
with TO_DATE('1989-12-09','YYYY-MM-DD')
Angular 6.0.0
https://github.com/angular/angular/blob/master/CHANGELOG.md#610-2018-07-25
introduced a KeyValuePipe
See also https://angular.io/api/common/KeyValuePipe
@Component({ selector: 'keyvalue-pipe', template: `<span> <p>Object</p> <div *ngFor="let item of object | keyvalue"> {{item.key}}:{{item.value}} </div> <p>Map</p> <div *ngFor="let item of map | keyvalue"> {{item.key}}:{{item.value}} </div> </span>` }) export class KeyValuePipeComponent { object: {[key: number]: string} = {2: 'foo', 1: 'bar'}; map = new Map([[2, 'foo'], [1, 'bar']]); }
original
You can use a pipe
@Pipe({ name: 'keys', pure: false })
export class KeysPipe implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value)//.map(key => value[key]);
}
}
<div *ngFor="let key of objs | keys">
Try this:
delete from your_table;
delete from sqlite_sequence where name='your_table';
SQLite keeps track of the largest ROWID that a table has ever held using the special
SQLITE_SEQUENCE
table. TheSQLITE_SEQUENCE
table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.
Compilers translate
for (a; b; c)
{
...
}
to
a;
while(b)
{
...
end:
c;
}
So in your case (post/pre- increment) it doesn't matter.
EDIT: continues are simply replaced by goto end;
Remove all spaces in string
// Remove only spaces
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/ /g,'');
"
Textwithspaces1111
andsome
breaklines
"
// Remove spaces and breaklines
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/\s/g,'');
"Textwithspaces1111andsomebreaklines"
every() function check if all elements of an array
const checkArr = a => a.every( val => val === a[0] )
checkArr(['a','a','a']) // true
Try this, it must be work, otherwise you need to print the error to specify your problem
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from Users WHERE UserName LIKE '$username'";
$result = mysql_query($sql,$con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
I just tried the same and came up with following solution:
public enum Countries {
TEXAS,
FLORIDA,
OKLAHOMA,
KENTUCKY;
private static Countries[] list = Countries.values();
public static Countries getCountry(int i) {
return list[i];
}
public static int listGetLastIndex() {
return list.length - 1;
}
}
The class has it's own values saved inside an array, and I use the array to get the enum at indexposition. As mentioned above arrays begin to count from 0, if you want your index to start from '1' simply change these two methods to:
public static String getCountry(int i) {
return list[(i - 1)];
}
public static int listGetLastIndex() {
return list.length;
}
Inside my Main I get the needed countries-object with
public static void main(String[] args) {
int i = Countries.listGetLastIndex();
Countries currCountry = Countries.getCountry(i);
}
which sets currCountry to the last country, in this case Countries.KENTUCKY.
Just remember this code is very affected by ArrayOutOfBoundsExceptions if you're using hardcoded indicies to get your objects.
<br>
worked for me.
On top of what the others have already stated, some sort of server-side scripting is necessary in order for the server to read and save the file.
Using PHP might be a good choice, but you're free to use any server-side scripting language. http://www.w3schools.com/php/php_file_upload.asp may be of use on that end.
The [:-1]
removes the last element. Instead of
a[3:-1]
write
a[3:]
You can read up on Python slicing notation here: Explain Python's slice notation
NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.
you can do it only in one line as below:
$cnt = mysql_num_rows(mysql_query("SELECT COUNT(1) FROM TABLE"));
echo $cnt;
v4l support has been dropped in recent kernel versions (including the one shipped with Ubuntu 11.04).
EDIT: Your question is connected to a recent message that was sent to the OpenCV users group, which has instructions to compile OpenCV 2.2 in Ubuntu 11.04. Your approach is not ideal.
Just adding a little more info.
JPA manages the version under the hood for you, however it doesn't do so when you update your record via JPAUpdateClause
, in such cases you need to manually add the version increment to the query.
Same can be said about updating via JPQL, i.e. not a simple change to the entity, but an update command to the database even if that is done by hibernate
Pedro
Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.
The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.
if you are calling from static
method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
You can show all commits that you have locally but not upstream with
git log @{u}..
@{u}
or @{upstream}
means the upstream branch of the current branch (see git rev-parse --help
or git help revisions
for details).
This is the best option. As said Michal Gasek (first answer), since the pull request was merged (https://github.com/ansible/ansible/pull/8651), we are able to set permanent environment variables easily by play level.
- hosts: all
roles:
- php
- nginx
environment:
MY_ENV_VARIABLE: whatever_value
To fix a problem, in my case: I checked Git folder under c:\program files\Git. I didn't find git.exe, so delete the Git folder and install it again. Declare them in the environment variables as shown above. the problem will be solved.
Another option for MS SQL is to replace the select
query here with the query you want the types for:
declare @sql varchar(4000);
set @sql = 'select ''hi'' as greeting';
select * from master.sys.dm_exec_describe_first_result_set (@sql, Null, 0);
kwargs is just a dictionary that is added to the parameters.
A dictionary can contain key, value pairs. And that are the kwargs. Ok, this is how.
The what for is not so simple.
For example (very hypothetical) you have an interface that just calls other routines to do the job:
def myDo(what, where, why):
if what == 'swim':
doSwim(where, why)
elif what == 'walk':
doWalk(where, why)
...
Now you get a new method "drive":
elif what == 'drive':
doDrive(where, why, vehicle)
But wait a minute, there is a new parameter "vehicle" -- you did not know it before. Now you must add it to the signature of the myDo-function.
Here you can throw kwargs into play -- you just add kwargs to the signature:
def myDo(what, where, why, **kwargs):
if what == 'drive':
doDrive(where, why, **kwargs)
elif what == 'swim':
doSwim(where, why, **kwargs)
This way you don't need to change the signature of your interface function every time some of your called routines might change.
This is just one nice example you could find kwargs helpful.
Reset all selection fields to the default option, where the attribute selected is defined.
$("#reset").on("click", function () {
// Reset all selections fields to default option.
$('select').each( function() {
$(this).val( $(this).find("option[selected]").val() );
});
});
Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.
Here are some providers which have a "free-tier" (may change in future):
Open source solutions:
Did you just try
$('#datebox li a').on('click', function(){
//$('#datebox').val($(this).text());
alert($(this).text());
});
It works for me :)
You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.
You can have a look at here for more information.
Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux
instead of Other.
After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.
Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.
Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.
Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.
In VirtualBox screen, go to Devices>USB devices. Select your dongle.
Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.
Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.
Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .
You can get it done using moment.js file.
Its simple you have just mention the place of the timezone.
Example: If you to convert your datetime to Asia/Kolkata timezone,you have to just mention the name of the timezone place obtained from moment.js
var UTCDateTime="Your date obtained from UTC";_x000D_
var ISTleadTime=(moment.tz(UTCDateTime, "Africa/Abidjan")).tz("Asia/Kolkata").format('YYYY-MM-DD LT');
_x000D_
It appears Microsoft now stores them in a SQLite database file called plum.sqlite located here:
C:\Users\%username%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite
One solution is to enclose every word in a span tag using script. Then if the Y dimension of a given span tag is less than that of it's immediate predecessor then a line break has occurred.
input.next() takes in the first whitsepace-delimited word of the input string. So by design it does what you've described. Try input.nextLine()
.
When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.
But there are more important differences on the receiving side of things. When the receiver does a recv
(or read
) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.
Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.
I ran into similar problems, you might be able to get it to work using a similar method.
First, try this with your current configuration, exclude httpclient
from httpmime
:
dependencies {
compile 'com.google.android.gms:play-services:+'
compile ('org.apache.httpcomponents:httpmime:4.2.6'){
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient:4.2.6'
}
In my case, I fixed it by using the following jars :
Then, in the build.gradle, excluding httpclient
from httpmime
:
dependencies {
compile 'com.google.android.gms:play-services:+'
compile('org.apache.httpcomponents:httpmime:4.3.5') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
}
You can use pushover if you don't want to create your own native app: https://pushover.net/
There are two problems in your code:
visibility
and not visiblity
..style
property.It's easy to fix. Simple replace this:
document.getElementById("remember").visiblity
with this:
document.getElementById("remember").style.visibility
final Calendar newCalendar = Calendar.getInstance();
final DatePickerDialog StartTime = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
activitydate.setText(dateFormatter.format(newDate.getTime()));
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
btn_checkin.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
StartTime.show():
});
You could also take a look at the DatePeriod class:
$period = new DatePeriod(
new DateTime('2010-10-01'),
new DateInterval('P1D'),
new DateTime('2010-10-05')
);
Which should get you an array with DateTime objects.
To iterate
foreach ($period as $key => $value) {
//$value->format('Y-m-d')
}
for example:
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="42dp"
android:maxHeight="42dp"
android:scaleType="fitCenter"
android:layout_marginLeft="3dp"
android:src="@drawable/icon"
/>
Add property android:scaleType="fitCenter"
and android:adjustViewBounds="true"
.
When you change count = count + 1
to count = count + 3
or count = count + 9
, count
will never be equal to 100. At the very best it'll be 99. That's not enough.
What you've got here is the classic case of infinite loop: count
is never equal to 100 (sure, at some point it'll be greater than 100, but your while
loop doesn't check for this condition) and the while
loop goes on and on.
What you want is probably:
while count < 100: # Or <=, if you feel like printing a hundred.
Not:
while count != 0: # Spaces around !=. Makes Guido van Rossum happy.
Now the loop will terminate when count >= 100
.
Take a look at Python documentation.
Request class doesn't offer a method that would return exactly what you need. But you can easily get it by concatenating results of 2 other methods:
echo (Request::getPathInfo() . (Request::getQueryString() ? ('?' . Request::getQueryString()) : '');
PDFBox is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found here.
It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are both inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!
Itext is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.
There is only one way from what I am aware.
Have 2 images, first a jpeg with first frame(or whatever you want) of the gif and the actual gif.
Load the page with the jpeg in place and on mouse over replace the jpeg with the gif. You can preload the gifs if you want or if they are of big size show a loading while the gif is loading and then replace the jpeg with it.
If you whant it to bi linear as in have the gif play on mouse over, stop it on mouse out and then resume play from the frame you stopped, then this cannot be done with javascript+gif combo.
Use database field type BLOB to store arrays.
Ref: http://us.php.net/manual/en/function.serialize.php
Return Values
Returns a string containing a byte-stream representation of value that can be stored anywhere.
Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.
Use escape characters for example this code:
var message = "I want to learn \"c#\"";
Console.WriteLine(message);
will output:
I want to learn "c#"
svn status | grep '^M' | sed -e 's/^.//' | xargs rm
svn update
Will remove any file which has been modified. I seem to remember having trouble with revert when files and directories may have been added.
Step 1: Implement an interface with your activity class
public class AuthenticatedMainActivity extends Activity implements FragmentManager.OnBackStackChangedListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
.............
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.frame_container,fragment, "First").addToBackStack(null).commit();
}
private void switchFragment(Fragment fragment){
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).addToBackStack("Tag").commit();
}
@Override
public void onBackStackChanged() {
FragmentManager fragmentManager = getFragmentManager();
System.out.println("@Class: SummaryUser : onBackStackChanged "
+ fragmentManager.getBackStackEntryCount());
int count = fragmentManager.getBackStackEntryCount();
// when a fragment come from another the status will be zero
if(count == 0){
System.out.println("again loading user data");
// reload the page if user saved the profile data
if(!objPublicDelegate.checkNetworkStatus()){
objPublicDelegate.showAlertDialog("Warning"
, "Please check your internet connection");
}else {
objLoadingDialog.show("Refreshing data...");
mNetworkMaster.runUserSummaryAsync();
}
// IMPORTANT: remove the current fragment from stack to avoid new instance
fragmentManager.removeOnBackStackChangedListener(this);
}// end if
}
}
Step 2: When you call the another fragment add this method:
String backStateName = this.getClass().getName();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
Fragment fragmentGraph = new GraphFragment();
Bundle bundle = new Bundle();
bundle.putString("graphTag", view.getTag().toString());
fragmentGraph.setArguments(bundle);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragmentGraph)
.addToBackStack(backStateName)
.commit();
For me, it said Module did not found and not worked. Finally, I found this solution and worked.
<img v-bind:src="require('@' + baseUrl + 'path/path' + obj.key +'.png')"/>
Needed to add '@' at the beginning of the local path.
a non-loop way to determine if the point was on the anti diag:
`if (x + y == n - 1)`
Other Alternatives from just renaming the file to .doc.....
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(office.11).aspx
Here is a good place to start. You can also try using this Office Open XML.
http://www.ecma-international.org/publications/standards/Ecma-376.htm
>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'
In pre-2.5 Python, you can replace datetime.strptime
with time.strptime
, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))
FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the
android:layout_gravity
attribute.Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).
A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.
(Current docs here)
A TableLayout consists of a number of
TableRow
objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.The width of a column is defined by the row with the widest cell in that column.
Note: Absolute Layout is deprecated.
on the basis of your only jQuery
tag :)
HTML
<select id="my-select">
<option value="1">This is text 1</option>
<option value="2">This is text 2</option>
<option value="3">This is text 3</option>
</select>
For text --
$(document).ready(function() {
$("#my-select").change(function() {
alert($('#my-select option:selected').html());
});
});
For value --
$(document).ready(function() {
$("#my-select").change(function() {
alert($(this).val());
});
});
As of TypeScript 2.0 you can include typings for native promises by including the following in your tsconfig.json
"compilerOptions": {
"lib": ["es5", "es2015.promise"]
}
This will include the promise declarations that comes with TypeScript without having to set the target to ES6.
Swift 3:
You can use Swifts built in functionality to find custom objects in an Array.
First you must make sure your custom object conforms to the: Equatable protocol.
class Person : Equatable { //<--- Add Equatable protocol
let name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
//Add Equatable functionality:
static func == (lhs: Person, rhs: Person) -> Bool {
return (lhs.name == rhs.name)
}
}
With Equatable functionality added to your object , Swift will now show you additional properties you can use on an array:
//create new array and populate with objects:
let p1 = Person(name: "Paul", age: 20)
let p2 = Person(name: "Mike", age: 22)
let p3 = Person(name: "Jane", age: 33)
var people = [Person]([p1,p2,p3])
//find index by object:
let index = people.index(of: p2)! //finds Index of Mike
//remove item by index:
people.remove(at: index) //removes Mike from array
To keep clean components you can use mixins.
On your component import external mixin file.
Profile.vue
import externalJs from '@client/mixins/externalJs';
export default{
mounted(){
this.externalJsFiles();
}
}
externalJs.js
import('@JSassets/js/file-upload.js').then(mod => {
// your JS elements
})
babelrc (I include this, if any get stuck on import)
{
"presets":["@babel/preset-env"],
"plugins":[
[
"module-resolver", {
"root": ["./"],
alias : {
"@client": "./client",
"@JSassets": "./server/public",
}
}
]
}
Even if you write a regular expression that matches exactly the subset "valid phone numbers" out of strings, there is no way to guarantee (by way of a regular expression) that they are valid mobile phone numbers. In several countries, mobile phone numbers are indistinguishable from landline phone numbers without at least a number plan lookup, and in some cases, even that won't help. For example, in Sweden, lots of people have "ported" their regular, landline-like phone number to their mobile phone. It's still the same number as they had before, but now it goes to a mobile phone instead of a landline.
Since valid phone numbers consist only of digits, I doubt that rolling your own would risk missing some obscure case of phone number at least. If you want to have better certainty, write a generator that takes a list of all valid country codes, and requires one of them at the beginning of the phone number to be matched by the generated regular expression.
I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.
For example:
$("#id_form").on("submit", function(){
//Code: Action (like ajax...)
return false;
})
An example using jQuery is below. Hope this helps
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
url: "https://example.com/api/",
type: "POST",
data: { apiKey: "23462", method: "example", ip: "208.74.35.5" },
dataType: "json",
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
</head>
<body>
<h1>My jQuery JSON Web Page</h1>
<div id="resultDivContainer"></div>
<button type="button" onclick="JSONTest()">JSON</button>
</body>
</html>
Firebug debug process
I'm going to assume compiling the QuickFix package does not produce a setup.py
file, but rather only compiles the Python bindings and relies on make install
to put them in the appropriate place.
In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so
extension), and add that directory to your PYTHONPATH
environmental variable e.g., add
export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH
or similar line in your shell configuration file.
A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local
. Assuming QuickFix knows to put the Python files in the appropriate site-packages
, when you do make install
, it should install the files to ~/.local/lib/pythonX.Y/site-packages
, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.
If, on the other hand, it did provide a setup.py
file, simply run
python setup.py install --user
for Python 2.6+.
This should work:
select * from syscat.tables
Use Aptana Studio 3, it's upgraded now.
You can either choose
Try online Aloha WYSIWYG Editor
But as a web-developer, I still prefer Notepad++, it has necessary code assists.
This might be late answer, yeah very late answer, but surely will help someone
Download "Eclipse IDE for Java EE Developers" Latest Stable Version
Download Google Plugin for Eclipse.zip
Select your download according to your Eclipse Version
After Downloading (don't Unzip)
Open Eclipse
Help > Install New Software > Add > Archive > Select the Downloaded Plug-in.zip
in the field "Name" enter "Google Plugin" Click ok.
How to use Google Plugin for Eclipse
File > New > Other > Web > Static Web Project > Enter Project name
Create New HTML File
Name to index.html
Select Properties of HTML File
Hit Ctrl+Space
similarly create new *.css file
Right Click on the css file > Properties > Web Content Settings > Select CSS3 Profile > ok
Hit CTRL+Space
Wooo, Yeah Start Coding.!
From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections
is the value of maxThreads
unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads
.
Simply mark any method you need to fake as virtual
(and not private). Then you will be able to create a fake that can override the method.
If you use new Mock<Type>
and you don't have a parameterless constructor then you can pass the parameters as the arguments of the above call as it takes a type of param Objects
Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:
<profile>
<id>alternateBuildDir</id>
<activation>
<property>
<name>alt.build.dir</name>
</property>
</activation>
<build>
<directory>${alt.build.dir}</directory>
</build>
</profile>
Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.
I've experienced the same problem. One of the responds to your question led me to the following idea (which worked eventually). I use Python 3.7.
# just an example
def func(): # define a function
func.y = 4 # here y is a local variable, which I want to access; func.y defines
# a method for my example function which will allow me to access
# function's local variable y
x = func.y + 8 # this is the main task for the function: what it should do
return x
func() # now I'm calling the function
a = func.y # I put it's local variable into my new variable
print(a) # and print my new variable
Then I launch this program in Windows PowerShell and get the answer 4. Conclusion: to be able to access a local function's variable one might add the name of the function and a dot before the name of the local variable (and then, of course, use this construction for calling the variable both in the function's body and outside of it). I hope this will help.
in fact for me just worked in ios disabling the scroll
<iframe src="//www.youraddress.com/" scrolling="no"></iframe>
and treating the OS via script.
Simply replace image/jpeg
with application/octet-stream
. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.
A simple JavaScript solution would be:
//var img = reference to image
var url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element,
Another method is to use a blob:
URI:
var img = document.images[0];
img.onclick = function() {
// atob to base64_decode the data-URI
var image_data = atob(img.src.split(',')[1]);
// Use typed arrays to convert the binary data to a Blob
var arraybuffer = new ArrayBuffer(image_data.length);
var view = new Uint8Array(arraybuffer);
for (var i=0; i<image_data.length; i++) {
view[i] = image_data.charCodeAt(i) & 0xff;
}
try {
// This is the recommended method:
var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
} catch (e) {
// The BlobBuilder API has been deprecated in favour of Blob, but older
// browsers don't know about the Blob constructor
// IE10 also supports BlobBuilder, but since the `Blob` constructor
// also works, there's no need to add `MSBlobBuilder`.
var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
bb.append(arraybuffer);
var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
}
// Use the URL object to create a temporary URL
var url = (window.webkitURL || window.URL).createObjectURL(blob);
location.href = url; // <-- Download!
};
@jennifer06262016, you can definitely add another filter to return the objects inside a django Queryset.
@register.filter
def get_item(Queryset):
return Queryset.your_item_key
In that case, you would type something like this {{ Queryset|index:x|get_item }} into your template to access some dictionary object. It works for me.
Gradle is in offline mode, which means that it won't go to the network to resolve dependencies.
Go to Preferences > Gradle and uncheck "Offline work".
If you are working with attached object (object loaded from the same instance of the context) you can simply use:
if (context.ObjectStateManager.GetObjectStateEntry(myEntity).State == EntityState.Detached)
{
context.MyEntities.AddObject(myEntity);
}
// Attached object tracks modifications automatically
context.SaveChanges();
If you can use any knowledge about the object's key you can use something like this:
if (myEntity.Id != 0)
{
context.MyEntities.Attach(myEntity);
context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
context.MyEntities.AddObject(myEntity);
}
context.SaveChanges();
If you can't decide existance of the object by its Id you must exectue lookup query:
var id = myEntity.Id;
if (context.MyEntities.Any(e => e.Id == id))
{
context.MyEntities.Attach(myEntity);
context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
context.MyEntities.AddObject(myEntity);
}
context.SaveChanges();
Make a list of tuples with your data and then create a DataFrame with it:
d = []
for p in game.players.passing():
d.append((p, p.team, p.passer_rating()))
pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))
A list of tuples should have less overhead than a list dictionaries. I tested this below, but please remember to prioritize ease of code understanding over performance in most cases.
Testing functions:
def with_tuples(loop_size=1e5):
res = []
for x in range(int(loop_size)):
res.append((x-1, x, x+1))
return pd.DataFrame(res, columns=("a", "b", "c"))
def with_dict(loop_size=1e5):
res = []
for x in range(int(loop_size)):
res.append({"a":x-1, "b":x, "c":x+1})
return pd.DataFrame(res)
Results:
%timeit -n 10 with_tuples()
# 10 loops, best of 3: 55.2 ms per loop
%timeit -n 10 with_dict()
# 10 loops, best of 3: 130 ms per loop
I was looking to do the same thing, and I have a work around that seems to be less complicated using the Frequency and Index functions. I use this part of the function from averaging over multiple sheets while excluding the all the 0's.
=(FREQUENCY(Start:End!B1,-0.000001)+INDEX(FREQUENCY(Start:End!B1,0),2))
if($('selector').hasClass('active')){ }
i think this will check if the selector hasClass active ...
Personally, I'd like to use range on a channel in a goroutine:
https://play.golang.org/p/qt48vvDu8cd
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
c := make(chan bool)
wg.Add(1)
go func() {
defer wg.Done()
for b := range c {
fmt.Printf("Hello %t\n", b)
}
}()
c <- true
c <- true
close(c)
wg.Wait()
}
Dave has written a great post about this: http://dave.cheney.net/2013/04/30/curious-channels.
How about std::remove()
instead:
#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());
This combination is also known as the erase-remove idiom.
I had the same problem when i have trying to read xml that was extracted from archive to memory stream.
MemoryStream SubSetupStream = new MemoryStream();
using (ZipFile archive = ZipFile.Read(zipPath))
{
archive.Password = "SomePass";
foreach (ZipEntry file in archive)
{
file.Extract(SubSetupStream);
}
}
Problem was in these lines:
XmlDocument doc = new XmlDocument();
doc.Load(SubSetupStream);
And solution is (Thanks to @Phil):
if (SubSetupStream.Position>0)
{
SubSetupStream.Position = 0;
}
Or simple try:
> sudo easy_install MySQL-python
If it gives a error like below:
EnvironmentError: mysql_config not found
, then just run this
> export PATH=$PATH:/usr/local/mysql/bin
If you made a merge on Github and are seeing the error below. You need to pull (fetch and commit) the changes from the remote server before it will recognize the merge on your local. After doing this, Git will allow you to delete the branch without giving you the error.
error: The branch 'x' is not fully merged. If you are sure you want to delete it, run 'git branch -D 'x'.
const getRandomNo = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
This function returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer) and is less than (but not equal to) max. Example
console.log(`Random no between 0 and 10 ${getRandomNo(0,10)}`)
Do you mean you want to execute code in function1 regardless of whether function2 threw an exception or not? Have you looked at the finally-block? http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.
Generally speaking, if you need to generate numbers from min
to max
(including both), you write
random.nextInt(max - min + 1) + min
Div is a block element and span is an inline element and its width depends upon the content of it self where div does not
I use windows 10, Anaconda and python 2. A combination of mentioned solutions worked for me:
Once you installed tensorflow using:
C:\Users\Laleh>conda create -n tensorflow python=3.5 # use your python version
C:\Users\Laleh>activate tensorflow
(tensorflow) C:\Users\Laleh>conda install -c conda-forge tensorflow
Then I realized tensorflow can not be imported in jupyter notebook, although it can work in commad windows. To solve this issue first I checked:
jupyter kernelspec list
I removeed the Jupyter kernelspec, useing:
jupyter kernelspec remove python2
Now, the jupyter kernelspec list is pointing to the correct kernel. Again, I activate tensorflow and installed notebook in its environment:
C:\Users\Laleh>activate tensorflow
(tensorflow)C:> conda install notebook
Also if you want to use other libraries such as matplotlib, they should be installed separately in tensorflow environment
(tensorflow)C:> conda install -c conda-forge matplotlib
Now everything works fine for me.
There is a optimized code for case when function needs to equals to empty arrays (and returning false in that case)
const objectsEqual = (o1, o2) => {
if (o2 === null && o1 !== null) return false;
return o1 !== null && typeof o1 === 'object' && Object.keys(o1).length > 0 ?
Object.keys(o1).length === Object.keys(o2).length &&
Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))
: (o1 !== null && Array.isArray(o1) && Array.isArray(o2) && !o1.length &&
!o2.length) ? true : o1 === o2;
}
Solved by removing a "async" load:
<script type="text/javascript" src="{% static 'js/my_js_file.js' %}" async></script>
changed for:
<script type="text/javascript" src="{% static 'js/my_js_file.js' %}"></script>
This works for me:
Function Test-RegistryValue
{
param($regkey, $name)
$exists = Get-ItemProperty "$regkey\$name" -ErrorAction SilentlyContinue
Write-Host "Test-RegistryValue: $exists"
if (($exists -eq $null) -or ($exists.Length -eq 0))
{
return $false
}
else
{
return $true
}
}
Do you mean something like this? JSFiddle
Attribute used:
margin-left: 50px;
Date and time input is accepted in almost any reasonable format, including ISO 8601, SQL-compatible, traditional POSTGRES, and others. For some formats, ordering of month, day, and year in date input is ambiguous and there is support for specifying the expected ordering of these fields.
In other words: just write anything and it will work.
Or check this table with all the unambiguous formats.
window.location = myUrl;
Anyway, this is not jQuery: it's plain javascript
I had good experience with SUDS https://fedorahosted.org/suds
Used their TestSuite as documentation.
The "\a" command in CSS generates a carriage return. This is CSS, not HTML, so it shall be closer to what you want: no extra markup.
In a blockquote, the example below displays both the title and the source link and separate the two with a carriage return ("\a"
):
blockquote[title][cite]:after {
content:attr(title)"\a"attr(cite)
}
You can access the same environment variables from groovy using the same names (e.g. JOB_NAME
or env.JOB_NAME
).
From the documentation:
Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):
env.MYTOOL_VERSION = '1.33' node { sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start' }
These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.
For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job
Don't use array_values
on your $row
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
array_push($res_arr_values, $row);
}
Also, the preferred way to add a value to an array is writing $array[] = $value;
, not using array_push
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$res_arr_values[] = $row;
}
And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC)
but to use mysql_fetch_assoc($result)
directly.
$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
{
$res_arr_values[] = $row;
}
DataRow has a method that is called IsNull()
that you can use to test the column if it has a null value - regarding to the null as it's seen by the database.
DataRow["col"]==null
will allways be false
.
use
DataRow r;
if (r.IsNull("col")) ...
instead.
For a manual fix to an existing cordova project
The black bars
Add this to your info.plist file. Fixing the launch image is a separate issue i.e. How to Add iPhoneX Launch Image
<key>UILaunchStoryboardName</key>
<string>CDVLaunchScreen</string>
The white bars
Set viewport-fit=cover in the meta tag
<meta name="viewport" content="initial-scale=1, width=device-width, height=device-height, viewport-fit=cover">
This works 100%.
textarea:focus, input[type="text"]:focus,textarea[type="text"]:focus, input[type="password"]:focus, input[type="datetime"]:focus, input[type="datetime-local"]:focus, input[type="date"]:focus, input[type="month"]:focus, input[type="time"]:focus, input[type="week"]:focus, input[type="number"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="search"]:focus, input[type="tel"]:focus, input[type="color"]:focus, .uneditable-input:focus, .form-control:focus {
border-color: (your color) or none;
box-shadow:(your color) or none;
outline: (your color) or none;}
There are several different approaches you can take.
The RESTful purists will want you to use BASIC authentication, and send credentials on every request. Their rationale is that no one is storing any state.
The client service could store a cookie, which maintains a session ID. I don't personally find this as offensive as some of the purists I hear from - it can be expensive to authenticate over and over again. It sounds like you're not too fond of this idea, though.
From your description, it really sounds like you might be interested in OAuth2 My experience so far, from what I've seen, is that it's kind of confusing, and kind of bleeding edge. There are implementations out there, but they're few and far between. In Java, I understand that it has been integrated into Spring3's security modules. (Their tutorial is nicely written.) I've been waiting to see if there will be an extension in Restlet, but so far, although it's been proposed, and may be in the incubator, it's still not been fully incorporated.
I just borrow some other guys' idea and write some code below that may be helpful.
import android.content.Context;
import android.graphics.Canvas;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
public class AutoResizeTextView extends TextView {
private static final int MAX_SIZE = 1000;
private static final int MIN_SIZE = 5;
private TextPaint mTextPaint;
private float mSpacingMult = 1.0f;
private float mSpacingAdd = 0.0f;
private boolean needAdapt = false;
private boolean adapting = false;
public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public AutoResizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public AutoResizeTextView(Context context) {
super(context);
init();
}
private void init() {
mTextPaint = new TextPaint();
}
@Override
protected void onDraw(Canvas canvas) {
if (adapting) {
return;
}
if (needAdapt) {
adaptTextSize();
} else {
super.onDraw(canvas);
}
}
private void adaptTextSize() {
CharSequence text = getText();
int viewWidth = getMeasuredWidth();
int viewHeight = getMeasuredHeight();
if (viewWidth==0 || viewHeight==0
|| TextUtils.isEmpty(text)) {
return;
}
adapting = true;
/* binary search */
int bottom=MIN_SIZE, top=MAX_SIZE, mid = 0;
while (bottom <= top) {
mid = (bottom + top)/2;
mTextPaint.setTextSize(mid);
int textWidth = (int) mTextPaint.measureText(text, 0, text.length());
int textHeight = getTextHeight(text, viewWidth);
if (textWidth<viewWidth && textHeight<viewHeight) {
bottom = mid+1;
} else {
top = mid-1;
}
}
int newSize = mid-1;
setTextSize(TypedValue.COMPLEX_UNIT_PX, newSize);
adapting=false;
needAdapt = false;
invalidate();
}
private int getTextHeight(CharSequence text, int targetWidth) {
StaticLayout layout = new StaticLayout(text, mTextPaint, targetWidth,
Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
return layout.getHeight();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
needAdapt = true;
}
@Override
protected void onTextChanged(CharSequence text, int start,
int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
needAdapt = true;
}
@Override
public void setLineSpacing(float add, float mult) {
super.setLineSpacing(add, mult);
mSpacingMult = mult;
mSpacingAdd = add;
}
}
Starting from this:
>>> lst = [1, 2, 3]
>>> print('\n'.join('{}: {}'.format(*k) for k in enumerate(lst)))
0: 1
1: 2
2: 3
You can get rid of the join
by passing \n
as a separator to print
>>> print(*('{}: {}'.format(*k) for k in enumerate(lst)), sep="\n")
0: 1
1: 2
2: 3
Now you see you could use map
, but you'll need to change the format string (yuck!)
>>> print(*(map('{0[0]}: {0[1]}'.format, enumerate(lst))), sep="\n")
0: 1
1: 2
2: 3
or pass 2 sequences to map
. A separate counter and no longer enumerate lst
>>> from itertools import count
>>> print(*(map('{}: {}'.format, count(), lst)), sep="\n")
0: 1
1: 2
2: 3
NP stands for Non-deterministic Polynomial time.
This means that the problem can be solved in Polynomial time using a Non-deterministic Turing machine (like a regular Turing machine but also including a non-deterministic "choice" function). Basically, a solution has to be testable in poly time. If that's the case, and a known NP problem can be solved using the given problem with modified input (an NP problem can be reduced to the given problem) then the problem is NP complete.
The main thing to take away from an NP-complete problem is that it cannot be solved in polynomial time in any known way. NP-Hard/NP-Complete is a way of showing that certain classes of problems are not solvable in realistic time.
Edit: As others have noted, there are often approximate solutions for NP-Complete problems. In this case, the approximate solution usually gives an approximation bound using special notation which tells us how close the approximation is.
Follow the steps to store data in Angular - local storage:
Inject 'ngStorage' in your angular.module
eg: angular.module("app", [ 'ngStorage']);
$localStorage
in your app.controller function4.You can use $localStorage
inside your controller
Eg: $localstorage.login= true;
The above will store the localstorage in your browser application
The problem: The format of the file as to how it is saved.
Use a proper text editor and save it with the .py
extension
and run it in terminal.
eg: file name should be saved as `example.py`
run
python example
To accomodate both data scenarios you have, you will want to use this:
datevalue(text(a2,"mm/dd/yyyy"))
That will give you the date number representation for a cell that Excel has in date, or in text datatype.
You can use a map with your object or string like bellow :
@RequestMapping(value = "/path",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Map<String,String>> getData(){
Map<String,String> response = new HashMap<String, String>();
boolean isValid = // some logic
if (isValid){
response.put("ok", "success saving data");
return ResponseEntity.accepted().body(response);
}
else{
response.put("error", "an error expected on processing file");
return ResponseEntity.badRequest().body(response);
}
}
The state of the database is maintained from the start of the transaction. If you retrieve a value in session1, then update that value in session2, retrieving it again in session1 will return the same results. Reads are repeatable.
session1> BEGIN;
session1> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> BEGIN;
session2> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> UPDATE names SET firstname = 'Bob' WHERE id = 7;
session2> SELECT firstname FROM names WHERE id = 7;
Bob
session2> COMMIT;
session1> SELECT firstname FROM names WHERE id = 7;
Aaron
Within the context of a transaction, you will always retrieve the most recently committed value. If you retrieve a value in session1, update it in session2, then retrieve it in session1again, you will get the value as modified in session2. It reads the last committed row.
session1> BEGIN;
session1> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> BEGIN;
session2> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> UPDATE names SET firstname = 'Bob' WHERE id = 7;
session2> SELECT firstname FROM names WHERE id = 7;
Bob
session2> COMMIT;
session1> SELECT firstname FROM names WHERE id = 7;
Bob
Makes sense?
For Asp.Net core you better use
<partial name="_MyPartialView" model="MyModel" />
So for example
@foreach (var item in Model)
{
<partial name="_MyItemView" model="item" />
}
Use the CSS
property list-style-position
to position the bullet:
list-style-position:inside /* or outside */;
Can't you create a subclass of Dictionary which has that functionality?
public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >
{
private Dictionary < TValue, TKey > _keys;
public TValue this[TKey key]
{
get
{
return base[key];
}
set
{
base[key] = value;
_keys[value] = key;
}
}
public MyDict()
{
_keys = new Dictionary < TValue, TKey >();
}
public TKey GetKeyFromValue(TValue value)
{
return _keys[value];
}
}
EDIT: Sorry, didn't get code right first time.
If you want to check if any item in the list violates a condition use all
:
if all([x[2] == 0 for x in lista]):
# Will run if all elements in the list has x[2] = 0 (use not to invert if necessary)
To remove all elements not matching, use filter
# Will remove all elements where x[2] is 0
listb = filter(lambda x: x[2] != 0, listb)
Oh, just with this:
$ docker-compose up client server database
Create a file called, say jshint_opts with this content: { "esversion": 6 }
Then invoke jshint with something like this command line:
jshint --config jshint_opts lib/*.js
Create new classes to overwrite the width. See jFiddle for working code.
<div class="row">
<div class="col-xs-1 col-xs-1-5">
<div class="box">
box 1
</div>
</div>
<div class="col-xs-3 col-xs-3-5">
<div class="box">
box 2
</div>
</div>
<div class="col-xs-3 col-xs-3-5">
<div class="box">
box 3
</div>
</div>
<div class="col-xs-3 col-xs-3-5">
<div class="box">
box 4
</div>
</div>
</div>
.col-xs-1-5 {
width: 12.49995%;
}
.col-xs-3-5 {
width: 29.16655%;
}
.box {
border: 1px solid #000;
text-align: center;
}
Please see here: static const vs define
usually a const declaration (notice it doesn't need to be static) is the way to go
I believe it's because #ID styles trump .class styles when computing the final style of an element. Try changing your li
from class
to id
, or you can try adding !important to your class, like this:
li.sub-navigation-home-news
{
color: #C1C1C1; !important
You can parse the geolocation through the addresses. Create an Array with jquery like this:
//follow this structure
var addressesArray = [
'Address Str.No, Postal Area/city'
]
//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
//it will place marker based on the addresses, which they will be translated as geolocations.
var aMarker= new google.maps.Marker({
position: latlng,
map: map
});
});
}
Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.
can you try something like this. You have to put each json in the data not json[i], because in the way you are doing it you are getting and putting only the properties of each json. Put the whole json instead in the data
var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
console.log("\n The details of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);
my_json = feed;
console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
data.push(my_json);
});
This might help:
<input type="number" step="1" pattern="\d+" />
step
is for convenience (and could be set to another integer), but pattern
does some actual enforcing.
Note that since pattern
matches the whole expression, it wasn't necessary to express it as ^\d+$
.
Even with this outwardly tight regular expression, Chrome and Firefox's implementations, interestingly allow for e
here (presumably for scientific notation) as well as -
for negative numbers, and Chrome also allows for .
whereas Firefox is tighter in rejecting unless the .
is followed by 0's only. (Firefox marks the field as red upon the input losing focus whereas Chrome doesn't let you input disallowed values in the first place.)
Since, as observed by others, one should always validate on the server (or on the client too, if using the value locally on the client or wishing to prevent the user from a roundtrip to the server).
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.
Example
find . -size +10000k -printf "%h/%f,%s\n"
Output
./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116
If you need one single regex, try:
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)
A short explanation:
(?=.*[a-z]) // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z]) // use positive look ahead to see if at least one upper case letter exists
(?=.*\d) // use positive look ahead to see if at least one digit exists
(?=.*\W]) // use positive look ahead to see if at least one non-word character exists
And I agree with SilentGhost, \W
might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?]
(feel free to add more of course!)
The accepted answer is great. This is not answer, but just an illustration of the issue.
I present a viewController like this:
inside vc1:
func showVC2() {
if let navController = self.navigationController{
navController.present(vc2, animated: true)
}
}
inside vc2:
func returnFromVC2() {
if let navController = self.navigationController {
navController.popViewController(animated: true)
}else{
print("navigationController is nil") <-- I was reaching here!
}
}
As 'stefandouganhyde' has said: "it is not contained by your UINavigationController or any other"
new solution:
func returnFromVC2() {
dismiss(animated: true, completion: nil)
}
Darian Moody has a nice solution to this challenge in his blog post:
a = 1
b = 2
c = True
rules = [a == 1,
b == 2,
c == True]
if all(rules):
print("Success!")
The all() method returns True
when all elements in the given iterable are true. If not, it returns False
.
You can read a little more about it in the python docs here and more information and examples here.
(I also answered the similar question with this info here - How to have multiple conditions for one if statement in python)
Without the need to install the grep variant pcregrep, you can do multiline search with grep.
$ grep -Pzo "(?s)^(\s*)\N*main.*?{.*?^\1}" *.c
Explanation:
-P
activate perl-regexp for grep (a powerful extension of regular expressions)
-z
suppress newline at the end of line, substituting it for null character. That is, grep knows where end of line is, but sees the input as one big line.
-o
print only matching. Because we're using -z
, the whole file is like a single big line, so if there is a match, the entire file would be printed; this way it won't do that.
In regexp:
(?s)
activate PCRE_DOTALL
, which means that .
finds any character or newline
\N
find anything except newline, even with PCRE_DOTALL
activated
.*?
find .
in non-greedy mode, that is, stops as soon as possible.
^
find start of line
\1
backreference to the first group (\s*
). This is a try to find the same indentation of method.
As you can imagine, this search prints the main method in a C (*.c
) source file.
So I do in Windows 10 and Python 3.7.1 (tested):
import subprocess
Quellpfad = r"C:\Users\MeMySelfAndI\Desktop"
Quelldatei = r"\a.bat"
Quelle = Quellpfad + Quelldatei
print(Quelle)
subprocess.call(Quelle)
Here's a compact Objective-C version as a Category on NSData. It takes some thinking about...
@implementation NSData (DataUtils)
static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- (NSString *)newStringInBase64FromData
{
NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
unsigned char * working = (unsigned char *)[self bytes];
int srcLen = [self length];
// tackle the source in 3's as conveniently 4 Base64 nibbles fit into 3 bytes
for (int i=0; i<srcLen; i += 3)
{
// for each output nibble
for (int nib=0; nib<4; nib++)
{
// nibble:nib from char:byt
int byt = (nib == 0)?0:nib-1;
int ix = (nib+1)*2;
if (i+byt >= srcLen) break;
// extract the top bits of the nibble, if valid
unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);
// extract the bottom bits of the nibble, if valid
if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);
[dest appendFormat:@"%c", base64[curr]];
}
}
return dest;
}
@end
Padding can be added if required by making the scope of 'byt' wider and appending 'dest' with (2-byt) "=" characters before returning.
A Category can then be added to NSString, thus:
@implementation NSString (StringUtils)
- (NSString *)newStringInBase64FromString
{
NSData *theData = [NSData dataWithBytes:[self UTF8String] length:[self length]];
return [theData newStringInBase64FromData];
}
@end
I see several answers here, but they don't seem to address the question - the user wants to get Unicode input from the command line.
Windows uses UTF-16 for encoding in two byte strings, so you need to get these from the OS in your program. There are two ways to do this -
1) Microsoft has an extension that allows main to take a wide character array: int wmain(int argc, wchar_t *argv[]); https://msdn.microsoft.com/en-us/library/6wd819wh.aspx
2) Call the windows api to get the unicode version of the command line wchar_t win_argv = (wchar_t)CommandLineToArgvW(GetCommandLineW(), &nargs); https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-commandlinetoargvw
Read this: http://utf8everywhere.org for detailed info, particularly if you are supporting other operating systems.
currently reopquery
is integrated into dnf
and yum
, so typing:
dnf repoquery -l <pkg-name>
will list package contents from a remote repository (even for the packages that are not installed yet)
meaning installing a separate dnf-utils
or yum-utils
package is no longer required for the functionality as it is now being supported natively.
for listing installed or local (*.rpm
files) packages' contents there is rpm -ql
i don't think it is possible with yum
org dnf
(not repoquery
subcommand)
please correct me if i am wrong
I recommend something like this:
public class MyMap {
Map<Object, V> map = new HashMap<Object, V>();
public V put(K1 key,V value){
return map.put(key, value);
}
public V put(K2 key,V value){
return map.put(key, value);
}
public V get(K1 key){
return map.get(key);
}
public V get(K2 key){
return map.get(key);
}
//Same for conatains
}
Then you can use it like:
myMap.put(k1,value)
or myMap.put(k2,value)
Advantages: It is simple, enforces type safety, and doesn't store repeated data (as the two maps solutions do, though still store duplicate values).
Drawbacks: Not generic.
@section
is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).
You might find Scott Gu's write up on this very interesting.
Edit: Based on additional question clarification
The @RenderSection
syntax goes into the Shared View, such as:
<div id="sidebar">
@RenderSection("Sidebar", required: false)
</div>
This would then be placed in your view with @Section
syntax:
@section Sidebar{
<!-- Content Here -->
}
In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views.
Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet.
@{
ViewBag.Title = "Corporate Homepage";
ViewBag.BodyID = "page-home";
Layout = "~/Views/Shared/_Layout2.cshtml";
}
There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer.
You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com
The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.
For example,
Begin Transaction
-Do some T-SQL queries here.
Rollback transaction -- OR commit transaction
If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.
For example:
USE AdventureWorks;
GO
BEGIN TRANSACTION;
BEGIN TRY
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
See the following link for more details.
http://msdn.microsoft.com/en-us/library/ms175976.aspx
Hope this helps but please let me know if you need more details.