You are missing a space between else
and if
It should be else if
instead of elseif
if(condition)
{
}
else if(condition)
{
}
else
{
}
If you also need to retrieve the values for the keys you are removing, this would be a pretty good way to do it:
values_removed = [d.pop(k, None) for k in entities_to_remove]
You could of course still do this just for the removal of the keys from d
, but you would be unnecessarily creating the list of values with the list comprehension. It is also a little unclear to use a list comprehension just for the function's side effect.
you can use super while extending Exception
if (pass.length() < minPassLength)
throw new InvalidPassException("The password provided is too short");
} catch (NullPointerException e) {
throw new InvalidPassException("No password provided", e);
}
// A custom business exception
class InvalidPassException extends Exception {
InvalidPassException() {
}
InvalidPassException(String message) {
super(message);
}
InvalidPassException(String message, Throwable cause) {
super(message, cause);
}
}
}
in onCreate()
:
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
supportInvalidateOptionsMenu();
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
supportInvalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Backstack.get(MainActivity.this).goBack();
}
});
//actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
//getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setHomeButtonEnabled(true);
And when setting up UP navigation:
private void setupViewsForKey(Key key) {
if(key.shouldShowUp()) {
drawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerToggle.setDrawerIndicatorEnabled(true);
}
drawerToggle.syncState();
First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.
But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.
For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used
CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN
INSERT hospitals ([Hospital ID], Email, Description)
VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid)));
SET @hid = @hid + 1;
END
And result would be
ID Hospital ID Email Description
---- ----------- ---------------- ---------------------
1 16 [email protected] Sample Description16
2 17 [email protected] Sample Description17
...
84 99 [email protected] Sample Description99
you can see the result here In these simple block of code you can change the size of your image ,and make it bigger when the mouse enter over the image , and it will return to its original size when mouve leave.
html:
<div>
<img onmouseover="fifo()" onmouseleave="fifo()" src="your_image"
width="10%" id="f" >
</div>
js file:
var b=0;
function fifo() {
if(b==0){
document.getElementById("f").width = "300";
b=1;
}
else
{
document.getElementById("f").width = "100";
b=0;
}
}
In loop you should refer to the current procceded element, so write:
var a_href = $(this).find('div.cpt h2 a').attr('href');
\?(.*)$
If you want to match all chars after "?" you can use a group to match any char, and you'd better use the "$" sign to indicate the end of line.
If you are using Google Chrome then you can simply use this extension named as Sense it is also a tool if you use Marvel.
https://chrome.google.com/webstore/detail/sense-beta/lhjgkmllcaadmopgmanpapmpjgmfcfig
First create an object of class2 in class1 and then use that object to call any function of class2 for example write this in class1
class2 obj= new class2();
obj.thefunctioname(args);
public void Linq95()
{
List<Customer> customers = GetCustomerList();
List<Product> products = GetProductList();
var customerNames =
from c in customers
select c.CompanyName;
var productNames =
from p in products
select p.ProductName;
var allNames = customerNames.Concat(productNames);
Console.WriteLine("Customer and product names:");
foreach (var n in allNames)
{
Console.WriteLine(n);
}
}
TL&DR: When you typically get data from a server, it is sent in bytes. The rationale is that these bytes will need to be 'decoded' by the recipient, who should know how to use the data. You should decode the binary upon arrival to not get 'b' (bytes) but instead a string.
Use case:
import requests
def get_data_from_url(url):
response = requests.get(url_to_visit)
response_data_split_by_line = response.content.decode('utf-8').splitlines()
return response_data_split_by_line
In this example, I decode the content that I received into UTF-8. For my purposes, I then split it by line, so I can loop through each line with a for loop.
In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:
user = UniversityDetails.objects.get(email=email)
is email a str
, or a None
? or an int
?
It will overflow and wrap around to Long.MIN_VALUE
.
Its not too likely though. Even if you increment 1,000,000 times per second it will take about 300,000 years to overflow.
Right way is using pytest.raises
but I found interesting alternative way in comments here and want to save it for future readers of this question:
try:
thing_that_rasises_typeerror()
assert False
except TypeError:
assert True
Swift 5 answer based on @ZpaceZombor's excellent answer
If you have a UIImage, just use
var image: UIImage = ....
image.draw(in: CGRect)
If you have a CGImage use my category below
Note: Unlike some other answers, this one takes into account that the rect you want to draw in might have y != 0. Those answers that don't take that into account are incorrect and won't work in the general case.
extension CGContext {
final func drawImage(image: CGImage, inRect rect: CGRect) {
//flip coords
let ty: CGFloat = (rect.origin.y + rect.size.height)
translateBy(x: 0, y: ty)
scaleBy(x: 1.0, y: -1.0)
//draw image
let rect__y_zero = CGRect(x: rect.origin.x, y: 0, width: rect.width, height: rect.height)
draw(image, in: rect__y_zero)
//flip back
scaleBy(x: 1.0, y: -1.0)
translateBy(x: 0, y: -ty)
}
}
Use like this:
let imageFrame: CGRect = ...
let context: CGContext = ....
let img: CGImage = .....
context.drawImage(image: img, inRect: imageFrame)
For node_modules you have to follow the below steps
1) In Command prompt -> Goto your project directory.
2) Command :npm init
3) It asks you to set up your package.json file
4) Command: npm install
or npm update
The way to do this is via the bracket notation.
var test = {_x000D_
"id": "109",_x000D_
"No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
For more info read out here:
Since they are already inline-block
child elements, you can set text-align:center
on the parent without having to set a width
or margin:0px auto
on the child. Meaning it will work for dynamically generated content with varying widths
.
.img_container, .img_container2 {
text-align: center;
}
This will center the child within both div
containers.
UPDATE:
For vertical centering, you can use the calc()
function assuming the height of the icon is known.
.img_container > i, .img_container2 > i {
position:relative;
top: calc(50% - 10px); /* 50% - 3/4 of icon height */
}
jsFiddle demo - it works.
For what it's worth - you can also use vertical-align:middle
assuming display:table-cell
is set on the parent.
A UNIX guy probably told you that. :)
You can use makefiles in VS, but when you do it bypasses all the built-in functionality in MSVC's IDE. Makefiles are basically the reinterpret_cast of the builder. IMO the simplest thing is just to use Solutions.
Execute the GetEventIdsByEventDate() method and save the results in a variable, and then you can use the .Contains() method
First of all you should know the difference between a virtual and abstract method.
Say your project is structured this way:
+---MyPythonProject
| +---.gitignore
| +---run.py
| | +---subscripts
| | | +---script_one.py
| | | +---script_two.py
Inside run.py
, you can import scripts one and two by:
from subscripts import script_one as One
from subscripts import script_two as Two
Now, still inside run.py
, you'll be able to call their methods with:
One.method_from_one(param)
Two.method_from_two(other_param)
I think this is a simple example, how to check if a radio in a group of radios was checked.
if($('input[name=html_elements]:checked').length){
//a radio button was checked
}else{
//there was no radio button checked
}
First of all, get your unix_socket location.
$ mysql -u root -p
Enter your mysql password and login your mysql server from command line.
mysql> show variables like '%sock%';
+---------------+---------------------------------------+
| Variable_name | Value |
+---------------+---------------------------------------+
| socket | /opt/local/var/run/mysql5/mysqld.sock |
+---------------+---------------------------------------+
Your unix_soket could be diffrent.
Then change your php.ini, find your php.ini
file from
<? phpinfo();
You maybe install many php with different version, so please don't assume your php.ini file location, get it from your 'phpinfo';
Change your php.ini:
mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock
mysqli.default_socket = /opt/local/var/run/mysql5/mysqld.sock
pdo_mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock
Then restart your apache or php-fpm.
Here is an example. (I am using CompareToBuilder
class from Apache for convenience, although this can be done without using it.)
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.builder.CompareToBuilder;
public class Tester {
boolean ascending = true;
public static void main(String args[]) {
Tester tester = new Tester();
tester.printValues();
}
public void printValues() {
List<HashMap<String, Object>> list =
new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map =
new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(21) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(7) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(456) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(1) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(20) );
map.put( "fromDate", getDate(4) );
map.put( "toDate", getDate(16) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(22) );
map.put( "fromDate", getDate(8) );
map.put( "toDate", getDate(11) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(10) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(4) );
map.put( "toDate", getDate(15) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(567) );
map.put( "eventId", new Integer(12) );
map.put( "fromDate", getDate(-1) );
map.put( "toDate", getDate(1) );
list.add(map);
System.out.println("\n Before Sorting \n ");
for( int j = 0; j < list.size(); j++ )
System.out.println(list.get(j));
Collections.sort( list, new HashMapComparator2() );
System.out.println("\n After Sorting \n ");
for( int j = 0; j < list.size(); j++ )
System.out.println(list.get(j));
}
public static Date getDate(int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, days);
return cal.getTime();
}
public class HashMapComparator2 implements Comparator {
public int compare(Object object1, Object object2) {
if( ascending ) {
return new CompareToBuilder()
.append(
((HashMap)object1).get("actionId"),
((HashMap)object2).get("actionId")
)
.append(
((HashMap)object2).get("eventId"),
((HashMap)object1).get("eventId")
)
.toComparison();
} else {
return new CompareToBuilder()
.append(
((HashMap)object2).get("actionId"),
((HashMap)object1).get("actionId")
)
.append(
((HashMap)object2).get("eventId"),
((HashMap)object1).get("eventId")
)
.toComparison();
}
}
}
}
If you have a specific code that you are working on and are having issues, you can post your pseudo code and we can try to help you out!
Yes, gzip
will let you do this. If you simply run gzip > foo.gz
, it will compress STDIN to the file foo.gz. You can also pipe data into it, like some_command | gzip > foo.gz
.
d = <dict>
values = d.values()
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
I use this object. Values are encoded, so it's necessary to consider it when reading or writing from server side.
cookie = (function() {
/**
* Sets a cookie value. seconds parameter is optional
*/
var set = function(name, value, seconds) {
var expires = seconds ? '; expires=' + new Date(new Date().getTime() + seconds * 1000).toGMTString() : '';
document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
};
var map = function() {
var map = {};
var kvs = document.cookie.split('; ');
for (var i = 0; i < kvs.length; i++) {
var kv = kvs[i].split('=');
map[kv[0]] = decodeURIComponent(kv[1]);
}
return map;
};
var get = function(name) {
return map()[name];
};
var remove = function(name) {
set(name, '', -1);
};
return {
set: set,
get: get,
remove: remove,
map: map
};
})();
The portable way to do this is:
sed -e 's/[ \t][ \t]*/\
/g'
That's an actual newline between the backslash and the slash-g. Many sed implementations don't know about \n
, so you need a literal newline. The backslash before the newline prevents sed from getting upset about the newline. (in sed scripts the commands are normally terminated by newlines)
With GNU sed you can use \n
in the substitution, and \s in the regex:
sed -e 's/\s\s*/\n/g'
GNU sed also supports "extended" regular expressions (that's egrep style, not perl-style) if you give it the -r flag, so then you can use +
:
sed -r -e 's/\s+/\n/g'
If this is for Linux only, you can probably go with the GNU command, but if you want this to work on systems with a non-GNU sed (eg: BSD, Mac OS-X), you might want to go with the more portable option.
It doesn't compile because T could be anything, and not everything will have the myvar
field.
You could make myvar
a property on ITest
:
public ITest
{
string myvar{get;}
}
and implement it on the classes as a property:
public class MyClass1 : ITest
{
public string myvar{ get { return "hello 1"; } }
}
and then put a generic constraint on your method:
public void PrintGeneric<T>(T test) where T : ITest
{
Console.WriteLine("Generic : " + test.myvar);
}
but in that case to be honest you are better off just passing in an ITest:
public void PrintGeneric(ITest test)
{
Console.WriteLine("Generic : " + test.myvar);
}
Alpine uses the command adduser
and addgroup
for creating users and groups (rather than useradd
and usergroup
).
FROM alpine:latest
# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Tell docker that all future commands should run as the appuser user
USER appuser
The flags for adduser
are:
Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)
To minimize drift more easily, use:
while :; do sleep 1m & some-command; wait; done
there will still be a tiny amount of drift due to bash's time to run the loop structure and the sleep command to actually execute.
hint: ':' evals to 0 ie true.
$fruit= array_map('trim', $fruit);
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(YourObjectType));
YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream);
You could also use the JavaScriptSerializer
, but DataContractJsonSerializer
is supposedly better able to handle complex types.
Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use DataContractJsonSerializer
since it is hard baked for WCF.
Best way to export database using php script.
Or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3")
for multiple tables
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "Your Username";
$mysqlPassword = "Your Password";
$mysqlHostName = "Your Host";
$DbName = "Your Database Name here";
$backup_name = "mybackup.sql";
$tables = "Your tables";
//or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables=false, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$backup_name = $backup_name ? $backup_name : $name.".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
echo $content; exit;
}
?>
That should be what --link
is for, at least for the hostname part.
With docker 1.10, and PR 19242, that would be:
docker network create --net-alias=[]: Add network-scoped alias for the container
(see last section below)
That is what Updating the /etc/hosts
file details
In addition to the environment variables, Docker adds a host entry for the source container to the
/etc/hosts
file.
For instance, launch an LDAP server:
docker run -t --name openldap -d -p 389:389 larrycai/openldap
And define an image to test that LDAP server:
FROM ubuntu
RUN apt-get -y install ldap-utils
RUN touch /root/.bash_aliases
RUN echo "alias lds='ldapsearch -H ldap://internalopenldap -LL -b
ou=Users,dc=openstack,dc=org -D cn=admin,dc=openstack,dc=org -w
password'" > /root/.bash_aliases
ENTRYPOINT bash
You can expose the 'openldap
' container as 'internalopenldap
' within the test image with --link:
docker run -it --rm --name ldp --link openldap:internalopenldap ldaptest
Then, if you type 'lds', that alias will work:
ldapsearch -H ldap://internalopenldap ...
That would return people. Meaning internalopenldap
is correctly reached from the ldaptest
image.
Of course, docker 1.7 will add libnetwork
, which provides a native Go implementation for connecting containers. See the blog post.
It introduced a more complete architecture, with the Container Network Model (CNM)
That will Update the Docker CLI with new “network” commands, and document how the “-net
” flag is used to assign containers to networks.
docker 1.10 has a new section Network-scoped alias, now officially documented in network connect
:
While links provide private name resolution that is localized within a container, the network-scoped alias provides a way for a container to be discovered by an alternate name by any other container within the scope of a particular network.
Unlike the link alias, which is defined by the consumer of a service, the network-scoped alias is defined by the container that is offering the service to the network.Continuing with the above example, create another container in
isolated_nw
with a network alias.
$ docker run --net=isolated_nw -itd --name=container6 -alias app busybox
8ebe6767c1e0361f27433090060b33200aac054a68476c3be87ef4005eb1df17
--alias=[]
Add network-scoped alias for the container
You can use
--link
option to link another container with a preferred aliasYou can pause, restart, and stop containers that are connected to a network. Paused containers remain connected and can be revealed by a network inspect. When the container is stopped, it does not appear on the network until you restart it.
If specified, the container's IP address(es) is reapplied when a stopped container is restarted. If the IP address is no longer available, the container fails to start.
One way to guarantee that the IP address is available is to specify an
--ip-range
when creating the network, and choose the static IP address(es) from outside that range. This ensures that the IP address is not given to another container while this container is not on the network.
$ docker network create --subnet 172.20.0.0/16 --ip-range 172.20.240.0/20 multi-host-network
$ docker network connect --ip 172.20.128.2 multi-host-network container2
$ docker network connect --link container1:c1 multi-host-network container2
I shared my experience of using two LEFT JOINS in a single SQL query.
I have 3 tables:
Table 1) Patient consists columns PatientID, PatientName
Table 2) Appointment consists columns AppointmentID, AppointmentDateTime, PatientID, DoctorID
Table 3) Doctor consists columns DoctorID, DoctorName
Query:
SELECT Patient.patientname, AppointmentDateTime, Doctor.doctorname
FROM Appointment
LEFT JOIN Doctor ON Appointment.doctorid = Doctor.doctorId //have doctorId column common
LEFT JOIN Patient ON Appointment.PatientId = Patient.PatientId //have patientid column common
WHERE Doctor.Doctorname LIKE 'varun%' // setting doctor name by using LIKE
AND Appointment.AppointmentDateTime BETWEEN '1/16/2001' AND '9/9/2014' //comparison b/w dates
ORDER BY AppointmentDateTime ASC; // getting data as ascending order
I wrote the solution to get date format like "mm/dd/yy" (under my name "VARUN TEJ REDDY")
This is a just a nice idea. that, you can Add class in body, and hide/show table while there is no data in table. This works perfect for me. You can design custom NO Record Found error message when there is no record in table, you can add class "no-record", and when there is 1 or more than one record, you can remove class and show datatable
Here is jQuery code.
$('#default_table').DataTable({
// your stuff here
"fnFooterCallback": function (nRow, aaData, iStart, iEnd, aiDisplay) {
if (aiDisplay.length > 0) {
$('body').removeClass('no-record');
}
else {
$('body').addClass('no-record');
}
}
});
Here is CSS
.no-record #default_table{display:none;}
If you are in a local network you can share a folder on your local machine and use it as destination folder for the backup.
Example:
Local folder:
C:\MySharedFolder -> URL: \\MyMachine\MySharedFolder
Remote SQL Server:
Select your database -> Tasks -> Back Up -> Destination -> Add -> Apply '\\MyMachine\MySharedFolder\BACKUP_NAME.bak'
The jQuery solution is to set the height of the textarea to 'auto', check the scrollHeight and then adapt the height of the textarea to that, every time a textarea changes (JSFiddle):
$('textarea').on( 'input', function(){
$(this).height( 'auto' ).height( this.scrollHeight );
});
If you're dynamically adding textareas (through AJAX or whatever), you can add this in your $(document).ready to make sure all textareas with class 'autoheight' are kept to the same height as their content:
$(document).on( 'input', 'textarea.autoheight', function() {
$(this).height( 'auto' ).height( this.scrollHeight );
});
Tested and working in Chrome, Firefox, Opera and IE. Also supports cut and paste, long words, etc.
$data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAADICAYAAAAQj4UaAAAcNUlEQVR4nO3dwW4cR37H8d8jzBsMXyACX4Aw7yawPBhIsDqs3kAEcolPGuQinbI6BMneLCRZ57AwJARLW8hhRcU8xA6QoaVsHGC9kVZrIVl7LYkJVootyf8cukcckjNV1T3VU1Xd3w/wBwSSmq4ecrrr3/WvKgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgKhsLNkHdYxTtwYAAABAb9mWZC8lszq+JQkBAAAA0AHblOz5XPIxi9upWwYAAACgV+wdyV4tSD6sTkpGqVsIAAAAoBfsnSWJx3xcS91KAAAA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Y8M98DAAAAwDJ2ccXRkJ7tTwAAAACgY0uXm53Iv7wrIx4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADrMZ1OR5999tnlzz777ApBEARBEARBZBSXp9Mp+yX1yXQ6HR0dHU2Pjo6MIAiCIAiCIDKMKUlIj0yn070M/qgIgiAIgiAIYmlMp9O91P1mREICQhAEQRAEQeQeJCA9Mp1OR9Pp9Cj1HxVBEARBEARBLIrpdHpECVbP1EnI3nQ6nRAEQRAEQRBERrE3JfkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhuv/ATiSIPBj5ipCAAAAAElFTkSuQmCC';
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = 'images/'.rand() . '.png';
$success = file_put_contents($file, $data);
$data = base64_decode($data);
$source_img = imagecreatefromstring($data);
$rotated_img = imagerotate($source_img, 90, 0);
$file = 'images/'. rand(). '.png';
$imageSave = imagejpeg($rotated_img, $file, 10);
imagedestroy($source_img);
To give the code that nstehr's answer refers to (from its source):
def timeparse(t, format):
"""Parse a time string that might contain fractions of a second.
Fractional seconds are supported using a fragile, miserable hack.
Given a time string like '02:03:04.234234' and a format string of
'%H:%M:%S', time.strptime() will raise a ValueError with this
message: 'unconverted data remains: .234234'. If %S is in the
format string and the ValueError matches as above, a datetime
object will be created from the part that matches and the
microseconds in the time string.
"""
try:
return datetime.datetime(*time.strptime(t, format)[0:6]).time()
except ValueError, msg:
if "%S" in format:
msg = str(msg)
mat = re.match(r"unconverted data remains:"
" \.([0-9]{1,6})$", msg)
if mat is not None:
# fractional seconds are present - this is the style
# used by datetime's isoformat() method
frac = "." + mat.group(1)
t = t[:-len(frac)]
t = datetime.datetime(*time.strptime(t, format)[0:6])
microsecond = int(float(frac)*1e6)
return t.replace(microsecond=microsecond)
else:
mat = re.match(r"unconverted data remains:"
" \,([0-9]{3,3})$", msg)
if mat is not None:
# fractional seconds are present - this is the style
# used by the logging module
frac = "." + mat.group(1)
t = t[:-len(frac)]
t = datetime.datetime(*time.strptime(t, format)[0:6])
microsecond = int(float(frac)*1e6)
return t.replace(microsecond=microsecond)
raise
$(document).on('keyup','#search_product',function(){
$( "#search_product" ).autocomplete({
source:function(request,response){
$.post("<?= base_url('ecommerce/autocomplete') ?>",{'name':$( "#search_product" ).val()}).done(function(data, status){
response(JSON.parse(data));
});
}
});
});
PHP code :
public function autocomplete(){
$name=$_POST['name'];
$result=$this->db->select('product_name,sku_code')->like('product_name',$name)->get('product_list')->result_array();
$names=array();
foreach($result as $row){
$names[]=$row['product_name'];
}
echo json_encode($names);
}
o(n sequre) is polynimal time complexity while o(2^n) is exponential time complexity if p=np when best case , in the worst case p=np not equal becasue when input size n grow so long or input sizer increase so longer its going to worst case and handling so complexity growth rate increase and depend on n size of input when input is small it is polynimal when input size large and large so p=np not equal it means growth rate depend on size of input "N". optimization, sat, clique, and independ set also met in exponential to polynimal.
In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.
Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.
Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.
Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.
To create an array of unlimited items of any sort of type:
typedef struct STRUCT_SS_VECTOR {
size_t size;
void** items;
} ss_vector;
ss_vector* ss_init_vector(size_t item_size) {
ss_vector* vector;
vector = malloc(sizeof(ss_vector));
vector->size = 0;
vector->items = calloc(0, item_size);
return vector;
}
void ss_vector_append(ss_vector* vec, void* item) {
vec->size++;
vec->items = realloc(vec->items, vec->size * sizeof(item));
vec->items[vec->size - 1] = item;
};
void ss_vector_free(ss_vector* vec) {
for (int i = 0; i < vec->size; i++)
free(vec->items[i]);
free(vec->items);
free(vec);
}
and how to use it:
// defining some sort of struct, can be anything really
typedef struct APPLE_STRUCT {
int id;
} apple;
apple* init_apple(int id) {
apple* a;
a = malloc(sizeof(apple));
a-> id = id;
return a;
};
int main(int argc, char* argv[]) {
ss_vector* vector = ss_init_vector(sizeof(apple));
// inserting some items
for (int i = 0; i < 10; i++)
ss_vector_append(vector, init_apple(i));
// dont forget to free it
ss_vector_free(vector);
return 0;
}
This vector/array can hold any type of item and it is completely dynamic in size.
I am using texmaker as the editor. you have to compile it in terminal as following:
but sometimes, when you use \citep{}
, the names of the references don't show up. In this case, I had to open the references.bib
file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.
I solved this problem with a custom Angular filter as well, but mine takes advantage of regex capturing groups and so the code is really short. I pair it with a separate stripNonNumeric
filter to sanitize the input:
app.filter('stripNonNumeric', function() {
return function(input) {
return (input == null) ? null : input.toString().replace(/\D/g, '');
}
});
The phoneFormat
filter properly formats a phone number with or without the area code. (I did not need international number support.)
app.filter('phoneFormat', function() {
//this establishes 3 capture groups: the first has 3 digits, the second has 3 digits, the third has 4 digits. Strings which are not 7 or 10 digits numeric will fail.
var phoneFormat = /^(\d{3})?(\d{3})(\d{4})$/;
return function(input) {
var parsed = phoneFormat.exec(input);
//if input isn't either 7 or 10 characters numeric, just return input
return (!parsed) ? input : ((parsed[1]) ? '(' + parsed[1] + ') ' : '') + parsed[2] + '-' + parsed[3];
}
});
Use them simply:
<p>{{customer.phone | stripNonNumeric | phoneFormat}}</p>
The regex for the stripNonNumeric
filter came from here.
This article here nicely explains it. Essentially, you can look at it as such:
CREATE TABLE t AS
SELECT 'a' v FROM dual UNION ALL
SELECT 'a' FROM dual UNION ALL
SELECT 'a' FROM dual UNION ALL
SELECT 'b' FROM dual UNION ALL
SELECT 'c' FROM dual UNION ALL
SELECT 'c' FROM dual UNION ALL
SELECT 'd' FROM dual UNION ALL
SELECT 'e' FROM dual;
SELECT
v,
ROW_NUMBER() OVER (ORDER BY v) row_number,
RANK() OVER (ORDER BY v) rank,
DENSE_RANK() OVER (ORDER BY v) dense_rank
FROM t
ORDER BY v;
The above will yield:
+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a | 1 | 1 | 1 |
| a | 2 | 1 | 1 |
| a | 3 | 1 | 1 |
| b | 4 | 4 | 2 |
| c | 5 | 5 | 3 |
| c | 6 | 5 | 3 |
| d | 7 | 7 | 4 |
| e | 8 | 8 | 5 |
+---+------------+------+------------+
In words
ROW_NUMBER()
attributes a unique value to each rowRANK()
attributes the same row number to the same value, leaving "holes"DENSE_RANK()
attributes the same row number to the same value, leaving no "holes"Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:
PHP Code sample:
if (!empty($_SERVER['HTTP_ORIGIN'])) {
// Uh oh, this XHR comes from outer space...
// Use this opportunity to filter out referers that shouldn't be allowed to see this request
if (!preg_match('@\.partner\.domain\.net$@'))
die("End of the road if you're not my business partner.");
// otherwise oblige
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
// local request, no need to send a specific header for CORS
}
In particular, don't add an exit;
as no preflight is needed.
People keep upvoting my answer, but it's a terrible solution compared to the joy of sass or less, particularly given the number of easy to use gui's for both these days. If you have any sense ignore everything I suggest below.
You could put a comment in the css before each colour in order to serve as a sort of variable, which you can change the value of using find/replace, so...
At the top of the css file
/********************* Colour reference chart****************
*************************** comment ********* colour ********
box background colour bbg #567890
box border colour bb #abcdef
box text colour bt #123456
*/
Later in the CSS file
.contentBox {background: /*bbg*/#567890; border: 2px solid /*bb*/#abcdef; color:/*bt*/#123456}
Then to, for example, change the colour scheme for the box text you do a find/replace on
/*bt*/#123456
Looks like the answer above was a little incomplete try the following:-
=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))
Obviously, this is for cell A2...
What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.
After the length has been determined and the portion of that which is required - then the Right command will display the information you need.
This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...
=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)
The List
interface already has this solved.
int temp = 2;
if(bankAccNos.contains(bakAccNo)) temp=1;
More can be found in the documentation about List.
So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.
To push the contents of foo to origin/master, you first need to set its upstream:
git checkout foo
git branch -u origin/master
Then you can push to this branch using:
git push origin HEAD:master
In the last command you can add --force to replace the entire history of origin/master with that of foo.
Heres my solution as of 5.4:
//Auth::routes();
// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
//Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
//Route::post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
Notice I've commented out Auth::routes()
and the two registration routes.
Important: you must also make sure you remove all instances of route('register')
in your app.blade
layout, or Laravel will throw an error.
Use str = ""+a+b+c;
Here the first +
is String
concat, so the result will be a String
. Note where the ""
lies is important.
Or (maybe) better, use a StringBuilder
.
Here is the official documentation of ArrayList.get().
Anyway it is very simple, for example
ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = (String) list.get(0); // here you get "1" in str
You can use sneaky-save gem: https://rubygems.org/gems/sneaky-save.
Note this cannot help in saving associations along without validations. It throws error 'created_at cannot be null' as it directly inserts the sql query unlike a model. To implement this, we need to update all auto generated columns of db.
You are not actually changing the function.
onClick
is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.
Another problem is your variable color
seems out of nowhere.
Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)
Generic functional form
def select_columns(data_frame, column_names):
new_frame = data_frame.loc[:, column_names]
return new_frame
Specific for your problem above
selected_columns = ['A', 'C', 'D']
new = select_columns(old, selected_columns)
I just recompiled curl with configure options pointing to the openssl 1.0.2g library folder and include folder, and I still get this message. When I do ldd on curl, it does not show that it uses either libcrypt.so
or libssl.so
, so I assume this must mean that even though the make
and make install
succeeded without errors, nevertheless curl does not have HTTPS support? Configure and make was as follows:
./configure --prefix=/local/scratch/PACKAGES/local --with-ssl=/local/scratch/PACKAGES/local/openssl/openssl-1.0.2g --includedir=/local/scratch/PACKAGES/local/include/openssl/openssl-1.0.2g
make
make test
make install
I should mention that libssl.so.1
is in /local/scratch/PACKAGES/local/lib
. It is unclear whether the --with-ssl
option should point there or to the directory where the openssl install placed the openssl.cnf file. I chose the latter. But if it were supposed to be the former, the make should have failed with an error that it couldn't find the library.
There is a command
svn revert -R .
OR
you can use the --depth=infinity, which is actually same as above:
svn revert --depth=infinity
svn revert
is inherently dangerous, since its entire purpose is to throw away data—namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes
First of all go to apache/bin/conf/httpd.conf and make sure that mod_deflate.so is enabled.
Then go to the .htaccess file and add this line:
SetOutputFilter DEFLATE
This should output all the content served as gzipped, i have tried it and it works.
If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:
my_arr.resize()
This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time. Hope this helped. Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.
What worked for me was using 'always|withText'. If you have many menus, consider using 'ifRoom' instead of 'always'.
<item android:id="@id/resource_name"
android:title="text"
android:icon="@drawable/drawable_resource_name"
android:showAsAction="always|withText" />
The old school way ;)
public static void openit(string x) {
System.Diagnostics.Process.Start("cmd", "/C start" + " " + x);
}
Use: openit("www.google.com");
You are trying to copy a string into an address that is statically allocated. You need to cat into a buffer.
Specifically:
...snip...
destination
Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.
...snip...
http://www.cplusplus.com/reference/clibrary/cstring/strcat.html
There's an example here as well.
This is because str.index(ch)
will return the index where ch
occurs the first time. Try:
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
This will return a list of all indexes you need.
P.S. Hugh's answer shows a generator function (it makes a difference if the list of indexes can get large). This function can also be adjusted by changing []
to ()
.
Get URL param as an object.
import { Router } from '@angular/router';
constructor(private router: Router) {
console.log(router.parseUrl(router.url));
}
You can detect if the browser supports the event by:
if ("onhashchange" in window) {
//...
}
See also:
Yes. In the javascript code:
window.location.href = "http://new.website.com/that/you/want_to_go_to.html";
The easiest method would be to use a semi-transparent background PNG image.
You can use JavaScript to make it work in Internet Explorer 6 if you need to.
I use the method outlined in Transparent PNGs in Internet Explorer 6.
Other than that, you could fake it using two side-by-side sibling elements - make one semi-transparent, then absolutely position the other over the top.
SELECT STUFF((SELECT ', ' + name FROM [table] FOR XML PATH('')), 1, 2, '')
Here's a sample:
DECLARE @t TABLE (name VARCHAR(10))
INSERT INTO @t VALUES ('Peter'), ('Paul'), ('Mary')
SELECT STUFF((SELECT ', ' + name FROM @t FOR XML PATH('')), 1, 2, '')
--Peter, Paul, Mary
js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.
Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file
<!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="xlsx.full.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {
type: "binary"
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
}
oReq.send();
</script>
</body>
</html>
Input:
Output:
You can use Jquery's on method and listen for the scroll
event.
Or can also insert the statement inside bracket.
SELECT * FROM tablename WHERE NOT (columnA = 'x')
Be careful of difference between 'c'
and "c"
'c'
is a char suitable for formatting with %c
"c"
is a char* pointing to a memory block with a length of 2 (with the null terminator).
When one uses the trick of closing on "this" during a constructor invocation, it's in order to write a function that can be used as a callback by some other object that doesn't want to invoke a method on an object. It's not related to "making the scope correct".
Here's a vanilla JavaScript object:
function MyThing(aParam) {
var myPrivateVariable = "squizzitch";
this.someProperty = aParam;
this.useMeAsACallback = function() {
console.log("Look, I have access to " + myPrivateVariable + "!");
}
}
// Every MyThing will get this method for free:
MyThing.prototype.someMethod = function() {
console.log(this.someProperty);
};
You might get a lot out of reading what Douglas Crockford has to say about JavaScript. John Resig is also brilliant. Good luck!
Try changing
public class LinqHelper
to
public static class LinqHelper
Alternatively you can also use CASE
for the same:
SELECT CASE WHEN field1 IS NULL OR field1 = ''
THEN 'empty'
ELSE field1 END AS field1
FROM tablename.
I had the same issue, and I couldn't comment on @Sven Marnach answer (not enough rep, gosh I remember when Stackoverflow first started...) anyway.
Adding a list of random numbers to a 10 X 10 matrix.
myNpArray = np.zeros([1, 10])
for x in range(1,11,1):
randomList = [list(np.random.randint(99, size=10))]
myNpArray = np.vstack((myNpArray, randomList))
myNpArray = myNpArray[1:]
Using np.zeros() an array is created with 1 x 10 zeros.
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
Then a list of 10 random numbers is created using np.random and assigned to randomList. The loop stacks it 10 high. We just have to remember to remove the first empty entry.
myNpArray
array([[31., 10., 19., 78., 95., 58., 3., 47., 30., 56.],
[51., 97., 5., 80., 28., 76., 92., 50., 22., 93.],
[64., 79., 7., 12., 68., 13., 59., 96., 32., 34.],
[44., 22., 46., 56., 73., 42., 62., 4., 62., 83.],
[91., 28., 54., 69., 60., 95., 5., 13., 60., 88.],
[71., 90., 76., 53., 13., 53., 31., 3., 96., 57.],
[33., 87., 81., 7., 53., 46., 5., 8., 20., 71.],
[46., 71., 14., 66., 68., 65., 68., 32., 9., 30.],
[ 1., 35., 96., 92., 72., 52., 88., 86., 94., 88.],
[13., 36., 43., 45., 90., 17., 38., 1., 41., 33.]])
So in a function:
def array_matrix(random_range, array_size):
myNpArray = np.zeros([1, array_size])
for x in range(1, array_size + 1, 1):
randomList = [list(np.random.randint(random_range, size=array_size))]
myNpArray = np.vstack((myNpArray, randomList))
return myNpArray[1:]
a 7 x 7 array using random numbers 0 - 1000
array_matrix(1000, 7)
array([[621., 377., 931., 180., 964., 885., 723.],
[298., 382., 148., 952., 430., 333., 956.],
[398., 596., 732., 422., 656., 348., 470.],
[735., 251., 314., 182., 966., 261., 523.],
[373., 616., 389., 90., 884., 957., 826.],
[587., 963., 66., 154., 111., 529., 945.],
[950., 413., 539., 860., 634., 195., 915.]])
You can simply check out a new branch, and then commit:
git checkout -b my_new_branch
git commit
Checking out the new branch will not discard your changes.
Check box-sizing
css property of your td
elements. I had problem with css template which sets it to border-box
value. You need set box-sizing: content-box
.
An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view
Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'
The best way to do this:
ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);
For me, this problem was solved by uninstalling the latest version of node and replacing it with the LTS version.
The thing about classes, and setting unencumbered global variables equal to some value within the class, is that what your global variable stores is actually the reference to the memory location the value is actually stored.
What you're seeing in your output is indicative of this.
Where you might be able to see the value and use print without issue on the initial global variables you used because of the str method and how print works, you won't be able to do this with lists, because what is stored in the elements within that list is just a reference to the memory location of the value -- read up on aliases, if you'd like to know more.
Additionally, when using lists and losing track of what is an alias and what is not, you might find you're changing the value of the original list element, if you change it in an alias list -- because again, when you set a list element equal to a list or element within a list, the new list only stores the reference to the memory location (it doesn't actually create new memory space specific to that new variable). This is where deepcopy comes in handy!
Got my private repo working using SSH key pairs. This was tested on git for Windows.
ssh-keygen -t ed25519 -C "[email protected]"
eval $(ssh-agent)
ssh-add ~/.ssh/id_ed25519
clip < ~/.ssh/id_ed25519.pub
ssh -T [email protected]
git config user.email [email protected]
git config user.name github_username
git remote -v
git remote set-url origin [email protected]:github_username/your-repo-name.git
git remote show origin
Also you will specify route on action for set route
[HttpGet]
[Route("api/customers/")]
public List<Customer> Get()
{
//gets all customer logic
}
[HttpGet]
[Route("api/customers/currentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
//gets some customer
}
[HttpGet]
[Route("api/customers/{id}")]
public Customer GetCustomerById(string id)
{
//gets a single customer by specified id
}
[HttpGet]
[Route("api/customers/customerByUsername/{username}")]
public Customer GetCustomerByUsername(string username)
{
//gets customer by its username
}
Simple sample:
HTML
<div id='player'>
<div id="my-button" ng-click="someFuntion()">Someone</div>
</div>
JavaScript
$timeout(function() {
angular.element('#my-button').triggerHandler('click');
}, 0);
What this does is look for the button's id
and perform a click action. Voila.
Source: https://techiedan.com/angularjs-how-to-trigger-click/
I'm the author of modular-spring-contexts.
This is a small utility library to allow a more modular organization of spring contexts than is achieved by using Composing XML-based configuration metadata. modular-spring-contexts
works by defining modules, which are basically stand alone application contexts and allowing modules to import beans from other modules, which are exported ín their originating module.
The key points then are
A simple example would look like this:
File moduleDefinitions.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<module:module id="serverModule">
<module:config location="/serverModule.xml" />
</module:module>
<module:module id="clientModule">
<module:config location="/clientModule.xml" />
<module:requires module="serverModule" />
</module:module>
</beans>
File serverModule.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<bean id="serverSingleton" class="java.math.BigDecimal" scope="singleton">
<constructor-arg index="0" value="123.45" />
<meta key="exported" value="true"/>
</bean>
</beans>
File clientModule.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<module:import id="importedSingleton" sourceModule="serverModule" sourceBean="serverSingleton" />
</beans>
If somehow balancePanel won't work, you could use this:
this.Location = new Point(127, 283);
or
anotherObject.Location = new Point(127, 283);
For a very specific reason Type Nullable<int>
put your cursor on Nullable and hit F12 - The Metadata provides the reason (Note the struct constraint):
public struct Nullable<T> where T : struct
{
...
}
These methods are in ObjectNode
: the division is such that most read operations are included in JsonNode
, but mutations in ObjectNode
and ArrayNode
.
Note that you can just change first line to be:
ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type
or
ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast
This examples shows calling a method
class ParentPage extends StatefulWidget {
@override
_ParentPageState createState() => _ParentPageState();
}
class _ParentPageState extends State<ParentPage> {
final GlobalKey<ChildPageState> _key = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Parent")),
body: Center(
child: Column(
children: <Widget>[
Expanded(
child: Container(
color: Colors.grey,
width: double.infinity,
alignment: Alignment.center,
child: RaisedButton(
child: Text("Call method in child"),
onPressed: () => _key.currentState.methodInChild(), // calls method in child
),
),
),
Text("Above = Parent\nBelow = Child"),
Expanded(
child: ChildPage(
key: _key,
function: methodInParent,
),
),
],
),
),
);
}
methodInParent() => Fluttertoast.showToast(msg: "Method called in parent", gravity: ToastGravity.CENTER);
}
class ChildPage extends StatefulWidget {
final Function function;
ChildPage({Key key, this.function}) : super(key: key);
@override
ChildPageState createState() => ChildPageState();
}
class ChildPageState extends State<ChildPage> {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.teal,
width: double.infinity,
alignment: Alignment.center,
child: RaisedButton(
child: Text("Call method in parent"),
onPressed: () => widget.function(), // calls method in parent
),
);
}
methodInChild() => Fluttertoast.showToast(msg: "Method called in child");
}
You can use emojis
Done? | Name
:---:| ---
??| Nope
?| Yep
If you want to do it programatically, you can use the FS
variable:
echo "1: " | awk 'BEGIN { FS=":" } /1/ { print $1 }'
Note that if you change it in the main loop rather than the BEGIN
loop, it takes affect for the next line read in, since the current line has already been split.
@dynamic is typically used (as has been said above) when a property is being dynamically created at runtime. NSManagedObject does this (why all its properties are dynamic) -- which suppresses some compiler warnings.
For a good overview on how to create properties dynamically (without NSManagedObject and CoreData:, see: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtDynamicResolution.html#//apple_ref/doc/uid/TP40008048-CH102-SW1
There is another consistent way (only for IE9+) in vanilla JavaScript for this:
const iframe = document.getElementById('iframe');
const handleLoad = () => console.log('loaded');
iframe.addEventListener('load', handleLoad, true)
And if you're interested in Observables this does the trick:
return Observable.fromEventPattern(
handler => iframe.addEventListener('load', handler, true),
handler => iframe.removeEventListener('load', handler)
);
make use of (Type Properties)
Name Gets the name of the current member. (Inherited from MemberInfo.)
Example : typeof(T).Name;
There is another away if you don't like to change System locale but the JVM. you can setup a System (or user) Environment variable JAVA_TOOL_OPTIONS
and set its value to -Duser.language=en-US
or any other language-REGION you want.
You can execute a string with OPENQUERY once you build it up. If you go this route think about security and take care not to concatenate user-entered text into your SQL!
DECLARE @Sql VARCHAR(8000)
SET @Sql = 'SELECT * FROM Tbl WHERE Field1 < ''someVal'' AND Field2 IN '+ @valueList
SET @Sql = 'SELECT * FROM OPENQUERY(SVRNAME, ''' + REPLACE(@Sql, '''', '''''') + ''')'
EXEC(@Sql)
Use static_cast<int>
:
int num = static_cast<int>(letter); // if letter='a', num=97
Edit: You probably should try to avoid to use (int)
int num = (int) letter;
check out Why use static_cast<int>(x) instead of (int)x? for more info.
Use no interpolation and set to gray.
import matplotlib.pyplot as plt
plt.imshow(img[:,:,1], cmap='gray',interpolation='none')
One solution to this would be a list comprehension, with pattern matching inside your tuple:
>>> mylist = [(25,7),(26,9),(55,10)]
>>> [age for (age,person_id) in mylist if person_id == 10]
[55]
Another way would be using map
and filter
:
>>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )
[55]
import os
import boto3
#initiate s3 resource
s3 = boto3.resource('s3')
# select bucket
my_bucket = s3.Bucket('my_bucket_name')
# download file into current directory
for s3_object in my_bucket.objects.all():
# Need to split s3_object.key into path and file name, else it will give error file not found.
path, filename = os.path.split(s3_object.key)
my_bucket.download_file(s3_object.key, filename)
Digging little deeper into that!
The type of a generic class in CPython is type
and its base class is Object
(Unless you explicitly define another base class like a metaclass). The sequence of low level calls can be found here. The first method called is the type_call
which then calls tp_new
and then tp_init
.
The interesting part here is that tp_new
will call the Object
's (base class) new method object_new
which does a tp_alloc
(PyType_GenericAlloc
) which allocates the memory for the object :)
At that point the object is created in memory and then the __init__
method gets called. If __init__
is not implemented in your class then the object_init
gets called and it does nothing :)
Then type_call
just returns the object which binds to your variable.
There seems to be a syntactically simpler way, and therefore easier to remember, as opposed to the proposed solutions. I'm assuming that the column is called 'meta' in a dataframe df:
df2 = pd.DataFrame(df['meta'].str.split().values.tolist())
If your problem is only with function overloading (you need to check if 'parameters' parameter is 'parameters' and not 'callback'), i would recommend you don't bother about argument type and
use this approach. The idea is simple - use literal objects to combine your parameters:
function getData(id, opt){
var data = voodooMagic(id, opt.parameters);
if (opt.callback!=undefined)
opt.callback.call(data);
return data;
}
getData(5, {parameters: "1,2,3", callback:
function(){for (i=0;i<=1;i--)alert("FAIL!");}
});
That's exactly what cursor: pointer;
is supposed to do.
If you want the cursor to remain normal, you should be using cursor: default
It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:
The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.
I would suggest doing this in a more functional style :P
function CreateMessageboard(BoardMessages) {
var htmlMessageboardString = BoardMessages
.map(function(BoardMessage) {
return MessageToHTMLString(BoardMessage);
})
.join('');
}
Try this
What you do is add a welcome file in your web.xml
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
And then add this to your servlet mappings so that when someone goes to the root of your application, they get sent to index.html internally and then the mapping will internally send them to the servlet you map it to
<servlet-mapping>
<servlet-name>MainActions</servlet-name>
<url-pattern>/main</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>MainActions</servlet-name>
<url-pattern>/index.html</url-pattern>
</servlet-mapping>
End result: You visit /Application, but you are presented with /Application/MainActions servlet without disrupting any other root requests.
Get it? So your app still sits at a sub url, but automatically gets presented when the user goes to the root of your site. This allows you to have the /images/bob.img still go to the regular place, but '/' is your app.
On a 64-bit machine:
int: 4
long: 8
long long: 8
void*: 8
size_t: 8
The simple jquery source for the same -
$("input:radio[name='group1']").click(function() {
$('.desc').hide();
$('#' + $("input:radio[name='group1']:checked").val()).show();
});
In order to make it little more appropriate just add checked to first option --
<div><label><input type="radio" name="group1" value="opt1" checked>opt1</label></div>
remove .desc class from styling and modify divs like --
<div id="opt1" class="desc">lorem ipsum dolor</div>
<div id="opt2" class="desc" style="display: none;">consectetur adipisicing</div>
<div id="opt3" class="desc" style="display: none;">sed do eiusmod tempor</div>
it will really look good any-ways.
If you're doing some sort of math with the numbers you might also want to know the units. Given your input restrictions (that the input string contains unit and value only), this should correctly return both (you'll just need to figure out how to convert units into common units for your math).
def unit_value(str):
m = re.match(r'([^\d]*)(\d*\.?\d+)([^\d]*)', str)
if m:
g = m.groups()
return ' '.join((g[0], g[2])).strip(), float(g[1])
else:
return int(str)
Without redundant intermediate arrays:
arr = $('li').map(function(i,el) {
return $(el).text();
}).get();
See jsfiddle demo
echo "C:\Users\San.Tan\My Folder\project1" | sed -e 's/C:\\/mnt\/c\//;s/\\/\//g'
replaces
C:\Users\San.Tan\My Folder\project1
to
mnt/c/Users/San.Tan/My Folder/project1
in case someone needs to replace windows paths to Windows Subsystem for Linux(WSL) paths
For the people who want to use the JSON.parse(JSON.stringify(obj))
version, but without losing the Date objects, you can use the second argument of parse
method to convert the strings back to Date:
function clone(obj) {
var regExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
return JSON.parse(JSON.stringify(obj), function(k, v) {
if (typeof v === 'string' && regExp.test(v))
return new Date(v)
return v;
})
}
// usage:
var original = {
a: [1, null, undefined, 0, {a:null}, new Date()],
b: {
c(){ return 0 }
}
}
var cloned = clone(original)
console.log(cloned)
_x000D_
I solved this converting the JSP from XHTML to HTML, doing this in the begining:
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
...
Use g++
g++ -o hi hi.cpp
g++ is for C++, gcc is for C although with the -libstdc++ you can compile c++ most people don't do this.
To be more exhaustive (and as it has been requested in comments), I add the solution given by C++17 using std::from_chars
.
std::string str = "10";
int number;
std::from_chars(str.data(), str.data()+str.size(), number);
If you want to check whether the conversion was successful:
std::string str = "10";
int number;
auto [ptr, ec] = std::from_chars(str.data(), str.data()+str.size(), number);
assert(ec == std::errc{});
// ptr points to chars after read number
Moreover, to compare the performance of all these solutions, see the following quick-bench link: https://quick-bench.com/q/GBzK53Gc-YSWpEA9XskSZLU963Y
(std::from_chars
is the fastest and std::istringstream
is the slowest)
The bias helps to get a better equation
Imagine the input and output like a function y = ax + b
and you need to put the right line between the input(x) and output(y) to minimise the global error between each point and the line , if you keep the equation like this y = ax
, you will have one parameter for adaptation only , even if you find the best a
minimising the global error it will be kind of far from the wanted value
You can say the bias makes the equation more flexible to adapt to the best values
{{ word|striptags('<b>,<a>,<pre>')|raw }}
if you want to allow multiple tags
It could also be because, it might not be able to found the .dll file required. Either the file is not in the folder or is renamed. I faced the same issue and found that .dll file was missing in my bin folder some how.
On the other hand, if there's a way to move an existing window from one X-server to another, that might solve the problem.
I think you can use xmove to move windows between two separate x-servers. So if it works, this should at least give you a way to do what you want albeit not as easily as changing the resolution.
Basic:
string[] myString = new string[]{"string1", "string2"};
or
string[] myString = new string[4];
myString[0] = "string1"; // etc.
Advanced: From a List
list<string> = new list<string>();
//... read this in from somewhere
string[] myString = list.ToArray();
From StringCollection
StringCollection sc = new StringCollection();
/// read in from file or something
string[] myString = sc.ToArray();
Source: CodePath - UI Testing With Espresso
- Finally, we need to pull in the Espresso dependencies and set the test runner in our app build.gradle:
// build.gradle
...
android {
...
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
dependencies {
...
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
// Necessary if your app targets Marshmallow (since Espresso
// hasn't moved to Marshmallow yet)
exclude group: 'com.android.support', module: 'support-annotations'
}
androidTestCompile('com.android.support.test:runner:0.5') {
// Necessary if your app targets Marshmallow (since the test runner
// hasn't moved to Marshmallow yet)
exclude group: 'com.android.support', module: 'support-annotations'
}
}
I've added that to my gradle file and the warning disappeared.
Also, if you get any other dependency listed as conflicting, such as support-annotations, try excluding it too from the androidTestCompile dependencies.
How about
$('select>option:eq(3)').attr('selected', true);
example at http://www.jsfiddle.net/gaby/CWvwn/
for modern versions of jquery you should use the .prop()
instead of .attr()
$('select>option:eq(3)').prop('selected', true);
example at http://jsfiddle.net/gaby/CWvwn/1763/
If you are still not getting device token, try putting following code so to register your device for push notification.
It will also work on ios8 or more.
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([UIApplication respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
}
#else
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
#endif
I don't know what qualifies as best but zxing has a qr code generator for java, is actively developed, and is liberally licensed.
This question already has an answer, but I just want to add that in Windows there is Windows Subsystem for Linux WSL.
So for example if you want to check if you have service named Elasicsearch that is in status running you can do something like the snippet below in powershell
net start | grep Elasticsearch
You can just add an alias
alias subl='/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl'
Then you should be able to open a folder or whatever with
subl <path>
You will find multiple different methods that people use and they each have there own place.
<?php if($first_condition): ?>
/*$first_condition is true*/
<?php elseif ($second_condition): ?>
/*$first_condition is false and $second_condition is true*/
<?php else: ?>
/*$first_condition and $second_condition are false*/
<?php endif; ?>
If in your php.ini attribute short_open_tag = true
(this is normally found on line 141
of the default php.ini file) you can replace your php open tag from <?php
to <?
. This is not advised as most live server environments have this turned off (including many CMS's like Drupal, WordPress and Joomla). I have already tested short hand open tags in Drupal and confirmed that it will break your site, so stick with <?php
. short_open_tag
is not on by default in all server configurations and must not be assumed as such when developing for unknown server configurations. Many hosting companies have short_open_tag
turned off.
A quick search of short_open_tag
in stackExchange shows 830 results. https://stackoverflow.com/search?q=short_open_tag
That's a lot of people having problems with something they should just not play with.
with some server environments and applications, short hand php open tags will still crash your code even with short_open_tag
set to true
.
short_open_tag
will be removed in PHP6 so don't use short hand tags.
all future PHP versions will be dropping short_open_tag
"It's been recommended for several years that you not use the short tag "short cut" and instead to use the full tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it's currently still supported for backwards compatibility, but we recommend you don't use them." – Jelmer Sep 25 '12 at 9:00 php: "short_open_tag = On" not working
and
Normally you write PHP like so: . However if allow_short_tags directive is enabled you're able to use: . Also sort tags provides extra syntax: which is equal to .
Short tags might seem cool but they're not. They causes only more problems. Oh... and IIRC they'll be removed from PHP6. Crozin answered Aug 24 '10 at 22:12 php short_open_tag problem
and
To answer the why part, I'd quote Zend PHP 5 certification guide: "Short tags were, for a time, the standard in the PHP world; however, they do have the major drawback of conflicting with XML headers and, therefore, have somewhat fallen by the wayside." – Fluffy Apr 13 '11 at 14:40 Are PHP short tags acceptable to use?
You may also see people use the following example:
<?php if($first_condition){ ?>
/*$first_condition is true*/
<?php }else if ($second_condition){ ?>
/*$first_condition is false and $second_condition is true*/
<?php }else{ ?>
/*$first_condition and $second_condition are false*/
<?php } ?>
This will work but it is highly frowned upon as it's not considered as legible and is not what you would use this format for. If you had a PHP file where you had a block of PHP code that didn't have embedded tags inside, then you would use the bracket format.
The following example shows when to use the bracket method
<?php
if($first_condition){
/*$first_condition is true*/
}else if ($second_condition){
/*$first_condition is false and $second_condition is true*/
}else{
/*$first_condition and $second_condition are false*/
}
?>
If you're doing this code for yourself you can do what you like, but if your working with a team at a job it is advised to use the correct format for the correct circumstance. If you use brackets in embedded html/php scripts that is a good way to get fired, as no one will want to clean up your code after you. IT bosses will care about code legibility and college professors grade on legibility.
UPDATE
based on comments from duskwuff its still unclear if shorthand is discouraged (by the php standards) or not. I'll update this answer as I get more information. But based on many documents found on the web about shorthand being bad for portability. I would still personally not use it as it gives no advantage and you must rely on a setting being on that is not on for every web host.
@ and @@ in modules also work differently when a class extends or includes that module.
So given
module A
@a = 'module'
@@a = 'module'
def get1
@a
end
def get2
@@a
end
def set1(a)
@a = a
end
def set2(a)
@@a = a
end
def self.set1(a)
@a = a
end
def self.set2(a)
@@a = a
end
end
Then you get the outputs below shown as comments
class X
extend A
puts get1.inspect # nil
puts get2.inspect # "module"
@a = 'class'
@@a = 'class'
puts get1.inspect # "class"
puts get2.inspect # "module"
set1('set')
set2('set')
puts get1.inspect # "set"
puts get2.inspect # "set"
A.set1('sset')
A.set2('sset')
puts get1.inspect # "set"
puts get2.inspect # "sset"
end
class Y
include A
def doit
puts get1.inspect # nil
puts get2.inspect # "module"
@a = 'class'
@@a = 'class'
puts get1.inspect # "class"
puts get2.inspect # "class"
set1('set')
set2('set')
puts get1.inspect # "set"
puts get2.inspect # "set"
A.set1('sset')
A.set2('sset')
puts get1.inspect # "set"
puts get2.inspect # "sset"
end
end
Y.new.doit
So use @@ in modules for variables you want common to all their uses, and use @ in modules for variables you want separate for every use context.
Text will never wrap to the next line. The text continues on the same line until a
tag is encountered.
.dropdown-menu {
white-space: nowrap;
}
I personally used the approach of "if it makes sense for the user to bookmark a URLwhich includes these parameters then use PathParam".
For instance, if the URL for a user profile includes some profile id parameter, since this can be bookmarked by the user and/or emailed around, I would include that profile id as a path parameter. Also, another considerent to this is that the page denoted by the URL which includes the path param doesn't change -- the user will set up his/her profile, save it, and then unlikely to change that much from there on; this means webcrawlers/search engines/browsers/etc can cache this page nicely based on the path.
If a parameter passed in the URL is likely to change the page layout/content then I'd use that as a queryparam. For instance, if the profile URL supports a parameter which specifies whether to show the user email or not, I would consider that to be a query param. (I know, arguably, you could say that the &noemail=1
or whatever parameter it is can be used as a path param and generates 2 separate pages -- one with the email on it, one without it -- but logically that's not the case: it is still the same page with or without certain attributes shown.
Hope this helps -- I appreciate the explanation might be a bit fuzzy :)
Perhaps setOnClickListener(null)
?
You can use either File.Copy(oldFilePath, newFilePath) method or other way is, read file using StreamReader into an string and then use StreamWriter to write the file to destination location.
Your code might look like this :
StreamReader reader = new StreamReader("C:\foo.txt");
string fileContent = reader.ReadToEnd();
StreamWriter writer = new StreamWriter("D:\bar.txt");
writer.Write(fileContent);
You can add exception handling code...
Using "kill -9 [PID]" or "killall -9 node" worked for me where "kill -2 [PID]" did not work.
It seems the images you have used is very large in size.so some older devices crashes occurs due to heap memory full.In older devices(honey comb or ICS or any low end model devices) try to use android:largeHeap="true"
in the manifest file under application tag or reduce the size of the bitmap by using below code.
Bitmap bMap;
BitmapFactory.Options options = new BitmapFactory.Options();
options.InSampleSize = 8;
bMap= BitmapFactory.DecodeFile(imgFile.AbsolutePath, options);
you can also give 4 or 12 or 16 to reduce the bitmap size
If you don't want to from __future__ import print_function
you can do the following:
a = 100
b = True
print a if b else "", # Note the comma!
print "see no new line"
Which prints:
100 see no new line
If you're not aversed to from __future__ import print_function
or are using python 3 or later:
from __future__ import print_function
a = False
b = 100
print(b if a else "", end = "")
Adding the else is the only change you need to make to make your code syntactically correct, you need the else for the conditional expression (the "in line if else blocks")
The reason I didn't use None
or 0
like others in the thread have used, is because using None/0
would cause the program to print None
or print 0
in the cases where b
is False
.
If you want to read about this topic I've included a link to the release notes for the patch that this feature was added to Python.
The 'pattern' above is very similar to the pattern shown in PEP 308:
This syntax may seem strange and backwards; why does the condition go in the middle of the expression, and not in the front as in C's c ? x : y? The decision was checked by applying the new syntax to the modules in the standard library and seeing how the resulting code read. In many cases where a conditional expression is used, one value seems to be the 'common case' and one value is an 'exceptional case', used only on rarer occasions when the condition isn't met. The conditional syntax makes this pattern a bit more obvious:
contents = ((doc + '\n') if doc else '')
So I think overall this is a reasonable way of approching it but you can't argue with the simplicity of:
if logging: print data
This issue vexed me for some time. I was using reactive forms and I fixed it using this method. PS. Using Angular 9 and Material 9.
In the "ngOnInit" lifecycle hook
1) Get the object you want to set as the default from your array or object literal
const countryDefault = this.countries.find(c => c.number === '826');
Here I am grabbing the United Kingdom object from my countries array.
2) Then set the formsbuilder object (the mat-select) with the default value.
this.addressForm.get('country').setValue(countryDefault.name);
3) Lastly...set the bound value property. In my case I want the name value.
<mat-select formControlName="country">
<mat-option *ngFor="let country of countries" [value]="country.name" >
{{country.name}}
</mat-option>
</mat-select>
Works like a charm. I hope it helps
When converting from signed to unsigned there are two possibilities. Numbers that were originally positive remain (or are interpreted as) the same value. Number that were originally negative will now be interpreted as larger positive numbers.
It would be helpful to know what code you are trying to execute when the button is pressed. You've got the onClick property set in your xml file to a method called setLogin. For clarity, I'd delete this line android:onClick="setLogin"
and call the method directly from inside your onClick()
method.
Also you can't just set the display to a new XML, you need to start a new activity with an Intent, a method something like this would be appropriate
private void setLogin() {
Intent i = new Intent(currentActivity.this, newActivity.class);
startActivty(i);
}
Then set the new Activity to have the new layout.
The simple method is to use :
sdiff A1 A2
Another method is to use comm
, as you can see in Comparing two unsorted lists in linux, listing the unique in the second file
i think android studio has a 64bit kernel version which is giving the problem. https://github.com/swcarpentry/windows-installer/issues/49
My solution expands on @tak3r's.
It returns an empty object when there are no query parameters and supports the array notation ?a=1&a=2&a=3
:
function getQueryParams () {
function identity (e) { return e; }
function toKeyValue (params, param) {
var keyValue = param.split('=');
var key = keyValue[0], value = keyValue[1];
params[key] = params[key]?[value].concat(params[key]):value;
return params;
}
return decodeURIComponent(window.location.search).
replace(/^\?/, '').split('&').
filter(identity).
reduce(toKeyValue, {});
}
This should work.
$foo = someFunction 2>$null
Here's a simple example:
Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
list.add(m.group());
}
(if you have more capturing groups, you can refer to them by their index as an argument of the group method. If you need an array, then use list.toArray()
)
This issue will come mostly due to empty rows at the end of the file, remove those and run the job.
I think ("\") may be causing the problem because \ is the escape character. change it to ("\\")
You can now simply do Instant.parse("2015-04-28T14:23:38.521Z")
and get the correct thing now, especially since you should be using Instant
instead of the broken java.util.Date
with the most recent versions of Java.
You should be using DateTimeFormatter
instead of SimpleDateFormatter
as well.
The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.
Z
as demonstrated:In the pattern the
T
is escaped with'
on either side.The pattern for the
Z
at the end is actuallyXXX
as documented in the JavaDoc forSimpleDateFormat
, it is just not very clear on actually how to use it sinceZ
is the marker for the oldTimeZone
information as well.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Q2597083
{
/**
* All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
*/
public static final TimeZone UTC;
/**
* @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
*/
public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
/**
* 0001-01-01T00:00:00.000Z
*/
public static final Date BEGINNING_OF_TIME;
/**
* 292278994-08-17T07:12:55.807Z
*/
public static final Date END_OF_TIME;
static
{
UTC = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(UTC);
final Calendar c = new GregorianCalendar(UTC);
c.set(1, 0, 1, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
BEGINNING_OF_TIME = c.getTime();
c.setTime(new Date(Long.MAX_VALUE));
END_OF_TIME = c.getTime();
}
public static void main(String[] args) throws Exception
{
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
sdf.setTimeZone(UTC);
System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
}
}
sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994
I had a similar problem, but I was using initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
explicitly using the name of the class as the string passed (yes bad form!).
I ended up deleting and re-creating the view controller using a slightly different name but neglected to change the string specified in the method, thus my old version was still used - even though it was in the trash!
I will likely use this structure going forward as suggested in: Is passing two nil paramters to initWithNibName:bundle: method bad practice (i.e. unsafe or slower)?
- (id)init
{
[super initWithNibName:@"MyNib" bundle:nil];
... typical initialization ...
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
return [self init];
}
Hopefully this helps someone!
Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:
Mouse.OverrideCursor = Cursors.Wait;
try
{
// do stuff
}
finally
{
Mouse.OverrideCursor = null;
}
This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.
Use IsNumeric
. It returns true if it's a number or false otherwise.
Public Sub NumTest()
On Error GoTo MyErrorHandler
Dim myVar As Variant
myVar = 11.2 'Or whatever
Dim finalNumber As Integer
If IsNumeric(myVar) Then
finalNumber = CInt(myVar)
Else
finalNumber = 0
End If
Exit Sub
MyErrorHandler:
MsgBox "NumTest" & vbCrLf & vbCrLf & "Err = " & Err.Number & _
vbCrLf & "Description: " & Err.Description
End Sub
Element needs to be a variant, so you can't declare it as a string. Your function should accept a variant if it is a string though as long as you pass it ByVal.
Public Sub example()
Dim sArray(4) As string
Dim element As variant
For Each element In sArray
do_something (element)
Next element
End Sub
Sub do_something(ByVal e As String)
End Sub
The other option is to convert the variant to a string before passing it.
do_something CStr(element)
I'm pretty sure you can do explicit casting here.
foo f = (foo)value;
So long as you say the enum inherits(?) from int, which you have.
enum foo : int
EDIT Yes it turns out that by default, an enums underlying type is int. You can however use any integral type except char.
You can also cast from a value that's not in the enum, producing an invalid enum. I suspect this works by just changing the type of the reference and not actually changing the value in memory.
enum (C# Reference)
Enumeration Types (C# Programming Guide)
If you want to do it from code behind, try this:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Message');", true);
The command you want is named tee
:
foo | tee output.file
For example, if you only care about stdout:
ls -a | tee output.file
If you want to include stderr, do:
program [arguments...] 2>&1 | tee outfile
2>&1
redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the tee
command.
Furthermore, if you want to append to the log file, use tee -a
as:
program [arguments...] 2>&1 | tee -a outfile
With a BorderLayout you need to use setPreferredSize
instead of setSize
$ch = curl_init('http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie
// multi-cookie variant contributed by @Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
var_dump($cookies);
With the use of Google Guava:
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public String readResource(final String fileName, Charset charset) throws Exception {
try {
return Resources.toString(Resources.getResource(fileName), charset);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
Example:
String fixture = this.readResource("filename.txt", Charsets.UTF_8)
Here's how to look in the documentation.
First, you're dealing with IO, so look in the java.io
package.
There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles()
method in the File class. And the documentation for that method says:
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
Scrolling up in the File
JavaDoc, I see the constructors. And that's really all I need to be able to create a File
instance and call listFiles()
on it. Scrolling still further, I can see some information about how files are named in different operating systems.
I got it working using the Raw data option in postman, as you can see in the screen shot
php 5.5 has an imagecrop function http://php.net/manual/en/function.imagecrop.php
This should work too:
logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')
You could use the Tkinter module, which is the standard Python interface to the Tk GUI toolkit and you don't need extra download. See https://docs.python.org/2/library/tkinter.html.
(For Python 3, Tkinter is renamed to tkinter)
Here is how to set RGB values:
#from http://tkinter.unpythonic.net/wiki/PhotoImage
from Tkinter import *
root = Tk()
def pixel(image, pos, color):
"""Place pixel at pos=(x,y) on image, with color=(r,g,b)."""
r,g,b = color
x,y = pos
image.put("#%02x%02x%02x" % (r,g,b), (y, x))
photo = PhotoImage(width=32, height=32)
pixel(photo, (16,16), (255,0,0)) # One lone pixel in the middle...
label = Label(root, image=photo)
label.grid()
root.mainloop()
And get RGB:
#from http://www.kosbie.net/cmu/spring-14/15-112/handouts/steganographyEncoder.py
def getRGB(image, x, y):
value = image.get(x, y)
return tuple(map(int, value.split(" ")))
There are two directories that looks like JDK.
C:\Program Files\Java\jdk1.7.0_02
C:\Program Files (x86)\Java\jdk1.7.0_02\
This may be due to both 64 bit and 32 bit JDK installed? What ever may be the case, the java.exe
seen by ant.bat should from the JDK. If the JRE's java.exe
comes first in the path, that will be used to guess the JDK location.
Put 'C:\Program Files (x86)\Java\jdk1.7.0_02\bin' or 'C:\Program Files\Java\jdk1.7.0_02' as the first argument in the path.
Further steps:
You can take output of ant -diagnostics
and look for interesting keys. (assuming Sun/Oracle JDK).
java.class.path
java.library.path
sun.boot.library.path
(in my case tools.jar appears in java.class.path)
It's a common misconception that user input can be filtered. PHP even has a (now deprecated) "feature", called magic-quotes, that builds on this idea. It's nonsense. Forget about filtering (or cleaning, or whatever people call it).
What you should do, to avoid problems, is quite simple: whenever you embed a a piece of data within a foreign code, you must treat it according to the formatting rules of that code. But you must understand that such rules could be too complicated to try to follow them all manually. For example, in SQL, rules for strings, numbers and identifiers are all different. For your convenience, in most cases there is a dedicated tool for such an embedding. For example, when you need to use a PHP variable in the SQL query, you have to use a prepared statement, that will take care of all the proper formatting/treatment.
Another example is HTML: If you embed strings within HTML markup, you must escape it with htmlspecialchars
. This means that every single echo
or print
statement should use htmlspecialchars
.
A third example could be shell commands: If you are going to embed strings (such as arguments) to external commands, and call them with exec
, then you must use escapeshellcmd
and escapeshellarg
.
Also, a very compelling example is JSON. The rules are so numerous and complicated that you would never be able to follow them all manually. That's why you should never ever create a JSON string manually, but always use a dedicated function, json_encode()
that will correctly format every bit of data.
And so on and so forth ...
The only case where you need to actively filter data, is if you're accepting preformatted input. For example, if you let your users post HTML markup, that you plan to display on the site. However, you should be wise to avoid this at all cost, since no matter how well you filter it, it will always be a potential security hole.
The API Demos in the Android SDK have an example that does just that.
It's under DIALOG_TEXT_ENTRY
. They have a layout, inflate it with a LayoutInflater
, and use that as the View.
EDIT: What I had linked to in my original answer is stale. Here is a mirror.
A little contribution to the two-bit-fool's answer:
As described on the table on droid phones "orientationchange" event gets fired earlier than "resize" event thus blocking the next resize call (because of the if statement). Width property is still not set.
A workaround though maybe not a perfect one could be to not fire the "orientationchange" event. That can be archived by wrapping "orientationchange" event binding in "if" statement:
if (!navigator.userAgent.match(/android/i))
{
window.addEventListener("orientationchange", checkOrientation, false);
}
Hope it helps
(tests were done on Nexus S)
This first choice might be a confusing one but it’s really very simple. PhoneGap is a product owned by Adobe which currently includes additional build services, and it may or may not eventually offer additional services and/or charge payments for use in the future. Cordova is owned and maintained by Apache, and will always be maintained as an open source project. Currently they both have a very similar API. I would recommend going with Cordova, unless you require the additional PhoneGap build services.
have a look to this site
http://yourdon.com/strucanalysis/wiki/index.php?title=Chapter_9#The_Flow
its really help u to understand what is DFD
I would guess your query isn't running as expected and you are getting to the return line with undefined variables.
Also, the way you are doing the variable assignment, you would be overwriting the same variable with each loop iteration, so you wouldn't return the entire result set.
Finally, it seems odd to return a numerically-keyed result set instead of an associatively-keyed one. Consider naming only the fields needed in the SELECT and keeping the key assignments. So something like this:
Function ShowDataPatient($idURL){
$query =" select * from cmu_list_insurance,cmu_home,cmu_patient where cmu_home.home_id = (select home_id from cmu_patient where patient_hn like '%$idURL%')
AND cmu_patient.patient_hn like '%$idURL%'
AND cmu_list_insurance.patient_id like (select patient_id from cmu_patient where patient_hn like '%$idURL%') ";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
$return = array();
while ($row = pg_fetch_array($result)){
$return[] = $row;
}
return $return;
}
You might also consider opening a question about how to improve your query, is it is pretty heinous as it stands now.
Add namespace
using System.Configuration;
and in place of
ConfigurationSettings.AppSettings
you should use
ConfigurationManager.AppSettings
String path = ConfigurationManager.AppSettings["configFile"];
I can see that this question was originally posted 5 yrs ago when programmers had to work harder to get their desired results. With Visual Studio 2012 and beyond, a lazy programmer can go the Design View for the Listview properties settings, and click on Properties->Sorting, choose Ascending. There are plenty of other properties features to obtain the various results a lazy (aka smart) programmer can leverage.
You can get the protocol, host, and port using this:
window.location.origin
Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
(Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | 11 | ? | 7 (possibly earlier, see webkit bug 46558) |
Android | Edge | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
(Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | ? | ? | 7 (possibly earlier, see webkit bug 46558) |
All browser compatibility is from Mozilla Developer Network
Just use HTML5 :)
<picture>
<source srcset="smaller.jpg" media="(max-width: 768px)">
<source srcset="default.jpg">
<img srcset="default.jpg" alt="My default image">
</picture>
My solution doesn't require the addition of external tools or scripting languages --it's pretty much guaranteed to work on your build machine. I solve this problem in several parts. First, I have created a BUILD.BAT file that converts the Jenkins BUILD_NUMBER parameter into an environment variable. I use Jenkins's "Execute Windows batch command" function to run the build batch file by entering the following information for the Jenkins build:
./build.bat --build_id %BUILD_ID% -build_number %BUILD_NUMBER%
In the build environment, I have a build.bat file that starts as follows:
rem build.bat
set BUILD_ID=Unknown
set BUILD_NUMBER=0
:parse_command_line
IF NOT "%1"=="" (
IF "%1"=="-build_id" (
SET BUILD_ID=%2
SHIFT
)
IF "%1"=="-build_number" (
SET BUILD_NUMBER=%2
SHIFT
)
SHIFT
GOTO :parse_command_line
)
REM your build continues with the environmental variables set
MSBUILD.EXE YourProject.sln
Once I did that, I right-clicked on the project to be built in Visual Studio's Solution Explorer pane and selected Properties, select Build Events, and entered the following information as the Pre-Build Event Command Line, which automatically creates a .cs file containing build number information based on current environment variable settings:
set VERSION_FILE=$(ProjectDir)\Properties\VersionInfo.cs
if !%BUILD_NUMBER%==! goto no_buildnumber_set
goto buildnumber_set
:no_buildnumber_set
set BUILD_NUMBER=0
:buildnumber_set
if not exist %VERSION_FILE% goto no_version_file
del /q %VERSION_FILE%
:no_version_file
echo using System.Reflection; >> %VERSION_FILE%
echo using System.Runtime.CompilerServices; >> %VERSION_FILE%
echo using System.Runtime.InteropServices; >> %VERSION_FILE%
echo [assembly: AssemblyVersion("0.0.%BUILD_NUMBER%.1")] >> %VERSION_FILE%
echo [assembly: AssemblyFileVersion("0.0.%BUILD_NUMBER%.1")] >> %VERSION_FILE%
You may need to adjust to your build taste. I build the project manually once to generate an initial Version.cs file in the Properties directory of the main project. Lastly, I manually include the Version.cs file into the Visual Studio solution by dragging it into the Solution Explorer pane, underneath the Properties tab for that project. In future builds, Visual Studio then reads that .cs file at Jenkins build time and gets the correct build number information out of it.
The hidden-* and visible-* classes no longer exist in Bootstrap 4. The same fucntion can be achieved in Bootstrap 4 by using the d-* for the specific tiers.
Using this function you can get Image Bitmap. Just pass image url
public Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Change display:inline to display:inline-block
.test {
width:200px;
display:inline-block;
overflow: auto;
white-space: nowrap;
margin:0px auto;
border:1px red solid;
}
Firebase listeners fire for both the initial data and any changes.
If you're looking to synchronize the data in a collection, use ChildEventListener
. If you're looking to synchronize a single object, use ValueEventListener
. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.
This is covered in Firebase's quickstart guide for Android. The relevant code and quote:
FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue()); //prints "Do you have data? You'll love Firebase."
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
In the example above, the value event will fire once for the initial state of the data, and then again every time the value of that data changes.
Please spend a few moments to go through that quick start. It shouldn't take more than 15 minutes and it will save you from a lot of head scratching and questions. The Firebase Android Guide is probably a good next destination, for this question specifically: https://firebase.google.com/docs/database/android/read-and-write
Splice is good, everyone explain splice so I didn't explain it. You can also use delete keyword in JavaScript, it's good. You can use $.grep also to manipulate this using jQuery.
The jQuery Way :
data.items = jQuery.grep(
data.items,
function (item,index) {
return item.id != "1";
});
DELETE Way:
delete data.items[0]
For Adding PUSH is better the splice, because splice is heavy weighted function. Splice create a new array , if you have a huge size of array then it may be troublesome. delete is sometime useful, after delete if you look for the length of the array then there is no change in length there. So use it wisely.
<div>
<img src="something.jpg" alt="" />
</div>
div {
width: 48px;
height: 48px;
}
div img {
display: block;
width: 100%;
}
This will make the image expand to fill its parent, of which its size is set in the div
CSS.
Here is the code
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .ok{_x000D_
display : none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div>_x000D_
<div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
An alternative that might make sense especially if this test is being made multiple times and you are running PHP 7+ and have installed the Set
class is:
use Ds\Set;
$strings = new Set(['uk', 'in']);
if (!$strings->contains($some_variable)) {
Or on any version of PHP you can use an associative array to simulate a set:
$strings = ['uk' => 1, 'in' => 1];
if (!isset($strings[$some_variable])) {
There is additional overhead in creating the set but each test then becomes an O(1) operation. Of course the savings becomes greater the longer the list of strings being compared is.
How to measure the time between two operations. Compare the time of two operations.
import time
b = (123*321)*123
t1 = time.time()
c = ((9999^123)*321)^123
t2 = time.time()
print(t2-t1)
7.987022399902344e-05
$this->container->get('security.token_storage')->getToken()->getUser();
For me, in addition to having runAllManagedModulesForAllRequests="true"
I also had to edit the "path"
attribute below. Previously my path attribute was "*."
which means it only executed on url's containing a dot
character. However, my application's url's don't contain a dot. When I switched path to "*"
then it worked.
Here's what I have now:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
I spent more time on this than I should have, and haven't tested in IE for obvious reasons. That being said, it's pretty much identical.
a.boxclose{
float:right;
margin-top:-30px;
margin-right:-30px;
cursor:pointer;
color: #fff;
border: 1px solid #AEAEAE;
border-radius: 30px;
background: #605F61;
font-size: 31px;
font-weight: bold;
display: inline-block;
line-height: 0px;
padding: 11px 3px;
}
.boxclose:before {
content: "×";
}
First of all, CORS is definitely a server-side problem and not client-side but I was more than sure that server code was correct in my case since other apps were working using the same server on different domains. The solution for this described in more details in other answers.
My problem started when I started using axios
with my custom instance. In my case, it was a very specific problem when we use a baseURL in axios
instance and then try to make GET
or POST
calls from anywhere, axios adds a slash / between baseURL and request URL. This makes sense too, but it was the hidden problem. My Laravel server was redirecting to remove the trailing slash which was causing this problem.
In general, the pre-flight OPTIONS
request doesn't like redirects. If your server is redirecting with 301 status code, it might be cached at different levels. So, definitely check for that and avoid it.
if you want to select column with specific name then just do
A=mtcars[,which(conames(mtcars)==cols[1])]
#and then
colnames(mtcars)[A]=cols[1]
you can run it in loop as well reverse way to add dynamic name eg if A is data frame and xyz is column to be named as x then I do like this
A$tmp=xyz
colnames(A)[colnames(A)=="tmp"]=x
again this can also be added in loop
Outputwise both are equivalent. Though the second expression goes through a top down lookup from the DOM root. You might want to avoid the additional overhead (however minuscule it may be) if you already have document.body object in hand for JQuery to wrap over. See http://api.jquery.com/jQuery/ #Selector Context
When you want it to validate (in XML/XHTML - thanks, Loren Segal).
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)