The cleanest way to manage multiple java versions on Mac is to use Homebrew
.
And within Homebrew
, use:
homebrew-cask
to install the versions of javajenv
to manage the installed versions of javaAs seen on http://hanxue-it.blogspot.ch/2014/05/installing-java-8-managing-multiple.html , these are the steps to follow.
Add the homebrew/cask-versions
tap to homebrew using:
brew tap homebrew/cask-versions
Then you can look at all the versions available:
brew search java
Then you can install the version(s) you like:
brew cask install java7
brew cask install java6
And add them to be managed by jenv as usual.
jenv add <javaVersionPathHere>
I think this is the cleanest & simplest way to go about it.
Another important thing to note, as mentioned in Mac OS X 10.6.7 Java Path Current JDK confusing :
For different types of JDKs or installations, you will have different paths
You can check the paths of the versions installed using
/usr/libexec/java_home -V
, see How do I check if the Java JDK is installed on Mac?On Mac OS X Mavericks, I found as following:
1) Built-in JRE default:
/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
2) JDKs downloaded from Apple:
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/
3) JDKs downloaded from Oracle:
/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home
An elegant method would be to use the ~=
compatible release operator according to PEP 440. In your case this would amount to:
package~=0.5.0
As an example, if the following versions exist, it would choose 0.5.9
:
0.5.0
0.5.9
0.6.0
For clarification, each pair is equivalent:
~= 0.5.0
>= 0.5.0, == 0.5.*
~= 0.5
>= 0.5, == 0.*
If you want to list all the files currently being tracked under the branch master
, you could use this command:
git ls-tree -r master --name-only
If you want a list of files that ever existed (i.e. including deleted files):
git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild
using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
okay got it , you have to use ngAfterViewInit
method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit
will not throw any error because it will render after template loading
#include"stdio.h"//rmv coding for randam number access
#include"conio.h"
#include"time.h"
void main()
{
time_t t;
int rmvivek;
srand(time(&t));
rmvivek=1;
while(rmvivek<=5)
{
printf("%c\t",rand()%10);
rmvivek++;
}
getch();
}
I use this with good results:
border-style:hidden;
It also works for:
border-right-style:hidden; /*if you want to hide just a border on a cell*/
Example:
<style type="text/css">_x000D_
table, th, td {_x000D_
border: 2px solid green;_x000D_
}_x000D_
tr.hide_right > td, td.hide_right{_x000D_
border-right-style:hidden;_x000D_
}_x000D_
tr.hide_all > td, td.hide_all{_x000D_
border-style:hidden;_x000D_
}_x000D_
}_x000D_
</style>_x000D_
<table>_x000D_
<tr>_x000D_
<td class="hide_right">11</td>_x000D_
<td>12</td>_x000D_
<td class="hide_all">13</td>_x000D_
</tr>_x000D_
<tr class="hide_right">_x000D_
<td>21</td>_x000D_
<td>22</td>_x000D_
<td>23</td>_x000D_
</tr>_x000D_
<tr class="hide_all">_x000D_
<td>31</td>_x000D_
<td>32</td>_x000D_
<td>33</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Check if the cross product of b-a
and c-a
is0
: that means all the points are collinear. If they are, check if c
's coordinates are between a
's and b
's. Use either the x or the y coordinates, as long as a
and b
are separate on that axis (or they're the same on both).
def is_on(a, b, c):
"Return true iff point c intersects the line segment from a to b."
# (or the degenerate case that all 3 points are coincident)
return (collinear(a, b, c)
and (within(a.x, c.x, b.x) if a.x != b.x else
within(a.y, c.y, b.y)))
def collinear(a, b, c):
"Return true iff a, b, and c all lie on the same line."
return (b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y)
def within(p, q, r):
"Return true iff q is between p and r (inclusive)."
return p <= q <= r or r <= q <= p
This answer used to be a mess of three updates. The worthwhile info from them: Brian Hayes's chapter in Beautiful Code covers the design space for a collinearity-test function -- useful background. Vincent's answer helped to improve this one. And it was Hayes who suggested testing only one of the x or the y coordinates; originally the code had and
in place of if a.x != b.x else
.
Have you tried:
$("#iFrameId").on("load", function () {
// do something once the iframe is loaded
});
You can use normal file operation to create an error log. Just refer this and input this link: PHP File Handling
By using Ado.net
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace PBDataAccess
{
public class AddContact
{
// for preparing connection to sql server database
private SqlConnection conn;
// for preparing sql statement or stored procedure that
// we want to execute on database server
private SqlCommand cmd;
// used for storing the result in datatable, basically
// dataset is collection of datatable
private DataSet ds;
// datatable just for storing single table
private DataTable dt;
// data adapter we use it to manage the flow of data
// from sql server to dataset and after fill the data
// inside dataset using fill() method
private SqlDataAdapter da;
// created a method, which will return the dataset
public DataSet GetAllContactType()
{
// retrieving the connection string from web.config, which will
// tell where our database is located and on which database we want
// to perform opearation, in this case we are working on stored
// procedure so you might have created it somewhere in your database.
// connection string will include the name of the datasource, your
// database name, user name and password.
using (conn = new SqlConnection(ConfigurationManager.ConnectionString["conn"]
.ConnectionString))
{
// Addcontact is the name of the stored procedure
using (cmd = new SqlCommand("Addcontact", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// here we are passing the parameters that
// Addcontact stored procedure expect.
cmd.Parameters.Add("@CommandType",
SqlDbType.VarChar, 50).Value = "GetAllContactType";
// here created the instance of SqlDataAdapter
// class and passed cmd object in it
da = new SqlDataAdapter(cmd);
// created the dataset object
ds = new DataSet();
// fill the dataset and your result will be
stored in dataset
da.Fill(ds);
}
}
return ds;
}
}
****** Stored Procedure ******
CREATE PROCEDURE Addcontact
@CommandType VARCHAR(MAX) = NULL
AS
BEGIN
IF (@CommandType = 'GetAllContactType')
BEGIN
SELECT * FROM Contacts
END
END
If you are concerned about the "unterminated character class" case, removing all non-alphanumeric chars would be helpful:
searchstring = searchstring.replace(/[^a-zA-Z 0-9]+/g,'');
Use git clone c:/folder1 c:/folder2
git clone [--template=<template_directory>] [-l] [-s] [--no-hardlinks]
[-q] [-n] [--bare] [--mirror] [-o <name>] [-b <name>] [-u <upload-pack>]
[--reference <repository>] [--separate-git-dir <git dir>] [--depth <depth>]
[--[no-]single-branch] [--recursive|--recurse-submodules] [--]<repository>
[<directory>]
<repository>
The (possibly remote) repository to clone from.
See the URLS section below for more information on specifying repositories.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory
is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.
Following code is working for me.
Usings:
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
Code:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
string json = responseReader.ReadToEnd();
string data = JObject.Parse(json)["id"].ToString();
}
}
}
//json = {"kind": "ALL", "id": "1221455", "longUrl": "NewURL"}
If this is to be the 'ultimate' discussion, then it should be noted that Larry Leonard's script can query a remote server as well if the servers are linked.
if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable')
print 'Exists'
If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers().disable()
...;
}
}
For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.
Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).
loop over an Array:
var a = [];
for (var i=0; i<a.length; i++) {
i // is the index
a[i] // is the item
}
loop over an Object:
var o = {};
for (var prop in o) {
prop // is the property name
o[prop] // is the property value - the item
}
If the values are integer then you can use [2-3]
or you can use [5,7,8]
for non continuous values.
#!/bin/bash
while [ $# -gt 0 ];
do
case $1 in
1)
echo "one"
;;
[2-3])
echo "two or three"
;;
[4-6])
echo "four to six"
;;
[7,9])
echo "seven or nine"
;;
*)
echo "others"
;;
esac
shift
done
If the values are string then you can use |
.
#!/bin/bash
while [ $# -gt 0 ];
do
case $1 in
"one")
echo "one"
;;
"two" | "three")
echo "two or three"
;;
*)
echo "others"
;;
esac
shift
done
Assaf's response of
Depends on how much money you got...
sounds flippant, but actually it's pertinant.
Only today we had an issue where a record failed to be inserted into our Rate table, because one of the columns (GrossRate) is set to Decimal (11,4), and our Product department just got a contract for rooms in some amazing resort in Bora Bora, that sell for several million Pacific Francs per night... something that was never anticpated when the database schema was designed 10 years ago.
Here is the one that I created based on these requirements:
Replace the pattern regardless of whether is was long or shorter.
Not use any malloc (explicit or implicit) to intrinsically avoid memory leaks.
Replace any number of occurrences of pattern.
Tolerate the replace string having a substring equal to the search string.
Does not have to check that the Line array is sufficient in size to hold the replacement. e.g. This does not work unless the caller knows that line is of sufficient size to hold the new string.
/* returns number of strings replaced.
*/
int replacestr(char *line, const char *search, const char *replace)
{
int count;
char *sp; // start of pattern
//printf("replacestr(%s, %s, %s)\n", line, search, replace);
if ((sp = strstr(line, search)) == NULL) {
return(0);
}
count = 1;
int sLen = strlen(search);
int rLen = strlen(replace);
if (sLen > rLen) {
// move from right to left
char *src = sp + sLen;
char *dst = sp + rLen;
while((*dst = *src) != '\0') { dst++; src++; }
} else if (sLen < rLen) {
// move from left to right
int tLen = strlen(sp) - sLen;
char *stop = sp + rLen;
char *src = sp + sLen + tLen;
char *dst = sp + rLen + tLen;
while(dst >= stop) { *dst = *src; dst--; src--; }
}
memcpy(sp, replace, rLen);
count += replacestr(sp + rLen, search, replace);
return(count);
}
Any suggestions for improving this code are cheerfully accepted. Just post the comment and I will test it.
The best solution for me is
COMPOSER_MEMORY_LIMIT=-1 composer require <package-name>
mentioned by @realtebo
With Spring boot , the spring.config.location does work,just provide comma separated properties files.
see the below code
@PropertySource(ignoreResourceNotFound=true,value="classpath:jdbc-${spring.profiles.active}.properties")
public class DBConfig{
@Value("${jdbc.host}")
private String jdbcHostName;
}
}
one can put the default version of jdbc.properties inside application. The external versions can be set lie this.
java -jar target/myapp.jar --spring.config.location=classpath:file:///C:/Apps/springtest/jdbc.properties,classpath:file:///C:/Apps/springtest/jdbc-dev.properties
Based on profile value set using spring.profiles.active property, the value of jdbc.host will be picked up. So when (on windows)
set spring.profiles.active=dev
jdbc.host will take value from jdbc-dev.properties.
for
set spring.profiles.active=default
jdbc.host will take value from jdbc.properties.
Use Any()
instead of Contains()
:
buildingStatus.Any(item => item.GetCharValue() == v.Status)
I was getting this error until I added (as shown in the code below) $.holdReady(true) at the beginning of my web service call and $.holdReady(false) after it ends. This is jQuery thing to suspend the ready state of the page so any script within document.ready function would be waiting for this (among other possible but unknown to me things).
<span class="AjaxPlaceHolder"></span>
<script type="text/javascript">
$.holdReady(true);
function GetHTML(source, section){
var divToBeWorkedOn = ".AjaxPlaceHolder";
var webMethod = "../MyService.asmx/MyMethod";
var parameters = "{'source':'" + source + "','section':'" + section + "'}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
xhrFields: {
withCredentials: false
},
crossDomain: true,
success: function(data) {
$.holdReady(false);
var myData = data.d;
if (myData != null) {
$(divToBeWorkedOn).prepend(myData.html);
}
},
error: function(e){
$.holdReady(false);
$(divToBeWorkedOn).html("Unavailable");
}
});
}
GetHTML("external", "Staff Directory");
</script>
Step 1:
Add .vs/ to your .gitignore file (as said in other answers).
Step 2:
It is important to understand, that step 1 WILL NOT remove files within .vs/ from your current branch index, if they have already been added to it. So clear your active branch by issuing:
git rm --cached -r .vs/*
Step 3:
Best to immediately repeat steps 1 and 2 for all other active branches of your project as well.
Otherwise you will easily face the same problems again when switching to an uncleaned branch.
Pro tip:
Instead of step 1 you may want to to use this official .gitingore template for VisualStudio that covers much more than just the .vs path:
https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
(But still don't forget steps 2 and 3.)
If a proper encryption method was used, it's not going to be possible to easily retrieve them.
Just reset them with new passwords.
Edit: The string looks like it is using PASSWORD()
:
UPDATE user SET password = PASSWORD("newpassword");
Here is a solution that works with Xcode 10.1 (FEB 23 2019) :
func getCurrentDateTime() {
let now = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "fr_FR")
formatter.dateFormat = "EEEE dd MMMM YYYY"
labelDate.text = formatter.string(from: now)
labelDate.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
labelDate.textColor = UIColor.lightGray
let text = formatter.string(from: now)
labelDate.text = text.uppercased()
}
Quick solution without downloading anything is to use online editors that has "Magic Wand Tool".
You might try turning off pooling, which is enabled by default. See this discussion for more information.
import pyodbc
pyodbc.pooling = False
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
csr = conn.cursor()
csr.close()
del csr
When slicing in Python the third parameter is the step. As others mentioned, see Extended Slices for a nice overview.
With this knowledge, [::3]
just means that you have not specified any start or end indices for your slice. Since you have specified a step, 3
, this will take every third entry of something
starting at the first index. For example:
>>> '123123123'[::3]
'111'
I needed to generate mongodb ids on client side.
After digging into the mongodb source code i found they generate ObjectIDs using npm bson
lib.
If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bson
library :
const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2
Note: There is also an npm project named bson-objectid
being even lighter
If you are inside of Spring bean (in this case @Controller
bean) you shouldn't use Spring context instance at all. Just autowire className
bean directly.
BTW, avoid using field injection as it's considered as bad practice.
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
You could parse the JSON to an object, then create your malformed JSON from the ajavscript object. This may not be the best performance-wise, tho.
Otherwise, if you only need to make very small changes to the string, just treat it as a string, and mangle it using standard javascript.
What I do is take common tasks like centering or floating and make CSS classes out of them. When I do that I can use them throughout any of the pages. I can also call as many as I want on the same element.
.text_center {text-align: center;}
.center {margin: auto 0px;}
.float_left {float: left;}
Now I can use them in my HTML code to perform simple tasks.
<p class="text_center">Some Text</p>
The date function can return this if you specify the format correctly:
$daynum = date("w", strtotime("wednesday"));
will return 0 for Sunday through to 6 for Saturday.
An alternative format is:
$daynum = date("N", strtotime("wednesday"));
which will return 1 for Monday through to 7 for Sunday (this is the ISO-8601 represensation).
1) It is the only difference in C++.
2) POD: plain old data Other classes -> not POD
There are a couple of good solutions here.
Similar to the answer from Harpal, but within the facet, so doesn't require any change to underlying data or pre-plotting manipulation:
# Change this code:
facet_grid(.~size) +
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))
This is flexible, and can be implemented for any variable as you change what element is faceted, no underlying change in the data required.
In python the with
keyword is used when working with unmanaged resources (like file streams). It is similar to the using
statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally
blocks.
From Python Docs:
The
with
statement clarifies code that previously would usetry...finally
blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.The
with
statement is a control-flow structure whose basic structure is:with expression [as variable]: with-block
The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has
__enter__()
and__exit__()
methods).
Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with
with using
.
Yes but its messy hacking the sun classes. There is a simpler way:
http://code.google.com/p/named-regexp/
named-regexp is a thin wrapper for the standard JDK regular expressions implementation, with the single purpose of handling named capturing groups in the .net style : (?...).
It can be used with Java 5 and 6 (generics are used).
Java 7 will handle named capturing groups , so this project is not meant to last.
var node = document.getElementsByClassName("second")[0].firstElementChild
Disclaimer: Browser compliance on getElementsByClassName
and firstElementChild
are shaky. DOM-shims fix those problems though.
Just make a new folder inside C:\xampp\htdocs like C:\xampp\htdocs\test and place your index.php or whatever file in it. Access it by browsing localhost/test/
Good luck!
I had the same problem with small difference:
Exception was raised at the moment of flushing
It is a different stackoverflow issue. The brief explanation was a wrong response header setting:
response.setHeader("Content-Encoding", "gzip");
despite uncompressed response data content.
So the the connection was closed by the browser.
This is the easiest one
You can define your modal behavior, defining data-keyboard and data-backdrop.
<div id="modal" class="modal hide fade in" data-keyboard="false" data-backdrop="static">
If you want to append unique object, you can expand Array struct
extension Array where Element: Equatable {
mutating func appendUniqueObject(object: Generator.Element) {
if contains(object) == false {
append(object)
}
}
}
I've seen a lot of inadequate answers while trying to figure this one out. General response has been "you are trying to stop something that hasn't started" or "some other program is running on the port you need".
The problem for me turned out to be my firewall. I hadn't even considered this, but port 8005 (the port used for shutdown, thanks mindas), was blocked. I changed it, and now, no more error. Good luck.
function getProductionGroupItems($itemId){
$this->db->select("*");
$this->db->where("id",$itemId);
$this->db->or_where("parent_item_id",$itemId);
/*********** order by *********** */
$this->db->order_by("id", "asc");
$q=$this->db->get("recipe_products");
if($q->num_rows()>0){
foreach($q->result() as $row){
$data[]=$row;
}
return $data;
}
return false;
}
Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.com/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
That would be the Enter key.
Based on antoinepairet's comment/example:
Using uib-collapse
attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="collapse navbar-collapse" uib-collapse="navCollapsed">
<ul class="nav navbar-nav">
...
</ul>
</div>
</nav>
I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:
The only variation from the official bootstrap example is the addition of ng-
attributes noted by comments, below:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- note the ng-class here -->
<div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">
<ul class="nav navbar-nav">
...
Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)
This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!
You can refer this one too, I have written step by step procedure of Manual Crash Re-Symbolication.
STEP 1
Move all the above files (MyApp.app, MyApp-dSYM.dSYM and MyApp-Crash-log.crash) into a Folder with a convenient name wherever you can go using Terminal easily.
For me, Desktop is the most easily reachable place ;) So, I have moved these three files into a folder MyApp at Desktop.
STEP 2
Now its turn of Finder, Go to the path from following whichever is applicable for your XCODE version.
Use this command to find the symbolicatecrash
script file,
find /Applications/Xcode.app -name symbolicatecrash
Xcode 8, Xcode 9, Xcode 11 /Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash
Xcode 7.3
/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash
XCode 7 /Applications/Xcode.app/Contents/SharedFrameworks/DTDeviceKitBase.framework/Versions/A/Resources/symbolicatecrash
Xcode 6 /Applications/Xcode.app/Contents/SharedFrameworks/DTDeviceKitBase.framework/Versions/A/Resources
Lower then Xcode 6
Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKitBase.framework/Versions/A/Resources
Or
Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKit.framework/Versions/A/Resources
STEP 3
Add the found symbolicatecrash script file's directory to $PATH
env variable like this: sudo vim /etc/paths.d/Xcode-symbolicatecrash
and paste the script file's directory and save the file. When opening a new terminal, you can call symbolicatecrash
at any folder as commands located in /usr/bin
.
Or
Copy symbolicatecrash file from this location, and paste it to the Desktop/MyApp (Wait… Don’t blindly follow me, I am pasting sybolicatecrash file in folder MyApp, one that you created in step one at your favorite location, having three files.)
STEP 4
Open Terminal, and CD to the MyApp Folder.
cd Desktop/MyApp — Press Enter
export DEVELOPER_DIR=$(xcode-select --print-path)
— Press Enter
./symbolicatecrash -v MyApp-Crash-log.crash MyApp.dSYM
— Press Enter
That’s it !! Symbolicated logs are on your terminal… now what are you waiting for? Now simply, Find out the Error and resolve it ;)
Happy Coding !!!
When using JetBrains IntelliJ, first enable "Attach memory agent" in File | Settings | Build, Execution, Deployment | Debugger.
When debugging, right-click a variable of interest and choose "Calculate Retained Size":
Version 5.5 of PHP will have built-in support for BCrypt, the functions password_hash()
and password_verify()
. Actually these are just wrappers around the function crypt()
, and shall make it easier to use it correctly. It takes care of the generation of a safe random salt, and provides good default values.
The easiest way to use this functions will be:
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
This code will hash the password with BCrypt (algorithm 2y
), generates a random salt from the OS random source, and uses the default cost parameter (at the moment this is 10). The second line checks, if the user entered password matches an already stored hash-value.
Should you want to change the cost parameter, you can do it like this, increasing the cost parameter by 1, doubles the needed time to calculate the hash value:
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));
In contrast to the "cost"
parameter, it is best to omit the "salt"
parameter, because the function already does its best to create a cryptographically safe salt.
For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash()
function. For PHP versions before 5.3.7 there is no support for crypt()
with 2y
, the unicode safe BCrypt algorithm. One could replace it instead with 2a
, which is the best alternative for earlier PHP versions.
Create Bean for Rest Template to auto wiring the Rest Template object.
@SpringBootApplication
public class ChatAppApplication {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ChatAppApplication.class, args);
}
}
Consume the GET/POST API by using RestTemplate - exchange() method. Below is for the post api which is defined in the controller.
@RequestMapping(value = "/postdata",method = RequestMethod.POST)
public String PostData(){
return "{\n" +
" \"value\":\"4\",\n" +
" \"name\":\"David\"\n" +
"}";
}
@RequestMapping(value = "/post")
public String getPostResponse(){
HttpHeaders headers=new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity=new HttpEntity<String>(headers);
return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody();
}
Refer this tutorial[1]
[1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm
The question revolves around how this
keyword behaves in javascript. this
behaves differently as below,
this
is usually determined by a function execution context.this
refers to the global object (the window
object).this
will be undefined
as in strict mode, global object refers to undefined
in place of the window
object.call()
, bind()
, and apply()
new
keyword is used (a constructor), this is bound to the new object being created.this
— instead, this
is bound lexically (i.e. based on the original context)As most of the answers suggest, we can use Arrow function or bind()
Method or Self var. I would quote a point about lambdas (Arrow function) from Google JavaScript Style Guide
Prefer using arrow functions over f.bind(this), and especially over goog.bind(f, this). Avoid writing const self = this. Arrow functions are particularly useful for callbacks, which sometimes pass unexpectedly additional arguments.
Google clearly recommends using lambdas rather than bind or const self = this
So the best solution would be to use lambdas as below,
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', () => {
alert(this.data);
});
}
References:
This is the main difference between username variable and whoami command:
C:\Users\user.name>echo %username%
user.name
C:\Users\user.name>whoami
domain\user.name
DOMAIN = bios name of the domain (not fqdn)
I tried out most options mentioned previously but found this small and intuitive package to be the best: pympler
It's quite straight forward to trace objects that were not garbage-collected, check this small example:
install package via pip install pympler
from pympler.tracker import SummaryTracker
tracker = SummaryTracker()
# ... some code you want to investigate ...
tracker.print_diff()
The output shows you all the objects that have been added, plus the memory they consumed.
Sample output:
types | # objects | total size
====================================== | =========== | ============
list | 1095 | 160.78 KB
str | 1093 | 66.33 KB
int | 120 | 2.81 KB
dict | 3 | 840 B
frame (codename: create_summary) | 1 | 560 B
frame (codename: print_diff) | 1 | 480 B
This package provides a number of more features. Check pympler's documentation, in particular the section Identifying memory leaks.
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
[
"@babel/plugin-proposal-class-properties"
]
]
}
replace your .babelrc file with above code. it fixed the issue for me.
The best way I found so far, is just two lines of code:
curl http://python-distribute.org/distribute_setup.py | python
curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python
It was tested on Windows 8 with PowerShell, Cmd, and Git Bash (MinGW).
And you probably want to add the path to your environment. It's somewhere like C:\Python33\Scripts
.
<h4>Order List</h4>
<ul>
<li ng-repeat="val in filter_option.order">
<span>
<input title="{{filter_option.order_name[$index]}}" type="radio" ng-model="filter_param.order_option" ng-value="'{{val}}'" />
{{filter_option.order_name[$index]}}
</span>
<select title="" ng-model="filter_param[val]">
<option value="asc">Asc</option>
<option value="desc">Desc</option>
</select>
</li>
</ul>
If you're using Bash, the solution is to use $'string'
, for example:
$ STR=$'Hello\nWorld'
$ echo "$STR" # quotes are required here!
Hello
World
If you're using pretty much any other shell, just insert the newline as-is in the string:
$ STR='Hello
> World'
Bash is pretty nice. It accepts more than just \n
in the $''
string. Here is an excerpt from the Bash manual page:
Words of the form $'string' are treated specially. The word expands to
string, with backslash-escaped characters replaced as specified by the
ANSI C standard. Backslash escape sequences, if present, are decoded
as follows:
\a alert (bell)
\b backspace
\e
\E an escape character
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\' single quote
\" double quote
\nnn the eight-bit character whose value is the octal value
nnn (one to three digits)
\xHH the eight-bit character whose value is the hexadecimal
value HH (one or two hex digits)
\cx a control-x character
The expanded result is single-quoted, as if the dollar sign had not
been present.
A double-quoted string preceded by a dollar sign ($"string") will cause
the string to be translated according to the current locale. If the
current locale is C or POSIX, the dollar sign is ignored. If the
string is translated and replaced, the replacement is double-quoted.
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
If you installed the system image and still get this error, it might be that the Android SDK manager did not put the files in the right folder for the AVD manager. See an answer to Stack Overflow question How to create an AVD for Android 4.0.3? (Unable to find a 'userdata.img').
web.xml
they are in the servlet container configuration files (server.xml
on tomcat)No. But the default servlet (mapped in a web.xml at a common location in your servlet container) should preferably disable file listings (so that users don't see the contents of your web folders):
listings true
As another answer mentioned, you can now do this in C11 with _Generic
.
For example, here's a macro that will check if some input is compatible with another type:
#include <stdbool.h>
#define isCompatible(x, type) _Generic(x, type: true, default: false)
You can use the macro like so:
double doubleVar;
if (isCompatible(doubleVar, double)) {
printf("doubleVar is of type double!\n"); // prints
}
int intVar;
if (isCompatible(intVar, double)) {
printf("intVar is compatible with double too!\n"); // doesn't print
}
This can also be used on other types, including structs. E.g.
struct A {
int x;
int y;
};
struct B {
double a;
double b;
};
int main(void)
{
struct A AVar = {4, 2};
struct B BVar = {4.2, 5.6};
if (isCompatible(AVar, struct A)) {
printf("Works on user-defined types!\n"); // prints
}
if (isCompatible(BVar, struct A)) {
printf("And can differentiate between them too!\n"); // doesn't print
}
return 0;
}
And on typedefs.
typedef char* string;
string greeting = "Hello world!";
if (isCompatible(greeting, string)) {
printf("Can check typedefs.\n");
}
However, it doesn't always give you the answer you expect. For instance, it can't distinguish between an array and a pointer.
int intArray[] = {4, -9, 42, 3};
if (isCompatible(intArray, int*)) {
printf("Treats arrays like pointers.\n");
}
// The code below doesn't print, even though you'd think it would
if (isCompatible(intArray, int[4])) {
printf("But at least this works.\n");
}
Answer borrowed from here: http://www.robertgamble.net/2012/01/c11-generic-selections.html
It is nice to verify that the code you pushed actually got committed.
You can get a log of changes on a bare repository by explicitly setting the path using the --relative option.
$ cd test_repo
$ git log --relative=/
This will show you the committed changes as if this was a regular git repo.
Try moving the lapsList
function out of your class and into your render function:
render() {
const lapsList = this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
return (
<View style={styles.container}>
<View style={styles.footer}>
<View><Text>coucou test</Text></View>
{lapsList}
</View>
</View>
)
}
You can do this by just changing the html. Here's an example:
<hmtl>
<head>
<title>Some title</title>
</head>
<body>
<map name="navigatemap">
<area shape="rect"
coords="166,4,319,41"
href="WII.htm"
onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'"
onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverWII).png'"
/>
<area shape="rect"
coords="330,4,483,41"
href="OT.htm"
onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'"
onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverOT).png'"
/>
<area shape="rect"
coords="491,3,645,41"
href="OP.htm"
onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'"
onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverOP).png'"
/>
</map>
<img src="Assets/NavigationBar(OnHome).png"
name="navbar"
usemap="#navigatemap" />
</body>
</html>
I created a dummy variable for every state using this code.
def create_dummy_column(series, f):
return series.apply(f)
for el in df.area_title.unique():
col_name = el.split()[0] + "_dummy"
f = lambda x: int(x==el)
df[col_name] = create_dummy_column(df.area_title, f)
df.head()
More generally, I would just use .apply and pass it an anonymous function with the inequality that defines your category.
(Thank you to @prpl.mnky.dshwshr for the .unique() insight)
This article seems to offer a pretty good overview of the difference.
From the page:
Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to “image”, but the BUTTON element type allows content.
The Button Element - W3C
With Angular 7, I got it working by using the following without using HttpParams.
import { HttpClient } from '@angular/common/http';
export class ApiClass {
constructor(private httpClient: HttpClient) {
// use it like this in other services / components etc.
this.getDataFromServer().
then(res => {
console.log('res: ', res);
});
}
getDataFromServer() {
const params = {
param1: value1,
param2: value2
}
const url = 'https://api.example.com/list'
// { params: params } is the same as { params }
// look for es6 object literal to read more
return this.httpClient.get(url, { params }).toPromise();
}
}
I had the same issue and the url below really helped me.
It might help you as well.
Your question is: are these not modules capable of declaring variables at global scope?
Answer: YES, they are "capable"
The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1
, e.g.)
References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).
For instance, place in Sheet1 code
Public glob_sh1 As String
Sub test_sh1()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
place in ThisWorkbook code
Public glob_this As String
Sub test_this()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
and in a Standard Module code
Public glob_mod As String
Sub test_mod()
glob_mod = "glob_mod"
ThisWorkbook.glob_this = "glob_this"
Sheet1.glob_sh1 = "glob_sh1"
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
All three subs work fine.
PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).
PS2: Your line Debug.Print ("Hello")
will give you the compile error Invalid outside procedure
.
PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.
PS4: Check also Put Excel-VBA code in module or sheet?.
PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.
PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.
It is very bad style to define external interfaces in .c files. .
You should do this
a.h
extern void doSomething (int sig);
a.c
void doSomething (int sig)
{
... do stuff
}
b.c
#include "a.h"
.....
signal(SIGNAL, doSomething);
.
dicejs.com (formally cssobjs) is a client-side version of SASS. You can set variables in your CSS (stored in json formatted CSS) and re-use your color variables.
//create the CSS JSON object with variables and styles
var myCSSObjs = {
cssVariables : {
primaryColor:'#FF0000',
padSmall:'5px',
padLarge:'$expr($padSmall * 2)'
}
'body' : {padding:'$padLarge'},
'h1' : {margin:'0', padding:'0 0 $padSmall 0'},
'.pretty' : {padding:'$padSmall', margin:'$padSmall', color:'$primaryColor'}
};
//give your css objects a name and inject them
$.cssObjs('myStyles',myCSSObjs).injectStyles();
And here is a link to a complete downloadable demo which is a little more helpful then their documentation : dicejs demo
You can:
click file-> new ->create project from existing project
select your original file, eg. solution 1 and input the new file name solution 2
change the project name in the new solution 2
You can try :
DECLARE @counter int
SET @counter = 0
UPDATE [table]
SET [column] = @counter, @counter = @counter + 1```
a do while loop would be a nice way to wait for the user input. Like this:
int main()
{
do
{
cout << '\n' << "Press a key to continue...";
} while (cin.get() != '\n');
return 0;
}
You can also use the function system('PAUSE')
but I think this is a bit slower and platform dependent
You can try VSCommands extension from Visual Studio Gallery. Latest release allows you to select two file and compare them:
Just use
y_pred = (y_pred > 0.5)
accuracy_score(y_true, y_pred, normalize=False)
Here is my solution.
///// find duplicates in an array and remove them
void unique(int* input, int n)
{
merge_sort(input, 0, n) ;
int prev = 0 ;
for(int i = 1 ; i < n ; i++)
{
if(input[i] != input[prev])
if(prev < i-1)
input[prev++] = input[i] ;
}
}
Simple answer: (watch for blank & null)
isNaN(+'111') = false;
isNaN(+'111r') = true;
isNaN(+'r') = true;
isNaN(+'') = false;
isNaN(null) = false;
Data table to List
#region "getobject filled object with property reconized"
public List<T> ConvertTo<T>(DataTable datatable) where T : new()
{
List<T> Temp = new List<T>();
try
{
List<string> columnsNames = new List<string>();
foreach (DataColumn DataColumn in datatable.Columns)
columnsNames.Add(DataColumn.ColumnName);
Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));
return Temp;
}
catch
{
return Temp;
}
}
public T getObject<T>(DataRow row, List<string> columnsName) where T : new()
{
T obj = new T();
try
{
string columnname = "";
string value = "";
PropertyInfo[] Properties;
Properties = typeof(T).GetProperties();
foreach (PropertyInfo objProperty in Properties)
{
columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
if (!string.IsNullOrEmpty(columnname))
{
value = row[columnname].ToString();
if (!string.IsNullOrEmpty(value))
{
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
{
value = row[columnname].ToString().Replace("$", "").Replace(",", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
}
else
{
value = row[columnname].ToString().Replace("%", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
}
}
}
}
return obj;
}
catch
{
return obj;
}
}
#endregion
IEnumerable collection To Datatable
#region "New DataTable"
public DataTable ToDataTable<T>(IEnumerable<T> collection)
{
DataTable newDataTable = new DataTable();
Type impliedType = typeof(T);
PropertyInfo[] _propInfo = impliedType.GetProperties();
foreach (PropertyInfo pi in _propInfo)
newDataTable.Columns.Add(pi.Name, pi.PropertyType);
foreach (T item in collection)
{
DataRow newDataRow = newDataTable.NewRow();
newDataRow.BeginEdit();
foreach (PropertyInfo pi in _propInfo)
newDataRow[pi.Name] = pi.GetValue(item, null);
newDataRow.EndEdit();
newDataTable.Rows.Add(newDataRow);
}
return newDataTable;
}
HTML css works fine if body tag does nothing you can write as well
<body scroll="no" style="overflow: hidden">
In this case overriding should be on the body tag, it is easier to control but sometimes gives headaches.
"On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip."
Have you tried it?
In the ideal case we should have enough memory to read the file in one read operation. That would be the best performer because we let the system manage File System , allocation units and HDD at will. In practice you are fortunate to know the file sizes in advance, just use the average file size rounded up to 4K (default allocation unit on NTFS). And best of all : create a benchmark to test multiple options.
A character class in regular expressions, denoted by the [...]
syntax, specifies the rules to match a single character in the input. As such, everything you write between the brackets specify how to match a single character.
Your pattern, [01-12]
is thus broken down as follows:
So basically all you're matching is 0, 1 or 2.
In order to do the matching you want, matching two digits, ranging from 01-12 as numbers, you need to think about how they will look as text.
You have:
You will then have to write a regular expression for that, which can look like this:
+-- a 0 followed by 1-9
|
| +-- a 1 followed by 0-2
| |
<-+--> <-+-->
0[1-9]|1[0-2]
^
|
+-- vertical bar, this roughly means "OR" in this context
Note that trying to combine them in order to get a shorter expression will fail, by giving false positive matches for invalid input.
For instance, the pattern [0-1][0-9]
would basically match the numbers 00-19, which is a bit more than what you want.
I tried finding a definite source for more information about character classes, but for now all I can give you is this Google Query for Regex Character Classes. Hopefully you'll be able to find some more information there to help you.
You can use this
"abcdefg".index('c') #=> 2
I'm in the same situation as you and the solution I found for cleaning the data is deleting all the CoreData stuff that my view controllers rely on to draw it's info. But I still found this approach to be very bad, I think that a more elegant way to do this can be accomplished without storyboards and using only code to manage the transitions between view controllers.
I've found this project at Github that does all this stuff only by code and it's quite easy to understand. They use a Facebook-like side menu and what they do is change the center view controller depending if the user is logged-in or not. When the user logs out the appDelegate
removes the data from CoreData and sets the main view controller to the login screen again.
I think you've missed the point of access control.
A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.
Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee
) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.
In your specific case, it seems that paste.ee
doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
@GünterZöchbauer also you can save it in localstorage but I not prefer it ) better to save in service and get this value from there
constructor(
private router: Router
) {
this.router.events
.subscribe((event) => {
if (event instanceof NavigationEnd) {
localStorage.setItem('previousUrl', event.url);
}
});
}
Could it be this, what you want to have:
# Initial list:
myList <- list()
# Now the new experiments
for(i in 1:3){
myList[[length(myList)+1]] <- list(sample(1:3))
}
myList
You should use URL and URLSearchParams native functions:
let url = new URL("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8&q=mdn%20query%20string")_x000D_
let params = new URLSearchParams(url.search);_x000D_
let sourceid = params.get('sourceid') // 'chrome-instant'_x000D_
let q = params.get('q') // 'mdn query string'_x000D_
let ie = params.has('ie') // true_x000D_
params.append('ping','pong')_x000D_
_x000D_
console.log(sourceid)_x000D_
console.log(q)_x000D_
console.log(ie)_x000D_
console.log(params.toString())_x000D_
console.log(params.get("ping"))
_x000D_
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams https://polyfill.io/v2/docs/features/
I encountered a similar problem while using Sourcetree with newly created files (they wouldnt be included in the stash either).
When I first chose 'stage all' and then stash the newly added components where tracked and therefore included in the stash.
We can replace the code in the AndroidManifest file in the application tag
android:icon="@drawable/logo"
Fall-through is really a handy thing, depending on what you're doing. Consider this neat and understandable way to arrange options:
switch ($someoption) {
case 'a':
case 'b':
case 'c':
// Do something
break;
case 'd':
case 'e':
// Do something else
break;
}
Imagine doing this with if/else. It would be a mess.
Type float, 32 bits long, has a precision of 7 digits. While it may store values with very large or very small range (+/- 3.4 * 10^38 or * 10^-38), it has only 7 significant digits.
Type double, 64 bits long, has a bigger range (*10^+/-308) and 15 digits precision.
Type long double is nominally 80 bits, though a given compiler/OS pairing may store it as 12-16 bytes for alignment purposes. The long double has an exponent that just ridiculously huge and should have 19 digits precision. Microsoft, in their infinite wisdom, limits long double to 8 bytes, the same as plain double.
Generally speaking, just use type double when you need a floating point value/variable. Literal floating point values used in expressions will be treated as doubles by default, and most of the math functions that return floating point values return doubles. You'll save yourself many headaches and typecastings if you just use double.
Blat:
blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body"
The auto keyword is simply asking the compiler to deduce the type of the variable from the initialization.
Even a pre-C++0x compiler knows what the type of an (initialization) expression is, and more often than not, you can see that type in error messages.
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int>s;
s.push_back(11);
s.push_back(22);
s.push_back(33);
s.push_back(55);
for (int it=s.begin();it!=s.end();it++){
cout<<*it<<endl;
}
}
Line 12: error: cannot convert '__gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<int*, __gnu_norm::vector<int, std::allocator<int> > >, __gnu_debug_def::vector<int, std::allocator<int> > >' to 'int' in initialization
The auto keyword simply allows you to take advantage of this knowledge - if you (compiler) know the right type, just choose for me!
Without explicitly defining the height
I determined I need to apply the flex
value to the parent and grandparent div
elements...
<div style="display: flex;">
<div style="display: flex;">
<img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>
If you're using a single element (e.g. dead-centered text in a single flex
element) use the following:
align-items: center;
display: flex;
justify-content: center;
Vue.component('task', {
template: '#task-template',
props: ['list'],
computed: {
middleData() {
return this.list
}
},
watch: {
list(newVal, oldVal) {
console.log(newVal)
this.newList = newVal
}
},
data() {
return {
newList: {}
}
}
});
new Vue({
el: '.container'
})
Maybe this will meet your needs.
I believe that the most reliable way to get the external server ip address would be to use an external service.
ipaddr=$(curl -s http://whatismyip.akamai.com/)
Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.
Anyway, I'd just do this:
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).
(I don't see anything obviously wrong with the code you have posted above)
Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?
Another solution based on the latest standard of URLSearchParams (https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
function getQueryParamsObject() {
const searchParams = new URLSearchParams(location.search.slice(1));
return searchParams
? _.fromPairs(Array.from(searchParams.entries()))
: {};
}
Please note that this solution is making use of
Array.from (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
and _.fromPairs (https://lodash.com/docs#fromPairs) of lodash for the sake of simplicity.
It should be easy to create a more compatible solution since you have access to searchParams.entries() iterator.
from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedAray|object} source Can be an url to where a PDF is
* located, a typed array (Uint8Array) already populated with data or
* and parameter object with the following possible fields:
* - url - The URL of the PDF.
* - data - A typed array with PDF data.
* - httpHeaders - Basic authentication headers.
* - password - For decrypting password-protected PDFs.
*
* @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
*/
So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).
But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
tl;dr
var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
This is Very Good Example of minus Length of an array in java, i am giving here both examples
public static int linearSearchArray(){
int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7};
int key = 7;
int i = 0;
int count = 0;
for ( i = 0; i< arrayOFInt.length; i++){
if ( arrayOFInt[i] == key ){
System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] );
count ++;
}
}
System.out.println("this Element found the ("+ count +") number of Times");
return i;
}
this above i < arrayOFInt.length; not need to minus one by length of array; but if you i <= arrayOFInt.length -1; is necessary other wise arrayOutOfIndexException Occur, hope this will help you.
Here is a generic way to convert array to ArrayList
<T> ArrayList<T> toArrayList(Object o, Class<T> type){
ArrayList<T> objects = new ArrayList<>();
for (int i = 0; i < Array.getLength(o); i++) {
//noinspection unchecked
objects.add((T) Array.get(o, i));
}
return objects;
}
Usage
ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);
You can use filterfalse function from itertools module
Example
import random
from itertools import filterfalse
random.seed(42)
data = [random.randrange(5) for _ in range(10)]
clean = [*filterfalse(lambda i: i == 0, data)]
print(f"Remove 0s\n{data=}\n{clean=}\n")
clean = [*filterfalse(lambda i: i in (0, 1), data)]
print(f"Remove 0s and 1s\n{data=}\n{clean=}")
Output:
Remove 0s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 1, 1, 1, 4, 4]
Remove 0s and 1s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 4, 4]
This is how I've "handled" it if you use pluck to get an identifier for each of the records, join the arrays together and then finally do a query for those joined ids:
transaction_ids = @club.type_a_trans.pluck(:id) + @club.type_b_transactions.pluck(:id) + @club.type_c_transactions.pluck(:id)
@transactions = Transaction.where(id: transaction_ids).limit(100)
Binary Tree is a specialized form of tree with two child (left child and right Child). It is simply representation of data in Tree structure
Binary Search Tree (BST) is a special type of Binary Tree that follows following condition:
Looking for EventHandling, ActionListener?
or code?
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textfield.setText("");
//textfield.setText(null); //or use this
}
});
Also See
How to Use Buttons
Also, for simulating a slow connection on some *nixes, you can try using ipfw. More information is provided by Ben Newman's answer on this Quora question
If an axes (generated by code below the code shown in the question) is sharing the range with the first axes, make sure that you set the range after the last plot of that axes.
argparse
is an easy solutionExample compatible with both Python versions 2 and 3:
#!/usr/bin/python
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('infile',
default=sys.stdin,
type=argparse.FileType('r'),
nargs='?')
args = parser.parse_args()
data = args.infile.read()
You can run this script in many ways:
1. Using stdin
echo 'foo bar' | ./above-script.py
or shorter by replacing echo
by here string:
./above-script.py <<< 'foo bar'
2. Using a filename argument
echo 'foo bar' > my-file.data
./above-script.py my-file.data
3. Using stdin
through the special filename -
echo 'foo bar' | ./above-script.py -
localhost
is special in MySQL, it means a connection over a UNIX socket (or named pipes on Windows, I believe) as opposed to a TCP/IP socket. Using %
as the host does not include localhost
, hence the need to explicitly specify it.
classic solution:
for f in $(find . -name "*dbg*"); do mv $f $(echo $f | sed 's/_dbg//'); done
The hold on
feature is switched on by default in matplotlib.pyplot
. So each time you evoke plt.plot()
before plt.show()
a drawing is added to the plot. Launching plt.plot()
after the function plt.show()
leads to redrawing the whole picture.
Wikipedia says:
Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
In detail, when you have an object foo that has a void hello() function:
class foo {
virtual void hello(); // Code : printf("Hello!");
}
A child of foo, will also have a hello() function:
class bar : foo {
// no functions in here but yet, you can call
// bar.hello()
}
However, you may want to print "Hello Bar!" when hello() function is being called from a bar object. You can do this using override
class bar : foo {
virtual void hello() override; // Code : printf("Hello Bar!");
}
Solution using Decorators that survives minification/uglification
We use code generation to decorate our Entity classes with metadata like so:
@name('Customer')
export class Customer {
public custId: string;
public name: string;
}
Then consume with the following helper:
export const nameKey = Symbol('name');
/**
* To perserve class name though mangling.
* @example
* @name('Customer')
* class Customer {}
* @param className
*/
export function name(className: string): ClassDecorator {
return (Reflect as any).metadata(nameKey, className);
}
/**
* @example
* const type = Customer;
* getName(type); // 'Customer'
* @param type
*/
export function getName(type: Function): string {
return (Reflect as any).getMetadata(nameKey, type);
}
/**
* @example
* const instance = new Customer();
* getInstanceName(instance); // 'Customer'
* @param instance
*/
export function getInstanceName(instance: Object): string {
return (Reflect as any).getMetadata(nameKey, instance.constructor);
}
Extra info:
reflect-metadata
reflect-metadata
is pollyfill written by members ot TypeScript for the proposed ES7 Reflection APIThe function Correlate of numpy works with 2 1D arrays that you want to correlate and returns one correlation value.
Simply find all the selected <option>
tags within your <select>
and remove the selected
attribute:
$("#my_select option:selected").removeAttr("selected");
As of jQuery 1.6, you should use .prop
instead of removing the attribute:
$("#my_select option:selected").prop("selected", false);
You can use below code on onSuccess(LoginResult loginResult)
loginResult.getAccessToken().getUserId();
a = ['1', '2', '3']
ls = []
count = False
while ls != a :
print(a[count])
if a[count] != a[-1] :
count = count + 1
else :
count = False
Restart while loop.
My problem: Find indexes of list.
L = makelist() # Returns a list of different objects
La = np.array(L, dtype = object) # add dtype!
for c in chunks:
L_ = La[c] # Since La is array, this works.
I realize this has been answered, but there is a slight issue with the accepted solution. It will return false positives. Easy to fix:
SELECT * FROM Products P
WHERE (@Status='published' and P.Status IN (1,3))
or (@Status='standby' and P.Status IN (2,5,9,6))
or (@Status='deleted' and P.Status IN (4,5,8,10))
or (@Status not in ('published','standby','deleted') and P.Status IN (1,2))
Parentheses aren't needed (although perhaps easier to read hence why I included them).
I use fetchObject() here a small example using Symfony 4.4
<?php
use Doctrine\DBAL\Driver\Connection;
class MyController{
public function index($username){
$queryBuilder = $connection->createQueryBuilder();
$queryBuilder
->select('id', 'name')
->from('app_user')
->where('name = ?')
->setParameter(0, $username)
->setMaxResults(1);
$stmUser = $queryBuilder->execute();
dump($stmUser->fetchObject());
//get_class_methods($stmUser) -> to see all methods
}
}
Response:
{
"id": "2", "name":"myuser"
}
Try this:
CREATE PROCEDURE MyProc @excludedlist integer_list_tbltype READONLY AS
SELECT * FROM A WHERE ID NOT IN (@excludedlist)
And then call it like this:
DECLARE @ExcludedList integer_list_tbltype
INSERT @ExcludedList(n) VALUES(3, 4, 22)
exec MyProc @ExcludedList
Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.
If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:
Original answer:
Here is a not-so-great "ng-if" directive:
myApp.directive('ngIf', function() {
return {
link: function(scope, element, attrs) {
if(scope.$eval(attrs.ngIf)) {
// remove '<div ng-if...></div>'
element.replaceWith(element.children())
} else {
element.replaceWith(' ')
}
}
}
});
that allows for this HTML syntax:
<div ng-repeat="message in data.messages" ng-class="message.type">
<hr>
<div ng-if="showFrom(message)">
<div>From: {{message.from.name}}</div>
</div>
<div ng-if="showCreatedBy(message)">
<div>Created by: {{message.createdBy.name}}</div>
</div>
<div ng-if="showTo(message)">
<div>To: {{message.to.name}}</div>
</div>
</div>
replaceWith() is used to remove unneeded content from the DOM.
Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?
The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.
E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from
, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.
On Ubuntu 18.04:
sudo systemctl restart postgresql.service
Below code will look for last used row in sheet1 and copy the entire range from A1 upto last used row in column A to Sheet2 at exact same location.
Sub test()
Dim lastRow As Long
lastRow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Sheet2").Range("A1:A" & lastRow).Value = Sheets("Sheet1").Range("A1:A" & lastRow).Value
End Sub
You can use PHP, JSP, ASP or any other server side script to connect with mysql database and and return JSON data that you can parse it to in your android app this link how to do it
russfrisch commented 4 days ago:
I was experiencing this same issue. Changing in the version for grunt-node-inspector to prepend a ">=" instead of a "~" got this to work for me.
Link to github page where I found this solution.
You can accomplish the result using sh
/bat
step and readFile
:
node {
sh 'env > env.txt'
readFile('env.txt').split("\r?\n").each {
println it
}
}
Unfortunately env.getEnvironment()
returns very limited map of environment variables.
I had a similar issue. I had both anaconda and python installed on my computer and my python dependencies were from the Anaconda directory. When I uninstalled Anaconda, this error started popping. I added PYTHONPATH
but it still didn't go.
I checked with python -version
and go to know that it was still taking the anaconda path.
I had to manually delete Anaconda3 directory and after that python started taking dependencies from PYTHONPATH
.
Issue Solved!
I find it very useful to append both stdout and stderr to a log file. I was glad to see a solution by alfonx with exec > >(tee -a)
, because I was wondering how to accomplish this using exec
. I came across a creative solution using here-doc syntax and .
: https://unix.stackexchange.com/questions/80707/how-to-output-text-to-both-screen-and-file-inside-a-shell-script
I discovered that in zsh, the here-doc solution can be modified using the "multios" construct to copy output to both stdout/stderr and the log file:
#!/bin/zsh
LOG=$0.log
# 8 is an arbitrary number;
# multiple redirects for the same file descriptor
# triggers "multios"
. 8<<\EOF /dev/fd/8 2>&2 >&1 2>>$LOG >>$LOG
# some commands
date >&2
set -x
echo hi
echo bye
EOF
echo not logged
It is not as readable as the exec
solution but it has the advantage of allowing you to log just part of the script. Of course, if you omit the EOF then the whole script is executed with logging. I'm not sure how zsh
implements multios, but it may have less overhead than tee
. Unfortunately it seems that one cannot use multios with exec
.
var result = projects.Where(p => filtedTags.All(t => p.Tags.Contains(t)));
I have tried all of the above solutions (which all bring valid points), but nothing was working for me.
Until I found that my MySQL table field mappings in C# was using an incorrect type: MySqlDbType.Blob . I changed it to MySqlDbType.Text and now I can write all the UTF8 symbols I want!
p.s. My MySQL table field is of the "LongText" type. However, when I autogenerated the field mappings using MyGeneration software, it automatically set the field type as MySqlDbType.Blob in C#.
Interestingly, I have been using the MySqlDbType.Blob type with UTF8 characters for many months with no trouble, until one day I tried writing a string with some specific characters in it.
Hope this helps someone who is struggling to find a reason for the error.
You can now use the npm package sequelize-auto-migrations to automatically generate a migrations file. https://www.npmjs.com/package/sequelize-auto-migrations
Using sequelize-cli, initialize your project with
sequelize init
Create your models and put them in your models folder.
Install sequelize-auto-migrations:
npm install sequelize-auto-migrations
Create an initial migration file with
node ./node_modules/sequelize-auto-migrations/bin/makemigration --name <initial_migration_name>
Run your migration:
node ./node_modules/sequelize-auto-migrations/bin/runmigration
You can also automatically generate your models from an existing database, but that is beyond the scope of the question.
At first use ExecuteScalar
objConn = new SqlConnection(strConnection);
objConn.Open();
objCmd = new SqlCommand(strSQL, objConn);
object result = cmd.ExecuteScalar();
if(result == null)
strLevel = "";
else
strLevel = result.ToString();
The plattform agnostic way would be 'sLineBreak': http://www.freepascal.org/docs-html/rtl/system/slinebreak.html
Write('Hello' + sLineBreak + 'World!');
The most simple way is to use Record type Record<number, productDetails >
interface productDetails {
productId : number ,
price : number ,
discount : number
};
const myVar : Record<number, productDetails> = {
1: {
productId : number ,
price : number ,
discount : number
}
}
this function worked for me
<?php
function everything_in_tags($string, $tagname)
{
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match($pattern, $string, $matches);
return $matches[1];
}
?>
You can just pass a list of the two points you want to connect to plt.plot
. To make this easily expandable to as many points as you want, you could define a function like so.
import matplotlib.pyplot as plt
x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5, 1, -0.5, -1]
plt.plot(x,y, 'ro')
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'k-')
connectpoints(x,y,0,1)
connectpoints(x,y,2,3)
plt.axis('equal')
plt.show()
Note, that function is a general function that can connect any two points in your list together.
To expand this to 2N points, assuming you always connect point i
to point i+1
, we can just put it in a for loop:
import numpy as np
for i in np.arange(0,len(x),2):
connectpoints(x,y,i,i+1)
In that case of always connecting point i
to point i+1
, you could simply do:
for i in np.arange(0,len(x),2):
plt.plot(x[i:i+2],y[i:i+2],'k-')
Change your code to:
System.out.println("AM or PM?");
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();
if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
...
if(Hours == 13){
if (TimeOfDayStringQ.equals("AM")) {
TimeOfDayStringQ = "PM"; // <--
} else {
TimeOfDayStringQ = "AM"; // <--
}
Hours = 1;
}
}
Everything in one line:
get-aduser -filter * -Properties memberof | select name, @{ l="GroupMembership"; e={$_.memberof -join ";" } } | export-csv membership.csv
I never liked the key code validation. My approach was to see if the input have text (any character), confirming that the user is entering text and no other characters
$('#input').on('keyup', function() {_x000D_
var words = $(this).val();_x000D_
// if input is empty, remove the word count data and return_x000D_
if(!words.length) {_x000D_
$(this).removeData('wcount');_x000D_
return true;_x000D_
}_x000D_
// if word count data equals the count of the input, return_x000D_
if(typeof $(this).data('wcount') !== "undefined" && ($(this).data('wcount') == words.length)){_x000D_
return true;_x000D_
}_x000D_
// update or initialize the word count data_x000D_
$(this).data('wcount', words.length);_x000D_
console.log('user tiped ' + words);_x000D_
// do you stuff..._x000D_
});
_x000D_
<html lang="en">_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<input type="text" name="input" id="input">_x000D_
</body>_x000D_
</html>
_x000D_
Another solution for this old post (for those that it might help) :
<application android:name=".BaseApplication" ... >
public class BaseApplication extends Application {
private class Status {
public boolean isVisible = true;
public boolean isFocused = true;
}
private Map<Activity, Status> activities;
@Override
public void onCreate() {
activities = new HashMap<Activity, Status>();
super.onCreate();
}
private boolean hasVisibleActivity() {
for (Status status : activities.values())
if (status.isVisible)
return true;
return false;
}
private boolean hasFocusedActivity() {
for (Status status : activities.values())
if (status.isFocused)
return true;
return false;
}
public void onActivityCreate(Activity activity, boolean isStarting) {
if (isStarting && activities.isEmpty())
onApplicationStart();
activities.put(activity, new Status());
}
public void onActivityStart(Activity activity) {
if (!hasVisibleActivity() && !hasFocusedActivity())
onApplicationForeground();
activities.get(activity).isVisible = true;
}
public void onActivityWindowFocusChanged(Activity activity, boolean hasFocus) {
activities.get(activity).isFocused = hasFocus;
}
public void onActivityStop(Activity activity, boolean isFinishing) {
activities.get(activity).isVisible = false;
if (!isFinishing && !hasVisibleActivity() && !hasFocusedActivity())
onApplicationBackground();
}
public void onActivityDestroy(Activity activity, boolean isFinishing) {
activities.remove(activity);
if(isFinishing && activities.isEmpty())
onApplicationStop();
}
private void onApplicationStart() {Log.i(null, "Start");}
private void onApplicationBackground() {Log.i(null, "Background");}
private void onApplicationForeground() {Log.i(null, "Foreground");}
private void onApplicationStop() {Log.i(null, "Stop");}
}
public class MyActivity extends BaseActivity {...}
public class BaseActivity extends Activity {
private BaseApplication application;
@Override
protected void onCreate(Bundle state) {
application = (BaseApplication) getApplication();
application.onActivityCreate(this, state == null);
super.onCreate(state);
}
@Override
protected void onStart() {
application.onActivityStart(this);
super.onStart();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
application.onActivityWindowFocusChanged(this, hasFocus);
super.onWindowFocusChanged(hasFocus);
}
@Override
protected void onStop() {
application.onActivityStop(this, isFinishing());
super.onStop();
}
@Override
protected void onDestroy() {
application.onActivityDestroy(this, isFinishing());
super.onDestroy();
}
}
const clonedFunction = Object.assign(() => {}, originalFunction);
Add below code in your client code :
static {
Security.insertProviderAt(new BouncyCastleProvider(),1);
}
with this there is no need to add any entry in java.security file.
I had the same problem. In my case, the issue was that someone used BeanUtils to copy the properties of one entity to another, so we ended up having two entities referencing the same collection.
Given that I spent some time investigating this issue, I would recommend the following checklist:
Look for scenarios like entity1.setCollection(entity2.getCollection())
and getCollection
returns the internal reference to the collection (if getCollection() returns a new instance of the collection, then you don't need to worry).
Look if clone()
has been implemented correctly.
Look for BeanUtils.copyProperties(entity1, entity2)
.
For me it works only with any of these solutions
$(this).select2('val', null);
or
$(this).select2('val', '');
I may be late to the party here but can you not just use the .change() event that jQuery provides.
You should be able to do something like ...
$(#CONTROLID).change(function(){
do your stuff here ...
});
You could always bind it to a list of controls with something like ...
var flds = $("input, textarea", window.document);
flds.live('change keyup', function() {
do your code here ...
});
The live binder ensures that all elements that exist on the page now and in the future are handled.
You can set this programmatically in the controller:-
HttpContext.Current.Server.ScriptTimeout = 300;
Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)
That may be also interesting in context of adding INTERNET permission to your application:
Google has also given each app Internet access, effectively removing the Internet access permission. Oh, sure, Android developers still have to declare they want Internet access when putting together the app. But users can no longer see the Internet access permission when installing an app and current apps that don’t have Internet access can now gain Internet access with an automatic update without prompting you.
Bottom line is that you still have to add INTERNET permission in manifest file but application will be updated on user's devices without asking them for new permission.
background-image: url(path-to-file/img.jpg);
background-repeat:no-repeat;
background-position: center center;
That should work.
If not, why not make a div
with the image and use z-index
to make it the background? This would be much easier to center than a background image on the body.
Other than that try:
background-position: 0 100px;/*use a pixel value that will center it*/
Or I think you can use 50% if you have set your body min-height
to 100%.
body{
background-repeat:no-repeat;
background-position: center center;
background-image:url(../images/images2.jpg);
color:#FFF;
font-family:Arial, Helvetica, sans-serif;
min-height:100%;
}
First case:
A normal product lookup would look like this
http://our.api.com/product/1
So Im thinking that best practice would be for you to do this
http://our.api.com/Product/101404,7267261
Second Case
Search with querystring parameters - fine like this. I would be tempted to combine terms with AND and OR instead of using []
.
PS This can be subjective, so do what you feel comfortable with.
The reason for putting the data in the url is so the link can pasted on a site/ shared between users. If this isnt an issue, by all means use a JSON/ POST instead.
EDIT: On reflection I think this approach suits an entity with a compound key, but not a query for multiple entities.
You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks:
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
# # for python 2.x:
# plt.bar(range(len(D)), D.values(), align='center') # python 2.x
# plt.xticks(range(len(D)), D.keys()) # in python 2.x
plt.show()
Note that the penultimate line should read plt.xticks(range(len(D)), list(D.keys()))
in python3, because D.keys()
returns a generator, which matplotlib cannot use directly.
There's a great article on Mozilla's MDN docs that describes exactly this issue:
The "Unicode Problem" Since
DOMString
s are 16-bit-encoded strings, in most browsers callingwindow.btoa
on a Unicode string will cause aCharacter Out Of Range exception
if a character exceeds the range of a 8-bit byte (0x00~0xFF). There are two possible methods to solve this problem:
- the first one is to escape the whole string (with UTF-8, see
encodeURIComponent
) and then encode it;- the second one is to convert the UTF-16
DOMString
to an UTF-8 array of characters and then encode it.
A note on previous solutions: the MDN article originally suggested using unescape
and escape
to solve the Character Out Of Range
exception problem, but they have since been deprecated. Some other answers here have suggested working around this with decodeURIComponent
and encodeURIComponent
, this has proven to be unreliable and unpredictable. The most recent update to this answer uses modern JavaScript functions to improve speed and modernize code.
If you're trying to save yourself some time, you could also consider using a library:
function b64EncodeUnicode(str) {
// first we use encodeURIComponent to get percent-encoded UTF-8,
// then we convert the percent encodings into raw bytes which
// can be fed into btoa.
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
b64EncodeUnicode('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('\n'); // "Cg=="
function b64DecodeUnicode(str) {
// Going backwards: from bytestream, to percent-encoding, to original string.
return decodeURIComponent(atob(str).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"
b64DecodeUnicode('Cg=='); // "\n"
Here is the the current recommendation, direct from MDN, with some additional TypeScript compatibility via @MA-Maddin:
// Encoding UTF8 ? base64
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode(parseInt(p1, 16))
}))
}
b64EncodeUnicode('? à la mode') // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('\n') // "Cg=="
// Decoding base64 ? UTF8
function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
}).join(''))
}
b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU=') // "? à la mode"
b64DecodeUnicode('Cg==') // "\n"
This used escape
and unescape
(which are now deprecated, though this still works in all modern browsers):
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
// Usage:
utf8_to_b64('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"
And one last thing: I first encountered this problem when calling the GitHub API. To get this to work on (Mobile) Safari properly, I actually had to strip all white space from the base64 source before I could even decode the source. Whether or not this is still relevant in 2017, I don't know:
function b64_to_utf8( str ) {
str = str.replace(/\s/g, '');
return decodeURIComponent(escape(window.atob( str )));
}
First, disable the php5
module:
a2dismod php5
then, enable the php7
module:
a2enmod php7.0
Next, reload/restart the Apache service:
service apache2 restart
wrt the comment, you need to specify exact installed php-7.x version.
There are a couple of ways:
To delete it directly:
SomeModel.objects.filter(id=id).delete()
To delete it from an instance:
instance = SomeModel.objects.get(id=id)
instance.delete()
The data type TEXT is old and should not be used anymore, it is a pain to select data out of a TEXT column.
ntext, text, and image (Transact-SQL)
ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
you need to use TEXTPTR (Transact-SQL) to retrieve the text data.
Also see this article on Handling The Text Data Type.
You need to use the files
parameter to send a multipart form POST request even when you do not need to upload any files.
From the original requests source:
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
...
:param files: (optional) Dictionary of ``'name': file-like-objects``
(or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``,
3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``,
where ``'content-type'`` is a string
defining the content type of the given file
and ``custom_headers`` a dict-like object
containing additional headers to add for the file.
The relevant part is: file-tuple can be a
2-tuple
, 3-tuple
or a
4-tuple
.
Based on the above, the simplest multipart form request that includes both files to upload and form fields will look like this:
multipart_form_data = {
'file2': ('custom_file_name.zip', open('myfile.zip', 'rb')),
'action': (None, 'store'),
'path': (None, '/path1')
}
response = requests.post('https://httpbin.org/post', files=multipart_form_data)
print(response.content)
☝ Note the None
as the first argument in the tuple for plain text fields — this is a placeholder for the filename field which is only used for file uploads, but for text fields passing None
as the first parameter is required in order for the data to be submitted.
If you need to post multiple fields with the same name then instead of a dictionary you can define your payload as a list (or a tuple) of tuples:
multipart_form_data = (
('file2', ('custom_file_name.zip', open('myfile.zip', 'rb'))),
('action', (None, 'store')),
('path', (None, '/path1')),
('path', (None, '/path2')),
('path', (None, '/path3')),
)
If the above API is not pythonic enough for you, then consider using requests toolbelt (pip install requests_toolbelt
) which is an extension of the core requests module that provides support for file upload streaming as well as the MultipartEncoder which can be used instead of files
, and which also lets you define the payload as a dictionary, tuple or list.
MultipartEncoder
can be used both for multipart requests with or without actual upload fields. It must be assigned to the data
parameter.
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
multipart_data = MultipartEncoder(
fields={
# a file upload field
'file': ('file.zip', open('file.zip', 'rb'), 'text/plain')
# plain text fields
'field0': 'value0',
'field1': 'value1',
}
)
response = requests.post('http://httpbin.org/post', data=multipart_data,
headers={'Content-Type': multipart_data.content_type})
If you need to send multiple fields with the same name, or if the order of form fields is important, then a tuple or a list can be used instead of a dictionary:
multipart_data = MultipartEncoder(
fields=(
('action', 'ingest'),
('item', 'spam'),
('item', 'sausage'),
('item', 'eggs'),
)
)
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
According to docs
Handle messages in a backgrounded app
When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
This includes messages that contain both notification and data payload. In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
If you want to open your app and perform a specific action, set click_action in the notification payload and map it to an intent filter in the Activity you want to launch. For example, set click_action to OPEN_ACTIVITY_1 to trigger an intent filter like the following:
<intent-filter> <action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Edit :
Based on this thread :
You can't set click_action payload using Firebase Console. You could try testing with a curl command or a custom http server
curl --header "Authorization: key=<YOUR_KEY_GOES_HERE>"
--header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send
-d "{\"to\":\"/topics/news\",\"notification\":
{\"title\": \"Click Action Message\",\"text\": \"Sample message\",
\"click_action\":\"OPEN_ACTIVITY_1\"}}"
I would say that you need to check if the state already has the same value you are trying to set. If it's the same, there is no point to set state again for the same value.
Make sure to set your state like this:
let top = newValue /*true or false*/
if(top !== this.state.top){
this.setState({top});
}
I had Lombok plugin, annotations enabled, it was compiling from command line - everything and it still did not see my project as maven (all maven dependencies were red in source files). Then I clicked SHIFT twice and searched for 'maven' and among results there was 'Reload all Maven Projects'. After running it Maven tab appeared and I was able to compile, and all red underlining in source code disappeared.
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.I don't like $.inArray(..)
, it's the kind of ugly, jQuery-ish solution that most sane people wouldn't tolerate. Here's a snippet which adds a simple contains(str)
method to your arsenal:
$.fn.contains = function (target) {
var result = null;
$(this).each(function (index, item) {
if (item === target) {
result = item;
}
});
return result ? result : false;
}
Similarly, you could wrap $.inArray
in an extension:
$.fn.contains = function (target) {
return ($.inArray(target, this) > -1);
}
<?php
$args = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args );
?>
This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products
Instead of setting async to false which is usually bad design, you may want to consider blocking the UI while the operation is pending.
This can be nicely achieved with jQuery promises as follows:
// same as $.ajax but settings can have a maskUI property
// if settings.maskUI==true, the UI will be blocked while ajax in progress
// if settings.maskUI is other than true, it's value will be used as the color value while bloking (i.e settings.maskUI='rgba(176,176,176,0.7)'
// in addition an hourglass is displayed while ajax in progress
function ajaxMaskUI(settings) {
function maskPageOn(color) { // color can be ie. 'rgba(176,176,176,0.7)' or 'transparent'
var div = $('#maskPageDiv');
if (div.length === 0) {
$(document.body).append('<div id="maskPageDiv" style="position:fixed;width:100%;height:100%;left:0;top:0;display:none"></div>'); // create it
div = $('#maskPageDiv');
}
if (div.length !== 0) {
div[0].style.zIndex = 2147483647;
div[0].style.backgroundColor=color;
div[0].style.display = 'inline';
}
}
function maskPageOff() {
var div = $('#maskPageDiv');
if (div.length !== 0) {
div[0].style.display = 'none';
div[0].style.zIndex = 'auto';
}
}
function hourglassOn() {
if ($('style:contains("html.hourGlass")').length < 1) $('<style>').text('html.hourGlass, html.hourGlass * { cursor: wait !important; }').appendTo('head');
$('html').addClass('hourGlass');
}
function hourglassOff() {
$('html').removeClass('hourGlass');
}
if (settings.maskUI===true) settings.maskUI='transparent';
if (!!settings.maskUI) {
maskPageOn(settings.maskUI);
hourglassOn();
}
var dfd = new $.Deferred();
$.ajax(settings)
.fail(function(jqXHR, textStatus, errorThrown) {
if (!!settings.maskUI) {
maskPageOff();
hourglassOff();
}
dfd.reject(jqXHR, textStatus, errorThrown);
}).done(function(data, textStatus, jqXHR) {
if (!!settings.maskUI) {
maskPageOff();
hourglassOff();
}
dfd.resolve(data, textStatus, jqXHR);
});
return dfd.promise();
}
with this you can now do:
ajaxMaskUI({
url: url,
maskUI: true // or try for example 'rgba(176,176,176,0.7)'
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log('error ' + textStatus);
}).done(function (data, textStatus, jqXHR) {
console.log('success ' + JSON.stringify(data));
});
And the UI will block until the ajax command returns
see jsfiddle
def match_string(words):
nums = 0
letter = 0
other = 0
for i in words :
if i.isalpha():
letter+=1
elif i.isdigit():
nums+=1
else:
other+=1
return nums,letter,other
x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>
You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).
You must login to have a valid session before downloading anything below.
*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)
*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.
Xcode 12
12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)
12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)
12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)
Xcode 11
11.7 (Latest as of Sept 02 2020)
11.4.1 (Requires macOS 10.15.2 or later)
11 (Requires macOS 10.14.4 or later)
Xcode 10 (unsupported for iTunes Connect)
Xcode 9
Xcode 8
Xcode 7
Xcode 6
Even Older Versions (unsupported for iTunes Connect)
I think you should give the data types of the column as NUMERIC or DOUBLE or FLOAT or REAL
Read http://sqlite.org/datatype3.html to more info.
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Assuming the Python code above is saved into a file called prog.py
$ python prog.py -h
Ref-link: https://docs.python.org/3.3/library/argparse.html
function refreshPage()
{
jQuery.mobile.changePage(window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
});
}
Taken from here http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/ also tested on jQuery Mobile 1.2.0
you could always try:
Regex r = new Regex(@"\d{2}/\d{2}/\d{4}");
r.isMatch(inputString);
this will check that the string is in the format "02/02/2002" you may need a bit more if you want to ensure that it is a valid date like dd/mm/yyyy
There are two options here.
Edit
@Html.Hidden("clubid", ViewBag.Club.id)
or
@using(Html.BeginForm("action", "controller",
new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n
will work.
If you use anything else you will cause issues with cut and paste on Windows platforms.
The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n
linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.
Interestingly, in spite of the Unix line end convention being \n
, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n
. Yes, it may not make a lot of sense, but that's history and evolving standards for you!
Coding toolbar (Edit > Toolbars > Coding) and select Code Format Settings to set your preferred formatting.
You can also access the formatting option from Commands > Apply Source Formatting or only apply it to a select block of code by selecting the Apply Source Formatting to Selection option.
http://www.hongkiat.com/blog/10-useful-dreamweaver-tips-for-beginners/
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
As the accepted answer has two important shortfalls, I'm posting the improved answer for those new comers who are looking for a correct answer:
foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
// Do something with $file
}
globe
function results with is_file
is necessary, because it might return some directories as well..
in their names, so */*
pattern sucks in general.If you use the callback URL, then the API can connect to the callback URL and send or receive some data. That means API can connect to you later (after API call).
Exact definition should be in API documentation.
is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):
It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.
A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.
Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.
{<interpolatedExpression>[,<alignment>][:<formatString>]}
Where:
The following code example concatenates a string where an object, author as a part of the string interpolation.
string author = "Mohit";
string hello = $"Hello {author} !";
Console.WriteLine(hello); // Hello Mohit !
Read more on C#/.NET Little Wonders: String Interpolation in C# 6
What is exactly the function of the LayoutInflater?
When you design using XML, all your UI elements are just tags and parameters. Before you can use these UI elements, (eg a TextView or LinearLayout), you need to create the actual objects corresponding to these xml elements. That is what the inflater is for. The inflater, uses these tags and their corresponding parameters to create the actual objects and set all the parameters. After this you can get a reference to the UI element using findViewById().
Why do all the articles that I've read check if convertview is null or not first? What does it mean when it is null and what does it mean when it isn't?
This is an interesting one. You see, getView() is called everytime an item in the list is drawn. Now, before the item can be drawn, it has to be created. Now convertView basically is the last used view to draw an item. In getView() you inflate the xml first and then use findByViewID() to get the various UI elements of the listitem. When we check for (convertView == null) what we do is check that if a view is null(for the first item) then create it, else, if it already exists, reuse it, no need to go through the inflate process again. Makes it a lot more efficient.
You must also have come across a concept of ViewHolder in getView(). This makes the list more efficient. What we do is create a viewholder and store the reference to all the UI elements that we got after inflating. This way, we can avoid calling the numerous findByViewId() and save on a lot of time. This ViewHolder is created in the (convertView == null) condition and is stored in the convertView using setTag(). In the else loop we just obtain it back using getView() and reuse it.
What is the parent parameter that this method accepts?
The parent is a ViewGroup to which your view created by getView() is finally attached. Now in your case this would be the ListView.
Hope this helps :)
This was one I tried using Win32:
import win32com.client as win32
import psutil
import os
import subprocess
import sys
# Drafting and sending email notification to senders. You can add other senders' email in the list
def send_notification():
outlook = win32.Dispatch('outlook.application')
olFormatHTML = 2
olFormatPlain = 1
olFormatRichText = 3
olFormatUnspecified = 0
olMailItem = 0x0
newMail = outlook.CreateItem(olMailItem)
newMail.Subject = sys.argv[1]
#newMail.Subject = "check"
newMail.BodyFormat = olFormatHTML #or olFormatRichText or olFormatPlain
#newMail.HTMLBody = "test"
newMail.HTMLBody = sys.argv[2]
newMail.To = "[email protected]"
attachment1 = sys.argv[3]
attachment2 = sys.argv[4]
newMail.Attachments.Add(attachment1)
newMail.Attachments.Add(attachment2)
newMail.display()
# or just use this instead of .display() if you want to send immediately
newMail.Send()
# Open Outlook.exe. Path may vary according to system config
# Please check the path to .exe file and update below
def open_outlook():
try:
subprocess.call(['C:\Program Files\Microsoft Office\Office15\Outlook.exe'])
os.system("C:\Program Files\Microsoft Office\Office15\Outlook.exe");
except:
print("Outlook didn't open successfully")
#
# Checking if outlook is already opened. If not, open Outlook.exe and send email
for item in psutil.pids():
p = psutil.Process(item)
if p.name() == "OUTLOOK.EXE":
flag = 1
break
else:
flag = 0
if (flag == 1):
send_notification()
else:
open_outlook()
send_notification()
Looks to me like to would be something like
library(tutoR)
format(1.128347132904321674821, 2)
Per a little online help.
For multiple lines the best way I find is to do this:
IEnumerable<string> lines = new List<string>
{
string.Format("{{ line with formatting... {0} }}", id),
"line 2",
"line 3"
};
StringBuilder sb = new StringBuilder();
foreach(var line in lines)
sb.AppendLine(line);
In this way you don't have to clutter the screen with the Environment.NewLine or AppendLine() repeated multiple times. It will also be less error prone than having to remember to type them.
Let's say you have an associative array like this:
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => array('x'=>123)
);
In the first iteration : $key="one"
and $value=1
.
Sometimes you need this key ,if you want only the value , you can avoid using it.
In the last iteration : $key='seventeen'
and $value = array('x'=>123)
so to get value of the first element in this array
value, you need a key
, x in this case: $value['x'] =123
.
If you want to want to treat 1,2 and 2,1 as the same pair, then this will give you the unique list on MS-SQL:
SELECT DISTINCT
CASE WHEN a > b THEN a ELSE b END as a,
CASE WHEN a > b THEN b ELSE a END as b
FROM pairs
Inspired by @meszias answer above
One way is using the immediate selector and negative margin. This rule will select a list right after a paragraph, so it's just setting a negative margin-top.
p + ul {
margin-top: -XX;
}
If I've understood your question correctly, then you are looking for the mouseup
event, rather than the click
event:
$("#message_link").mouseup(function() {
//Do stuff here
});
The mouseup
event fires when the mouse button is released, and does not take into account whether the mouse button was pressed on that element, whereas click
takes into account both mousedown
and mouseup
.
However, click
should work fine, because it won't actually fire until the mouse button is released.
A free open source community run geolocation ip service that runs on the MaxMind database is available here: https://ipstack.com/
Example
https://api.ipstack.com/160.39.144.19
Limitation
10,000 queries per month
something like this should work...
String name = "Test2";//Name of the class
Class myClass = Class.forName(name);
Object o = myClass.newInstance();
Issue resolved.!!! Below are the solutions.
For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar
Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
Issue is that it is failed to decrypt 256 bits of encryption.
function converter()
{
var number = $(.number).text();
var number = 'Rp. '+number;
s(.number).val(number);
}
If you know you're always going to use bash, it's much easier to always use the double bracket conditional compound command [[ ... ]]
, instead of the Posix-compatible single bracket version [ ... ]
. Inside a [[ ... ]]
compound, word-splitting and pathname expansion are not applied to words, so you can rely on
if [[ $aug1 == "and" ]];
to compare the value of $aug1
with the string and
.
If you use [ ... ]
, you always need to remember to double quote variables like this:
if [ "$aug1" = "and" ];
If you don't quote the variable expansion and the variable is undefined or empty, it vanishes from the scene of the crime, leaving only
if [ = "and" ];
which is not a valid syntax. (It would also fail with a different error message if $aug1
included white space or shell metacharacters.)
The modern [[
operator has lots of other nice features, including regular expression matching.