Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.
Use the keyword size
instead of fontsize
.
using System.Diagnostics;
...
var st = new StackTrace();
var sf = st.GetFrame(0);
var currentMethodName = sf.GetMethod();
Or, if you'd like to have a helper method:
[MethodImpl(MethodImplOptions.NoInlining)]
public string GetCurrentMethod()
{
var st = new StackTrace();
var sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
Updated with credits to @stusmith.
Use string interpolation instead.
print '%d %f' % (count,conv)
If the issue is that your SpringBootApplication/Configuration you are bringing in is component scanning the package your test configurations are in, you can actually remove the @Configuration annotation from the test configurations and you can still use them in the @SpringBootTest annotations. For example, if you have a class Application that is your main configuration and a class TestConfiguration that is a configuration for certain, but not all tests, you can set up your classes as follows:
@Import(Application.class) //or the specific configurations you want
//(Optional) Other Annotations that will not trigger an autowire
public class TestConfiguration {
//your custom test configuration
}
And then you can configure your tests in one of two ways:
With the regular configuration:
@SpringBootTest(classes = {Application.class}) //won't component scan your configuration because it doesn't have an autowire-able annotation
//Other annotations here
public class TestThatUsesNormalApplication {
//my test code
}
With the test custom test configuration:
@SpringBootTest(classes = {TestConfiguration.class}) //this still works!
//Other annotations here
public class TestThatUsesCustomTestConfiguration {
//my test code
}
This native way will help to convert any inputted format to the desired format.
$formatInput = 'd-m-Y'; //Give any format here, this would be converted into your format
$dateInput = '01-02-2018'; //date in above format
$formatOut = 'Y-m-d'; // Your format
$dateOut = DateTime::createFromFormat($formatInput, $dateInput)->format($formatOut);
There is no problem with displaying HTML code in blade templates.
For test, you can add to routes.php only one route:
Route::get('/', function () {
$data = new stdClass();
$data->page_desc
= '<strong>aaa</strong><em>bbb</em>
<p>New paragaph</p><script>alert("Hello");</script>';
return View::make('hello')->with('content', $data);
}
);
and in hello.blade.php
file:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
{{ $content->page_desc }}
</body>
</html>
For the following code you will get output as on image
So probably page_desc
in your case is not what you expect. But as you see it can be potential dangerous if someone uses for example '` tag so you should probably in your route before assigning to blade template filter some tags
EDIT
I've also tested it with putting the same code into database:
Route::get('/', function () {
$data = User::where('id','=',1)->first();
return View::make('hello')->with('content', $data);
}
);
Output is exactly the same in this case
Edit2
I also don't know if Pages
is your model or it's a vendor model. For example it can have accessor inside:
public function getPageDescAttribute($value)
{
return htmlspecialchars($value);
}
and then when you get page_desc
attribute you will get modified page_desc
with htmlspecialchars
. So if you are sure that data in database is with raw html (not escaped) you should look at this Pages
class
I found a good and complete solution for English
function slugify(string) {
return string
.toString()
.trim()
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\-]+/g, "")
.replace(/\-\-+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "");
}
Some examples of it in use:
slugify(12345);
// "12345"
slugify(" string with leading and trailing whitespace ");
// "string-with-leading-and-trailing-whitespace"
slugify("mIxEd CaSe TiTlE");
// "mixed-case-title"
slugify("string with - existing hyphens -- ");
// "string-with-existing-hyphens"
slugify("string with Special™ characters");
// "string-with-special-characters"
Thanks to Andrew Stewart
For what it's worth, on KitKat+ it seems that adapter.notifyDataSetChanged()
is enough to cause the new views to show up, provided that you've setOffscreenPageLimit
sufficiently high. I'm able to get desired behavior by doing viewPager.setOffscreenPageLimit(2)
.
check RegisterRoutes method in global.asax.cs - it's the default place for route configuration...
Another way could be like this:
$letters = array("a", "b", "c", "d", "e", "f", "g");
$result = substr(implode(", ", $letters), 0, -3);
Output of $result
is a nicely formatted comma-separated list.
a, b, c, d, e, f, g
Using some of the info in here I ended up creating my own function to use.
Could be used as...
custom_alert();
custom_alert( 'Display Message' );
custom_alert( 'Display Message', 'Set Title' );
jQuery UI Alert Replacement
function custom_alert( message, title ) {
if ( !title )
title = 'Alert';
if ( !message )
message = 'No Message to Display.';
$('<div></div>').html( message ).dialog({
title: title,
resizable: false,
modal: true,
buttons: {
'Ok': function() {
$( this ).dialog( 'close' );
}
}
});
}
you can just use this code to hit the script using cron job using cpanel:
wget https://www.example.co.uk/unique-code
The first line defines the variable. The second line loops it to 100, the third adds 1 to a and the 4th divides a by 3 and if there is no remainder (0) it will print that number otherwise it will print a blank line.
a = (0)
for i in range(0,100):
a = a + 1
if a % 3 == 0:
print(a)
else:
print("")
Inside Layout Xml File We can Change Color of Hint.....
android:textColorHint="@android:color/*****"
you can replace * with color or color code.
Agreeing with r-dub, keep it in source control, but to me, the real benefit is this:
collaboration in identical environments (disregarding the windohs and linux/mac stuff). Before Gemfile.lock, the next dude to install the project might see all kinds of confusing errors, blaming himself, but he was just that lucky guy getting the next version of super gem, breaking existing dependencies.
Worse, this happened on the servers, getting untested version unless being disciplined and install exact version. Gemfile.lock makes this explicit, and it will explicitly tell you that your versions are different.
Note: remember to group stuff, as :development and :test
After installing any version of Xcode targeting Intel-based Macs, you should be able to write assembly code. Xcode is a suite of tools, only one of which is the IDE, so you don't have to use it if you don't want to. (That said, if there are specific things you find clunky, please file a bug at Apple's bug reporter - every bug goes to engineering.) Furthermore, installing Xcode will install both the Netwide Assembler (NASM) and the GNU Assembler (GAS); that will let you use whatever assembly syntax you're most comfortable with.
You'll also want to take a look at the Compiler & Debugging Guides, because those document the calling conventions used for the various architectures that Mac OS X runs on, as well as how the binary format and the loader work. The IA-32 (x86-32) calling conventions in particular may be slightly different from what you're used to.
Another thing to keep in mind is that the system call interface on Mac OS X is different from what you might be used to on DOS/Windows, Linux, or the other BSD flavors. System calls aren't considered a stable API on Mac OS X; instead, you always go through libSystem. That will ensure you're writing code that's portable from one release of the OS to the next.
Finally, keep in mind that Mac OS X runs across a pretty wide array of hardware - everything from the 32-bit Core Single through the high-end quad-core Xeon. By coding in assembly you might not be optimizing as much as you think; what's optimal on one machine may be pessimal on another. Apple regularly measures its compilers and tunes their output with the "-Os" optimization flag to be decent across its line, and there are extensive vector/matrix-processing libraries that you can use to get high performance with hand-tuned CPU-specific implementations.
Going to assembly for fun is great. Going to assembly for speed is not for the faint of heart these days.
I created a method fixUntrustCertificate(), so when I am dealing with a domain that is not in trusted CAs you can invoke the method before the request. This code will gonna work after java1.4. This method applies for all hosts:
public void fixUntrustCertificate() throws KeyManagementException, NoSuchAlgorithmException{
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// set the allTrusting verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
}
}
Just to add some specific settings, I had a similar setup (with Apache 2.0.63 reverse proxying onto Tomcat 5.0.27).
For certain URLs the Tomcat server could take perhaps 20 minutes to return a page.
I ended up modifying the following settings in the Apache configuration file to prevent it from timing out with its proxy operation (with a large over-spill factor in case Tomcat took longer to return a page):
Timeout 5400
ProxyTimeout 5400
ProxyTimeout alone wasn't enough. Looking at the documentation for Timeout I'm guessing (I'm not sure) that this is because while Apache is waiting for a response from Tomcat, there is no traffic flowing between Apache and the Browser (or whatever http client) - and so Apache closes down the connection to the browser.
I found that if I left the Timeout setting at its default (300 seconds), then if the proxied request to Tomcat took longer than 300 seconds to get a response the browser would display a "502 Proxy Error" page. I believe this message is generated by Apache, in the knowledge that it's acting as a reverse proxy, before it closes down the connection to the browser (this is my current understanding - it may be flawed).
The proxy error page says:
Proxy Error
The proxy server received an invalid response from an upstream server. The proxy server could not handle the request GET.
Reason: Error reading from remote server
...which suggests that it's the ProxyTimeout setting that's too short, while investigation shows that Apache's Timeout setting (timeout between Apache and the client) that also influences this.
You could use HttpWebRequest to get the file and stream it back to the client. This allows you to get the file with a url. An example of this that I found ( but can't remember where to give credit ) is
//Create a stream for the file
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
// The number of bytes read
try
{
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest) HttpWebRequest.Create(url);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse) fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
If you want to find ALL controls of a specific type, you might be interested in this snippet too
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject parent)
where T : DependencyObject
{
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
var childType = child as T;
if (childType != null)
{
yield return (T)child;
}
foreach (var other in FindVisualChildren<T>(child))
{
yield return other;
}
}
}
This is a warning for usual. You can either disable it by
#pragma warning(disable:4996)
or simply use fopen_s like Microsoft has intended.
But be sure to use the pragma before other headers.
Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.
char c[2];
int i=1;
sprintf(c, "%d", i);
Simply follow the instructions given here:
Example install:
sudo apt-get install python-software-properties python g++ make sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs
It installs current stable Node on the current stable Ubuntu. Quantal (12.10) users may need to install the software-properties-common package for the
add-apt-repository
command to work:sudo apt-get install software-properties-common
As of Node.js v0.10.0, the nodejs package from Chris Lea's repo includes both npm and nodejs-dev.
Don't give sudo apt-get install nodejs npm
. Just sudo apt-get install nodejs
.
Hi please check the below link
https://www.postgresql.org/docs/current/xfunc-sql.html
EX:
CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;
to reattach this object, you must use merge();
this methode accept in parameter your entity detached and return an entity will be attached and reloaded from Database.
Example :
Lot objAttach = em.merge(oldObjDetached);
objAttach.setEtat(...);
em.persist(objAttach);
Xcode 8.2.1 • Swift 3.0.2
Locale.availableIdentifiers
Locale.isoRegionCodes
Locale.isoCurrencyCodes
Locale.isoLanguageCodes
Locale.commonISOCurrencyCodes
Locale.current.regionCode // "US"
Locale.current.languageCode // "en"
Locale.current.currencyCode // "USD"
Locale.current.currencySymbol // "$"
Locale.current.groupingSeparator // ","
Locale.current.decimalSeparator // "."
Locale.current.usesMetricSystem // false
Locale.windowsLocaleCode(fromIdentifier: "pt_BR") // 1,046
Locale.identifier(fromWindowsLocaleCode: 1046) ?? "" // "pt_BR"
Locale.windowsLocaleCode(fromIdentifier: Locale.current.identifier) // 1,033 Note: I am in Brasil but I use "en_US" format with all my devices
Locale.windowsLocaleCode(fromIdentifier: "en_US") // 1,033
Locale.identifier(fromWindowsLocaleCode: 1033) ?? "" // "en_US"
Locale(identifier: "en_US_POSIX").localizedString(forLanguageCode: "pt") // "Portuguese"
Locale(identifier: "en_US_POSIX").localizedString(forRegionCode: "br") // "Brazil"
Locale(identifier: "en_US_POSIX").localizedString(forIdentifier: "pt_BR") // "Portuguese (Brazil)"
TimeZone.current.localizedName(for: .standard, locale: .current) ?? "" // "Brasilia Standard Time"
TimeZone.current.localizedName(for: .shortStandard, locale: .current) ?? "" // "GMT-3
TimeZone.current.localizedName(for: .daylightSaving, locale: .current) ?? "" // "Brasilia Summer Time"
TimeZone.current.localizedName(for: .shortDaylightSaving, locale: .current) ?? "" // "GMT-2"
TimeZone.current.localizedName(for: .generic, locale: .current) ?? "" // "Brasilia Time"
TimeZone.current.localizedName(for: .shortGeneric, locale: .current) ?? "" // "Sao Paulo Time"
var timeZone: String {
return TimeZone.current.localizedName(for: TimeZone.current.isDaylightSavingTime() ?
.daylightSaving :
.standard,
locale: .current) ?? "" }
timeZone // "Brasilia Summer Time"
problem is that the collapse item (div) is nested in the table elements. The div is hidden, the tr and td of the table are still visible and some css-styles are applied to them (border and padding).
Why are you using tables? Is there a reason for? When you dont´t have to use them, dont´use them :-)
Set the env var: JAVACMD - full path of the Java executable. Use this to invoke a different JVM than JAVA_HOME/bin/java(.exe).
Reference: http://ant.apache.org/manual/running.html
An uninitialized Boolean
member (actually a reference to an object of type Boolean
) will have the default value of null
.
An uninitialized boolean
(primitive) member will have the default value of false
.
the mysqli_query
excepts 2 parameters , first variable is mysqli_connect
equivalent variable , second one is the query you have provided
$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);
$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");
I found the next command
mvn dependency:copy-dependencies -Dclassifier=sources
here maven.apache.org
SSLHandshakeException can be resolved 2 ways.
Incorporating SSL
Get the SSL (by asking the source system administrator, can also be downloaded by openssl command, or any browsers downloads the certificates)
Add the certificate into truststore (cacerts) located at JRE/lib/security
provide the truststore location in vm arguments as "-Djavax.net.ssl.trustStore="
Ignoring SSL
For this #2, please visit my other answer on another stackoverflow website: How to ingore SSL verification Ignore SSL Certificate Errors with Java
In your terminal run: docker exec -it container_name /bin/bash
Then: mysql
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
Here is an example to explain the most simple way of using getter and setter in java. One can do this in a more straightforward way but getter and setter have something special that is when using private member of parent class in child class in inheritance. You can make it possible through using getter and setter.
package stackoverflow;
public class StackoverFlow
{
private int x;
public int getX()
{
return x;
}
public int setX(int x)
{
return this.x = x;
}
public void showX()
{
System.out.println("value of x "+x);
}
public static void main(String[] args) {
StackoverFlow sto = new StackoverFlow();
sto.setX(10);
sto.getX();
sto.showX();
}
}
Came across this and thought I'd leave the solution I used as well, which utilizes line-height
and text-align: center
to do both vertical and horizontal centering:
I'm using Java 8 and this worked for me.
Add the dependency on pom.xml
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.4.0</version>
</dependency>
and add JodaModule on your ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
There is GitPython. Haven’t heard of it before and internally, it relies on having the git executables somewhere; additionally, they might have plenty of bugs. But it could be worth a try.
How to clone:
import git
git.Git("/your/directory/to/clone").clone("git://gitorious.org/git-python/mainline.git")
(It’s not nice and I don’t know if it is the supported way to do it, but it worked.)
@echo $(NDK_PROJECT_PATH) is the good way to do it. I don't think the error comes from there. Generally this error appears when you mistyped the intendation : I think you have spaces where you should have a tab.
MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.
Using compare methods like so:
<?php
$db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
$my_pass = "mypass";
if ($db_pass === md5($my_pass)) {
// password is matched
} else {
// password didn't match
}
Only for WordPress users.
If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass
is not only MD5 format it also uses utf8_mb4_cli
charset so what to do?
That's why I use another Approach if I forget my WordPress password I use
I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )
EASY is use this :
I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS
WORDPRESS USE THIS
https://developer.wordpress.org/reference/functions/wp_hash_password/
I found the answer is very very simple...
// It is in java, but it should be same in pyspark
Column col = ds.col("colName"); //the column object
String theNameOftheCol = col.toString();
The variable "theNameOftheCol" is "colName"
You can reset the index using reset_index
to get back a default index of 0, 1, 2, ..., n-1 (and use drop=True
to indicate you want to drop the existing index instead of adding it as an additional column to your dataframe):
In [19]: df2 = df2.reset_index(drop=True)
In [20]: df2
Out[20]:
x y
0 0 0
1 0 1
2 0 2
3 1 0
4 1 1
5 1 2
6 2 0
7 2 1
8 2 2
People have suggested many great solutions here, but I used this simple technique with my EditText (nothing in java and AnroidManifest.xml is required). Just set your focusable and focusableInTouchMode to false directly on EditText.
<EditText
android:id="@+id/text_pin"
android:layout_width="136dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAlignment="center"
android:inputType="numberPassword"
android:password="true"
android:textSize="24dp"
android:focusable="false"
android:focusableInTouchMode="false"/>
My intent here is to use this edit box in App lock activity where I am asking user to input the PIN and I want to show my custom PIN pad. Tested with minSdk=8 and maxSdk=23 on Android Studio 2.1
In jQuery Mobile:
$('#someselectElement').selectmenu().selectmenu('disable').selectmenu('refresh', true);
$('#someTextElement').textinput().textinput('disable');
$('#someselectElement').selectmenu().selectmenu('enable').selectmenu('refresh', true);
$('#someTextElement').textinput('enable');
select from_unixtime(column,'%Y-%m-%d') from myTable;
Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:
<input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />
Then you just get the value in your ajax call:
var path = $("#GetIndexDataPath").val();
$.ajax({
type: "GET",
url: path,
data: { id = e.value},
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.
you can also select WhatsApp business vs WhatsApp
String url = "https://api.whatsapp.com/send?phone=" + phoneNumber + "&text=" +
URLEncoder.encode(messageText, "UTF-8");
if(useWhatsAppBusiness){
intent.setPackage("com.whatsapp.w4b");
} else {
intent.setPackage("com.whatsapp");
}
URLEncoder.encode(messageText, "UTF-8");
intent.setData(Uri.parse(url));
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent);
} else {
Toast.makeText(this, "WhatsApp application not found", Toast.LENGTH_SHORT).show();
}
If you set the attribute Visible on the asp:BoundField to False. Like this
<asp:BoundField DataField="F1" HeaderText="F1" Visible="False"/>
You will not get any Text in the Cells[i].Text property when you loop the rows. So
foreach (GridViewRow row in myGrid.Rows)
{
userList.Add(row.Cells[0].Text); //this will be empty ""
}
But you can set a column not visible by connecting the grid to the event OnRowDataBound then from here do this
e.Row.Cells[0].Visible = false //now the cell has Text but it's hidden
If its SQL Server you can do it on the column properties within design view
Try this?:
ALTER TABLE dbo.TableName
ADD CONSTRAINT DF_TableName_ColumnName
DEFAULT '01/01/2000' FOR ColumnName
I'd like to post my re-re-inventing version based on @FredOverflow's. I made the following modifications.
fix:
operator<<
should be of const
reference type. In @FredOverflow's code, h.x >>= 4
changes output h
, which is surprisingly not compatible with standard library, and type T
is requared to be copy-constructable.CHAR_BITS
is a multiple of 4. @FredOverflow's code assumes char
is 8-bits, which is not always true, in some implementations on DSPs, particularly, it is not uncommon that char
is 16-bits, 24-bits, 32-bits, etc.improve:
std::uppercase
. Because format output is used in _print_byte
, standard library manipulators are still available.hex_sep
to print separate bytes (note that in C/C++ a 'byte' is by definition a storage unit with the size of char
). Add a template parameter Sep
and instantiate _Hex<T, false>
and _Hex<T, true>
in hex
and hex_sep
respectively._print_byte
is extracted out of operator<<
, with a function parameter size
, to avoid instantiation for different Size
.More on binary code bloat:
As mentioned in improvement 3, no matter how extensively hex
and hex_sep
is used, only two copies of (nearly) duplicated function will exits in binary code: _print_byte<true>
and _print_byte<false>
. And you might realized that this duplication can also be eliminated using exactly the same approach: add a function parameter sep
. Yes, but if doing so, a runtime if(sep)
is needed. I want a common library utility which may be used extensively in the program, thus I compromised on the duplication rather than runtime overhead. I achieved this by using compile-time if
: C++11 std::conditional
, the overhead of function call can hopefully be optimized away by inline
.
hex_print.h:
namespace Hex
{
typedef unsigned char Byte;
template <typename T, bool Sep> struct _Hex
{
_Hex(const T& t) : val(t)
{}
const T& val;
};
template <typename T, bool Sep>
std::ostream& operator<<(std::ostream& os, const _Hex<T, Sep>& h);
}
template <typename T> Hex::_Hex<T, false> hex(const T& x)
{ return Hex::_Hex<T, false>(x); }
template <typename T> Hex::_Hex<T, true> hex_sep(const T& x)
{ return Hex::_Hex<T, true>(x); }
#include "misc.tcc"
hex_print.tcc:
namespace Hex
{
struct Put_space {
static inline void run(std::ostream& os) { os << ' '; }
};
struct No_op {
static inline void run(std::ostream& os) {}
};
#if (CHAR_BIT & 3) // can use C++11 static_assert, but no real advantage here
#error "hex print utility need CHAR_BIT to be a multiple of 4"
#endif
static const size_t width = CHAR_BIT >> 2;
template <bool Sep>
std::ostream& _print_byte(std::ostream& os, const void* ptr, const size_t size)
{
using namespace std;
auto pbyte = reinterpret_cast<const Byte*>(ptr);
os << hex << setfill('0');
for (int i = size; --i >= 0; )
{
os << setw(width) << static_cast<short>(pbyte[i]);
conditional<Sep, Put_space, No_op>::type::run(os);
}
return os << setfill(' ') << dec;
}
template <typename T, bool Sep>
inline std::ostream& operator<<(std::ostream& os, const _Hex<T, Sep>& h)
{
return _print_byte<Sep>(os, &h.val, sizeof(T));
}
}
test:
struct { int x; } output = {0xdeadbeef};
cout << hex_sep(output) << std::uppercase << hex(output) << endl;
output:
de ad be ef DEADBEEF
This should work :
MyInstace.GetType().GetInterfaces();
But nice too :
if (obj is IMyInterface)
Or even (not very elegant) :
if (obj.GetType() == typeof(IMyInterface))
{{value | number : fractionSize}}
like {{12.52311 | number : 2}}
so this will print 12.52
<style>
.navbar-brand {
margin: auto;
}
</style>
<!--HTML-->
<nav class="navbar navbar-light bg-light">
<a class="navbar-brand" href="#">
<img src="logo goes here" width="100" height="100" class="logo" alt=""
loading="lazy">
</a>
</nav>
If you need it to have as a condition in an other event, I solved it this way:
$('.classname').hover(
function(){$(this).data('hover',true);},
function(){$(this).data('hover',false);}
);
Then in another event, you can easily use it:
if ($(this).data('hover')){
//...
}
(I see some using is(':hover')
to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)
this is only for REFEDIT ... generaly use uphere code shortly version... easy to be read and understood / it use poz of $
Private Sub RefEdit1_Change()
Me.Label1.Caption = NOtoLETTER(RefEdit1.Value) ' you may assign to a variable var=....'
End Sub
Function NOtoLETTER(REFedit)
Dim First As Long, Second As Long
First = InStr(REFedit, "$") 'first poz of $
Second = InStr(First + 1, REFedit, "$") 'second poz of $
NOtoLETTER = Mid(REFedit, First + 1, Second - First - 1) 'extract COLUMN LETTER
End Function
If you are like me, and are staring at this thread thinking "But I'm not trying to add a component, I am trying to add a guard/service/pipe, etc." then the issue is likely that you have added the wrong type to a routing path. That is what I did. I accidentally added a guard to the component: section of a path instead of the canActivate: section. I love IDE autocomplete but you have to slow down a bit and pay attention. If you absolutely can't find it, do a global search for the name it is complaining about and look at every usage to make sure you didn't slip-up with a name.
There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.
Rendering and Visibility
There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.
Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat
attribute value to server
on the markup page.
<div id="myDiv" runat="server"></div>
The decision to render the div or not can now be done in the code behind class like so:
myDiv.Visible = someConditionalBool;
If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.
Client Side Hiding
Hiding an element is done on the client side only. Meaning, it's rendered but it has a display
CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server
set just as I explained in the previous example.
Hiding in the Code Behind Class
To hide an element that you want rendered to the page but hidden is another simple single line of code:
myDiv.Style["display"] = "none";
If you have a need to remove the display
style server side, it can be done by removing the display
style, or setting it to a different value like inline
or block
(values described here).
myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";
Hiding on the Client Side with javascript
Using plain old javascript, you can easily hide the same element in this manner
var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";
// then to show again
myDivElem.style.display = "";
jQuery makes hiding elements a little simpler if you prefer to use jQuery:
var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();
// ... and to show
myDiv.show();
I faced the same issue:
E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation
I resolved by using the following commands:
apt-get update
apt-get install gnupg
Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial
The MDN Documentation is very eloquent and features examples.
Could be due to the TCP protocol turned off.
How to check/enable: https://dba.stackexchange.com/questions/11377/cannot-connect-to-ms-sql-2008-r2-by-dbvisualizer-native-sspi-library-not-loade/144097#144097
This configuration is working for me:
set termout off
set verify off
set trimspool on
set linesize 200
set longchunksize 200000
set long 200000
set pages 0
column txt format a120
The column
format definition with the linesize
option helped to avoid the truncation at 80 chars.
A Bundle
is very much like a Java Map
object that maps String
keys to values. It's used to pass information between activities and other application components. It's also used by the framework to capture and restore state information.
The reason Android doesn't use plain old Map
objects for this is that Map
is too flexible; it can contain objects (such as, say, I/O streams) that cannot be serialized. The Bundle
API restricts the types of objects that can be added to a bundle in such a way that the bundle's contents are guaranteed to be serializable. The Android framework relies on this property.
I suggest that you read the documentation on Application Fundamentals. This explains, among other things, what bundles and intents are and what they are used for.
$('div').attr('style', '');
or
$('div').removeAttr('style');
(From Andres's Answer)
To make this a little smaller, try this:
$('div[style]').removeAttr('style');
This should speed it up a little because it checks that the divs have the style attribute.
Either way, this might take a little while to process if you have a large amount of divs, so you might want to consider other methods than javascript.
SELECT * FROM Table_Name LIMIT 5;
You need to escape it with two backslashes
\\?
See this for more details:
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm
Model1.belongsTo(Model2, { as: 'alias' })
Model1.findAll({include: [{model: Model2 , as: 'alias' }]},{raw: true}).success(onSuccess).error(onError);
When you make a call to using namespace <some_namespace>;
all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.
E.g. if you add using namespace std;
you can write just cout
instead of std::cout
when calling the operator cout
defined in the namespace std
.
This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace
you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:
#include <iostream>
using std::cout;
int main() {
cout << "Hello world!";
return 0;
}
Problem solved! I'm using Ctrl + Alt + E to open Exception Window, and I checked all throw checkbox. So the debuger can stop at the exactly the error code.
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
Local variables don't have a default value.
They have to be definitely assigned before you use them. It reduces the chance of using a variable you think you've given a sensible value to, when actually it's got some default value.
Removing a file from pull request but not from your local repository.
git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin
Note : no single quote or double quotes for the filepath
I had this issue as well. My solution was to disable selinux. I tried allowing 2 different http settings in selinux (something like httpd_allow_email and http_can_connect) and that didn't work, so I just disabled it completely and it started working.
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
What about this:
while ($row = mysql_fetch_array($result))
{
$new_array[$row['id']]['id'] = $row['id'];
$new_array[$row['id']]['link'] = $row['link'];
}
To retrieve link and id:
foreach($new_array as $array)
{
echo $array['id'].'<br />';
echo $array['link'].'<br />';
}
I used PDFiumSharp and ImageSharp in a .NET Standard 2.1 class library.
/// <summary>
/// Saves a thumbnail (jpg) to the same folder as the PDF file, using dimensions 300x423,
/// which corresponds to the aspect ratio of 'A' paper sizes like A4 (ratio h/w=sqrt(2))
/// </summary>
/// <param name="pdfPath">Source path of the pdf file.</param>
/// <param name="thumbnailPath">Target path of the thumbnail file.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public static void SaveThumbnail(string pdfPath, string thumbnailPath = "", int width = 300, int height = 423)
{
using var pdfDocument = new PdfDocument(pdfPath);
var firstPage = pdfDocument.Pages[0];
using var pageBitmap = new PDFiumBitmap(width, height, true);
firstPage.Render(pageBitmap);
var imageJpgPath = string.IsNullOrWhiteSpace(thumbnailPath)
? Path.ChangeExtension(pdfPath, "jpg")
: thumbnailPath;
var image = Image.Load(pageBitmap.AsBmpStream());
// Set the background to white, otherwise it's black. https://github.com/SixLabors/ImageSharp/issues/355#issuecomment-333133991
image.Mutate(x => x.BackgroundColor(Rgba32.White));
image.Save(imageJpgPath, new JpegEncoder());
}
I'm using maven deploy file.
mvn deploy:deploy-file -DgroupId=my.group.id \
-DartifactId=my-artifact-id \
-Dversion=1.0.0.1 \
-Dpackaging=jar \
-Dfile=foo.jar \
-DgeneratePom=true \
-DrepositoryId=my-repo \
-Durl=http://my-nexus-server.com:8081/repository/maven-releases/
UPDATE:
As stated in comments using quotes in url cause NoSuchElementException
But I have add server config in my maven (~/.m2/settings.xml).
<servers>
<server>
<id>my-repo</id>
<username>admin</username>
<password>admin123</password>
</server>
</servers>
References:
I met the same problem, the error message and OS info are as follows
OS info:
CentOS release 6.5 (Final)
Linux 192-168-30-213 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
error info:
Initialized empty Git repository in /home/techops/pyenv/.git/ Password: error: while accessing https://[email protected]/pyenv/pyenv.git/info/refs
fatal: HTTP request failed
git & curl version info
git info :git version 1.7.1
curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz
debugging
$ curl --verbose https://github.com
- About to connect() to github.com port 443 (#0)
- Trying 13.229.188.59... connected
- Connected to github.com (13.229.188.59) port 443 (#0)
- Initializing NSS with certpath: sql:/etc/pki/nssdb
- CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
- NSS error -12190
Error in TLS handshake, trying SSLv3... GET / HTTP/1.1 User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Host: github.com Accept: /
Connection died, retrying a fresh connect
- Closing connection #0
- Issue another request to this URL: 'https://github.com'
- About to connect() to github.com port 443 (#0)
- Trying 13.229.188.59... connected
- Connected to github.com (13.229.188.59) port 443 (#0)
- TLS disabled due to previous handshake failure
- CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
- NSS error -12286
- Closing connection #0
- SSL connect error curl: (35) SSL connect error
after upgrading curl , libcurl and nss , git clone works fine again, so here it is. the update command is as follows
sudo yum update -y nss curl libcurl
That solved my problem on Ubuntu 14.04:
apt-get install libcurl4-gnutls-dev
From here:
-Xmn : the size of the heap for the young generation
Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".
And a more "official" source from IBM:
-Xmn
Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.
Insert a 3rd column and in Cell C2
paste this formula
=IF(SUMPRODUCT(($A$2:$A2=A2)*($B$2:$B2=B2))>1,0,1)
and copy it down. Now create your pivot based on 1st and 3rd column. See snapshot
When I paste code into Outlook or have sentences containing code or technical syntax I get annoyed by all of the red squiggles that identify spelling errors. If you want Outlook to clear all of the red spellcheck squiggles you can add a button to the Quick Access Toolbar that calls a VBA macro and removes all squiggles from the current document.
I prefer to run this macro separate from my style choice because I often use it on a selection of text that has mixed content.
For syntax highlighting I use the Notepad++ technique already listed by @srujanreddy, though I discovered that the right-click context menu option a bit handier than navigating the Plugins menu.
If you get annoyed by spell check while you are preparing your email you can add a button to your quick access toolbar that will remove the red squiggles from the message body.
See this article: https://stackoverflow.com/a/49865743/1898524
As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined
keyword.
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is undefined
This is an iterable function without yield
. It make use of the iter
function and a closure which keeps it's state in a mutable (list
) in the enclosing scope for python 2.
def count(low, high):
counter = [0]
def tmp():
val = low + counter[0]
if val < high:
counter[0] += 1
return val
return None
return iter(tmp, None)
For Python 3, closure state is kept in an immutable in the enclosing scope and nonlocal
is used in local scope to update the state variable.
def count(low, high):
counter = 0
def tmp():
nonlocal counter
val = low + counter
if val < high:
counter += 1
return val
return None
return iter(tmp, None)
Test;
for i in count(1,10):
print(i)
1
2
3
4
5
6
7
8
9
There are currently three distinct events which may or may not be triggered when the client devices moves. Two of them are focused around orientation and the last on motion:
ondeviceorientation
is known to work on the desktop version of Chrome, and most Apple laptops seems to have the hardware required for this to work. It also works on Mobile Safari on the iPhone 4 with iOS 4.2. In the event handler function, you can access alpha
, beta
, gamma
values on the event data supplied as the only argument to the function.
onmozorientation
is supported on Firefox 3.6 and newer. Again, this is known to work on most Apple laptops, but might work on Windows or Linux machines with accelerometer as well. In the event handler function, look for x
, y
, z
fields on the event data supplied as first argument.
ondevicemotion
is known to work on iPhone 3GS + 4 and iPad (both with iOS 4.2), and provides data related to the current acceleration of the client device. The event data passed to the handler function has acceleration
and accelerationIncludingGravity
, which both have three fields for each axis: x
, y
, z
The "earthquake detecting" sample website uses a series of if
statements to figure out which event to attach to (in a somewhat prioritized order) and passes the data received to a common tilt
function:
if (window.DeviceOrientationEvent) {
window.addEventListener("deviceorientation", function () {
tilt([event.beta, event.gamma]);
}, true);
} else if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', function () {
tilt([event.acceleration.x * 2, event.acceleration.y * 2]);
}, true);
} else {
window.addEventListener("MozOrientation", function () {
tilt([orientation.x * 50, orientation.y * 50]);
}, true);
}
The constant factors 2 and 50 are used to "align" the readings from the two latter events with those from the first, but these are by no means precise representations. For this simple "toy" project it works just fine, but if you need to use the data for something slightly more serious, you will have to get familiar with the units of the values provided in the different events and treat them with respect :)
Go to Gradle tab in Android Studio , then select library project .
Then go to Tasks
Then go to Other
Double click on bundleReleaseaar
You can find your .aar
files under your_module/build/outputs/aar/your-release.aar
Going back to absolute basics here. The answers on this page and a little googling have brought me to the following resolution to my issue. Steps to restart the apache service with Xampp installed:-
cd C:\xampp\apache\bin
(the default installation path for Xampp)httpd -k restart
I hope that this is of use to others just starting out with running a local Apache server.
Since this is one of the first links on Google when search for Android and .net support, it is only fitting to post this here.
The mono project is working on a SDK to develop Android applications using CIL languages such as C#. The down side is it will be a commercial product. monodroid
The CURL extension ext/curl
is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.
The forward/iterator method does not work when removing items. You can remove the element without error, but you will get a runtime error when you try to access removed items. You can't use the iterator because as pushy shows it will cause a ConcurrentModificationException, so use a regular for loop instead, but step backwards through it.
List<Integer> integerList;
integerList = new ArrayList<Integer>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
int size= integerList.size();
//Item to remove
Integer remove = Integer.valueOf(3);
A solution:
Traverse the array in reverse order if you are going to remove a list element. Simply by going backwards through the list you avoid visiting an item that has been removed, which removes the exception.
//To remove items from the list, start from the end and go backwards through the arrayList
//This way if we remove one from the beginning as we go through, then we will avoid getting a runtime error
//for java.lang.IndexOutOfBoundsException or java.util.ConcurrentModificationException as when we used the iterator
for (int i=size-1; i> -1; i--) {
if (integerList.get(i).equals(remove) ) {
integerList.remove(i);
}
}
Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.
Ok I think I have solves the problem below is a working code
//
package xmlhttp;
import org.jdesktop.http.Response;
import org.jdesktop.http.Session;
import org.jdesktop.http.State;
public class GetXmlHttp{
public static void main(String[] args) {
getResponse();
}
public static void getResponse()
{
final Session session = new Session();
try {
String url="http://192.172.2.23:8080/geoserver/wfs?request=GetFeature&version=1.1.0&outputFormat=GML2&typeName=topp:networkcoverage,topp:tehsil&bbox=73.07846689124875,33.67929015631999,73.07946689124876,33.68029015632,EPSG:4326";
final Response res=session.get(url);
boolean notDone=true;
do
{
System.out.print(session.getState().toString());
if(session.getState()==State.DONE)
{
String xml=res.toString();
System.out.println(xml);
notDone=false;
}
}while(notDone);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
In my troubleshooting, I found this AJAX xmlhttpRequest.status == 0 could mean the client call had NOT reached the server yet, but failed due to issue on the client side. If the response was from server, then the status must be either those 1xx/2xx/3xx/4xx/5xx HTTP Response code. Henceforth, the troubleshooting shall focus on the CLIENT issue, and could be internet network connection down or one of those described by @Langdon above.
Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
. If you want to use strptime, you need to strip out those variations first.
The goal is to generate a utc datetime object.
2016-06-29T19:36:29.3453Z
:
datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")
2016-06-29T19:36:29.3453-0400
or 2008-09-03T20:56:35.450686+05:00
use the following. These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500
making it more consistent/easier to parse.
import re
# this regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )
%z
strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'
) then you need to manually offset the time from Z
(UTC). Note %z
may not work on your system in python versions < 3 as it depended on the c library support which varies across system/python build type (i.e. Jython, Cython, etc.).
import re
import datetime
# this regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
# split on the offset to remove it. use a capture group to keep the delimiter
split_timestamp = re.split(r"[+|-]",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
# create timedelta based on offset
offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
# offset datetime with timedelta
output_datetime = output_datetime + offset_delta
[\W_]+
$string = preg_replace("/[\W_]+/u", '', $string);
It select all not A-Z, a-z, 0-9 and delete it.
See example here: https://regexr.com/3h1rj
I have made it from fastboot mode (Phone - Xiomi Mi5 Android 6.0.1)
Here is steps:
# check if device available
fastboot devices
# remove user data
fastboot erase userdata
# remove cache
fastboot erase cache
# reboot device
fastboot reboot
From my understanding of the Apple documentation, a selector represents the name of the method that you want to call. The nice thing about selectors is you can use them in cases where the exact method to be called varies. As a simple example, you can do something like:
SEL selec;
if (a == b) {
selec = @selector(method1)
}
else
{
selec = @selector(method2)
};
[self performSelector:selec];
I needed this feature, but also wanted to make sure I did not return lines with a prefix before the ABB.log:
grep "\WABB.log$" -w a.tmp
Here what I DO on MY PC I install all software that i usually used in G: partian not C: if my operating system is fall (win 10) , Do not need to reinstall them again and lost time , Then How windows work it update PATH automatic if you install any new programe or pice of softwore ,
SO
I must update PATH like these HERE! all my software i usually used
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;G:\HashiCorp\Vagrant\bin;G:\xampp\php;G:\xampp\mysql\bin;G:\Program Files (x86)\heroku\bin;G:\Program Files (x86)\Git\bin;G:\Program Files (x86)\composer;G:\Program Files (x86)\nodejs;G:\Program Files (x86)\Sublime Text 3;G:\Program Files (x86)\Microsoft VS Code\bin;G:\Program Files (x86)\cygwin64\bin
Using testflight :
1) create the ipa file by development certificate
2) upload the ipa file on testflight
3) Now, to identify the device to be tested on , add the device id on apple account and refresh your development certificate. Download the updated certificate and upload it on testflight website. Check the device id you are getting.
4) Now email the ipa file to the testers.
5) While downloading the ipa file, if the testers are not getting any warnings, this means the device token + provisioning profile has been verified. So, the testers can now download the ipa file on device and do the testing job...
JavaScript is a scripting language, not a HTMLanguage type. It is mainly to do process at background and it needs document.write
to display things on browser.
Also if your document.write
exceeds one line, make sure to put concatenation +
at the end of each line.
Example
<script type="text/javascript">
if(document.getElementById('number1').checked) {
document.write("<h1>Hello" +
"member</h1>");
}
</script>
In Windows 10, it's still 8191 characters...at least on my machine.
It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.
Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.
echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat
CSS
div.horizontalgap {
float: left;
overflow: hidden;
height: 1px;
width: 0px;
}
Usage in HTML (for a 10px horizontal gap)
<div class="horizontalgap" style="width:10px"></div>
VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
If we declare datatype as VARCHAR then it will occupy space for NULL values. In the case of VARCHAR2 datatype, it will not occupy any space for NULL values. e.g.,
name varchar(10)
will reserve 6 bytes of memory even if the name is 'Ravi__', whereas
name varchar2(10)
will reserve space according to the length of the input string. e.g., 4 bytes of memory for 'Ravi__'.
Here, _ represents NULL.
NOTE: varchar will reserve space for null values and varchar2 will not reserve any space for null values.
You can use [ModSecurity][1]
to view POST data.
Install on Debian/Ubuntu:
$ sudo apt install libapache2-mod-security2
Use the recommended configuration file:
$ sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
Reload Apache:
$ sudo service apache2 reload
You will now find your data logged under /var/log/apache2/modsec_audit.log
$ tail -f /var/log/apache2/modsec_audit.log
--2222229-A--
[23/Nov/2017:11:36:35 +0000]
--2222229-B--
POST / HTTP/1.1
Content-Type: application/json
User-Agent: curl
Host: example.com
--2222229-C--
{"test":"modsecurity"}
i suggest using this ...
np.arange(start_index, end_index, intervals)[::-1]
for example:
np.arange(10, 20, 0.5)
np.arange(10, 20, 0.5)[::-1]
[ 19.5, 19. , 18.5, 18. , 17.5, 17. , 16.5, 16. , 15.5,
15. , 14.5, 14. , 13.5, 13. , 12.5, 12. , 11.5, 11. ,
10.5, 10. ]
Yes. You can pass the numerical values to the constructor for the enum, like so:
enum Ids {
OPEN(100),
CLOSE(200);
private int value;
private Ids(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
See the Sun Java Language Guide for more information.
simple example:
<div ng-style="isTrue && {'background-color':'green'} || {'background-color': 'blue'}" style="width:200px;height:100px;border:1px solid gray;"></div>
{'background-color':'green'} RETURN true
OR the same result:
<div ng-style="isTrue && {'background-color':'green'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>
other conditional possibility:
<div ng-style="count === 0 && {'background-color':'green'} || count === 1 && {'background-color':'yellow'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>
Both source and target should be specified. I recommend providing ant defaults, that way you do not need to specify source/target attribute for every javac task:
<property name="ant.build.javac.source" value="1.5"/>
<property name="ant.build.javac.target" value="1.5"/>
See Java cross-compiling notes for more information.
Explanation from the Preshing on Programming blog:
It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:
with open('output.txt', 'w') as f: f.write('Hi there!')
The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.
You can do this thing using performSegueWithIdentifier
function.
Syntax :
func performSegueWithIdentifier(identifier: String, sender: AnyObject?)
Example :
performSegueWithIdentifier("homeScreenVC", sender: nil)
Specific actions you can do from SQL client and you don't need to restart anything:
SET GLOBAL log = 'ON';
FLUSH LOGS;
What you want is something like this:
document.getElementByClassName("example").click();
Using jQuery, it would be something like this:
$(".example").trigger("click");
This is my code for extracting pdf.
import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here' + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)
Please refer to this repo of mine for more details.
Look at the dba_blockers
, dba_waiters
and dba_locks
for locking. The names should be self explanatory.
You could create a job that runs, say, once a minute and logged the values in the dba_blockers
and the current active sql_id
for that session. (via v$session
and v$sqlstats
).
You may also want to look in v$sql_monitor
. This will be default log all SQL that takes longer than 5 seconds. It is also visible on the "SQL Monitoring" page in Enterprise Manager.
I started creating a Node.js/browserify application following the Cross Platform JavaScript blog post. And I ran into this issue, because my brand new Gruntfile didn't pass jshint.
Luckily I found an answer in the Leanpub book on Grunt:
If we try it now, we will scan our Gruntfile… and get some errors:
$ grunt jshint Running "jshint:all" (jshint) task Linting Gruntfile.js...ERROR [L1:C1] W097: Use the function form of "use strict". 'use strict'; Linting Gruntfile.js...ERROR [L3:C1] W117: 'module' is not defined. module.exports = function (grunt) { Warning: Task "jshint:all" failed. Use --force to continue.
Both errors are because the Gruntfile is a Node program, and by default JSHint does not recognise or allow the use of
module
and the string version ofuse strict
. We can set a JSHint rule that will accept our Node programs. Let’s edit our jshint task configuration and add an options key:jshint: { options: { node: true }, }
Adding node: true
to the jshint options
, to put jshint into "Node mode", removed both errors for me.
It is enough to use color property alongside with -webkit-text-fill-color this way:
input {_x000D_
color: red; /* color of caret */_x000D_
-webkit-text-fill-color: black; /* color of text */_x000D_
}
_x000D_
<input type="text"/>
_x000D_
Works in WebKit browsers (but not in iOS Safari, where is still used system color for caret) and also in Firefox.
The -webkit-text-fill-color CSS property specifies the fill color of characters of text. If this property is not set, the value of the color property is used. MDN
So this means we set text color with text-fill-color and caret color with standard color property. In unsupported browser, caret and text will have same color – color of the caret.
I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com. But when I print it in the interactive mode I get double slash - '\\w' as @Jimmynoarms said:
The Solution for python 3x:
print(r'%s' % your_variable_pattern_str)
Here is an article with full details on how to do this.
Private Sub btnScale_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnScale.Click
' Get the scale factor.
Dim scale_factor As Single = Single.Parse(txtScale.Text)
' Get the source bitmap.
Dim bm_source As New Bitmap(picSource.Image)
' Make a bitmap for the result.
Dim bm_dest As New Bitmap( _
CInt(bm_source.Width * scale_factor), _
CInt(bm_source.Height * scale_factor))
' Make a Graphics object for the result Bitmap.
Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)
' Copy the source image into the destination bitmap.
gr_dest.DrawImage(bm_source, 0, 0, _
bm_dest.Width + 1, _
bm_dest.Height + 1)
' Display the result.
picDest.Image = bm_dest
End Sub
[Edit]
One more on the similar lines.
There's another problem at work here. The Clean functionality of Eclipse is broken. If you delete files outside of Eclipse it will not pick up on the fact that the files are now missing, and you'll get build errors until you delete the files manually. Even then, that will not necessarily work either, especially if there are a lot of files missing. This happens to me rather often when I check out a branch of code that has had a lot of changes since the last time I built it. In that case, the only recourse I've found is to start a brand new workspace and reload the project from scratch.
Basically, The reason behind these type of error is eventually you are trying to delete a tupple which has primary key (root table) & that primary key is used in child table as a foreign key. In this scenario in order to delete parent table data you have to remove child table data (in which foreign key is used). Thanks
Something like this will work
arr = ["A", "B", "C", "B", "A"]
arr.inject(Hash.new(0)) { |h,e| h[e] += 1; h }.
select { |k,v| v > 1 }.
collect { |x| x.first }
That is, put all values to a hash where key is the element of array and value is number of occurences. Then select all elements which occur more than once. Easy.
You should throw an IllegalArgumentException, as it will make it obvious to the programmer that he has done something invalid. Developers are so used to seeing NPE thrown by the VM, that any programmer would not immediately realize his error, and would start looking around randomly, or worse, blame your code for being 'buggy'.
If you know that all other views should have the bar visible, you could use viewWillDisappear
to set it to visible again.
In Swift:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
import json
list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
Write to json File:
with open('/home/ubuntu/test.json', 'w') as fout:
json.dump(list , fout)
Read Json file:
with open(r"/home/ubuntu/test.json", "r") as read_file:
data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
You can use display: table-cell
property as in the following code:
div {
height: 100%;
display: table-cell;
vertical-align: middle;
}
That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.
The HTML in your example will be:
<tr>
<td>TEST</td>
</tr>
Read the PHP documentation that explains it.
@echo off
setlocal ENABLEEXTENSIONS
set KEY_NAME=HKLM\SOFTWARE\Wow6432Node\Acme Software Inc\Common
set VALUE_NAME=InstallDir
FOR /F "tokens=2*" %%A IN ('REG.exe query "%KEY_NAME%" /v "%VALUE_NAME%"') DO (set pInstallDir=%%B)
echo %pInstallDir%
That works for me in Win7 where the key has a space and the value also has a space. So saving the above in c:\temp as test.bat, open a cmd window and run it.
C:\temp>test
C:\Program Files (x86)\acme Software Inc\APP\
if ID
is available - You can use getElementById()
var element = document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
// exists.
}
OR Try with Jquery -
if ($(document).find(yourElement).length == 0)
{
// -- Not Exist
}
Instant.ofEpochMilli( 1_322_018_752_992L ) // Parse count of milliseconds-since-start-of-1970-UTC into an `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Assign a time zone to the `Instant` to produce a `ZonedDateTime` object.
The other answers use outmoded or incorrect classes.
Avoid the old date-time classes such as java.util.Date/.Calendar. They have proven to be poorly designed, confusing, and troublesome.
The java.time framework comes built into Java 8 and later. Much of the functionality is backported to Java 6 & 7 and further adapted to Android. Made by the some of the same folks as had made Joda-Time.
An Instant
is a moment on the timeline in UTC with a resolution of nanoseconds. Its epoch is first moment of 1970 in UTC.
Assuming your input data is a count of milliseconds from 1970-01-01T00:00:00Z (not clear in the Question), then we can easily instantiate an Instant
.
Instant instant = Instant.ofEpochMilli( 1_322_018_752_992L );
instant.toString(): 2011-11-23T03:25:52.992Z
The Z
in that standard ISO 8601 formatted string is short for Zulu
and means UTC.
Apply a time zone using a proper time zone name, to get a ZonedDateTime
.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( zoneId );
See this code run live at IdeOne.com.
Asia/Kolkata
time zone ?I am guessing your are had an India time zone affecting your code. We see here that adjusting into Asia/Kolkata
time zone renders the same time-of-day as you report, 08:55
which is five and a half hours ahead of our UTC value 03:25
.
2011-11-23T08:55:52.992+05:30[Asia/Kolkata]
You can apply the current default time zone of the JVM. Beware that the default can change at any moment during runtime. Any code in any thread of any app within the JVM can change the current default. If important, ask the user for their desired/expected time zone.
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
I ran into this issue as well. I don't know the technical details of what was actually happening. However, in my situation, the root cause was that there was cascading deletes setup in the Oracle database and my JPA/Hibernate code was also trying to do the cascading delete calls. So my advice is to make sure that you know exactly what is happening.
In case you're dealing with a Model, you can use the Attriutes API in Rails 5+ http://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute
just add a migration with a proper column name and then in the model set it with:
class StoreListing < ActiveRecord::Base
attribute :country, :string, default: 'PT'
end
autoconf
and automake
:configure
, make
and sudo make install
:./configure # Creates Makefile (from Makefile.in).
make # Creates the application (from the Makefile just created).
sudo make install # Installs the application
# Often, by default its files are installed into /usr/local
Notation below is roughly: inputs --> programs --> outputs
DEVELOPER runs these:
configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in
depreciated. Use configure.ac)
Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)
INSTALLER runs these:
Makefile.in -> configure -> Makefile (*.in = input file)
Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)
"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."
"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."
Manuals:
GNU AutoTools (The definitive manual on this stuff)
m4 (used by autoconf)
Free online tutorials:
The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)
From this my generated configure is over 41k lines of code.
And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)
Having two divs,
<div id="div1">The two divs are</div>
<div id="div2">next to each other.</div>
you could also use the display
property:
#div1 {
display: inline-block;
}
#div2 {
display: inline-block;
}
jsFiddle example here.
If div1
exceeds a certain height, div2
will be placed next to div1
at the bottom. To solve this, use vertical-align:top;
on div2
.
jsFiddle example here.
Watch for filenames in italic
Note that, the file name on the tab is formatted in italic if it has been opened in Preview Mode
.
Quickly take a file out of Preview Mode
To keep the file always available in VSCode editor (that is, to take it out of Preview Mode
into normal mode), you can double-click on the tab. Then, you will notice the name becomes non-italic.
Feature or bug?
I believe Preview Mode is helpful especially when you have limited screen space and need to check many files.
There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL
SQL> ed
Wrote file afiedt.buf
1 with x as (
2 select '1,2,3,a,b,c,d' str from dual
3 )
4 select regexp_substr(str,'[^,]+',1,level) element
5 from x
6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /
ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d
7 rows selected.
Or in PL/SQL
SQL> create type str_tbl is table of varchar2(100);
2 /
Type created.
SQL> create or replace function parse_list( p_list in varchar2 )
2 return str_tbl
3 pipelined
4 is
5 begin
6 for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
7 from dual
8 connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
9 loop
10 pipe row( x.element );
11 end loop
12 return;
13 end;
14
15 /
Function created.
SQL> select *
2 from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));
COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f
9 rows selected.
today is 29th of January, +1 month means 29th of Fabruary, but because February consists of 28 days this year, it overlaps to the next day which is March 1st
instead try
strtotime('next month')
Manage Jenkins/ configure system /GitHub Servers
On jenkins job / git credentials and Branch Specifier (give the branch you want to look for pushes)
Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.
But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)
You have to prepend every directory with -I
:
INC=-I/usr/informix/incl/c++ -I/opt/informix/incl/public
The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., UTF-8).
The document
and window
are different objects and they have some different events. Using addEventListener()
on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.
For example, there is a "resize"
event on the window
object that is not on the document
object.
For example, the "DOMContentLoaded"
event is only on the document
object.
So basically, you need to know which object receives the event you are interested in and use .addEventListener()
on that particular object.
Here's an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference
If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document
object before the window
object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document
over window
when either will work. But, I'd often move even closer to the source and use document.body
or even some closer common parent in the document (if possible).
$("#wizard li").click(function () {
console.log( $(this).index() );
});
However rather than attaching one click handler for each list item it is better (performance wise) to use delegate
which would look like this:
$("#wizard").delegate('li', 'click', function () {
console.log( $(this).index() );
});
In jQuery 1.7+, you should use on
. The below example binds the event to the #wizard
element, working like a delegate event:
$("#wizard").on("click", "li", function() {
console.log( $(this).index() );
});
You don't need one unless your class maintains unmanaged resources like Windows file handles.
Another python3 implementation that involves the use of Abstract classes with super(). You should remember that
super().__init__(name, 10)
has the same effect as
Person.__init__(self, name, 10)
Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it.
Hence super()
gets translated to Person
and then if you include the hidden self, you get the above code frag.
from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
name = ""
age = 0
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
@abstractmethod
def showName(self):
pass
@abstractmethod
def showAge(self):
pass
class Man(Person):
def __init__(self, name, height):
self.height = height
# Person.__init__(self, name, 10)
super().__init__(name, 10) # same as Person.__init__(self, name, 10)
# basically used to call the superclass init . This is used incase you want to call subclass init
# and then also call superclass's init.
# Since there's a hidden self in the super's parameters, when it's is called,
# the superclasses attributes are a part of the same object that was sent out in the super() method
def showIdentity(self):
return self.name, self.age, self.height
def showName(self):
pass
def showAge(self):
pass
a = Man("piyush", "179")
print(a.showIdentity())
The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:
<StackPanel>
<Label Foreground="Red">Red text</Label>
<Label Foreground="Blue">Blue text</Label>
</StackPanel>
In summary, No, there was nothing wrong with your snippet.
I think first one .To hide the complexity of Query. Its very appropriate for views .How when we normalize Database tables increases.Now to fetch data is very difficult when number of tables increases.So best way to handle is follow views.If i am wrong correct me.
Create a class TestUserDetailsImpl
on your test package:
@Service
@Primary
@Profile("test")
public class TestUserDetailsImpl implements UserDetailsService {
public static final String API_USER = "[email protected]";
private User getAdminUser() {
User user = new User();
user.setUsername(API_USER);
SimpleGrantedAuthority role = new SimpleGrantedAuthority("ROLE_API_USER");
user.setAuthorities(Collections.singletonList(role));
return user;
}
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
if (Objects.equals(username, ADMIN_USERNAME))
return getAdminUser();
throw new UsernameNotFoundException(username);
}
}
Rest endpoint:
@GetMapping("/invoice")
@Secured("ROLE_API_USER")
public Page<InvoiceDTO> getInvoices(){
...
}
Test endpoint:
@Test
@WithUserDetails("[email protected]")
public void testApi() throws Exception {
...
}
To rephrase Jarret Meyer's answer, you need to change the parameter name to 'id' or add a route like this:
routes.MapRoute(
"ViewStockNext", // Route name
"Inventory/ViewStockNext/{firstItem}", // URL with parameters
new { controller = "Inventory", action = "ViewStockNext" } // Parameter defaults
);
The reason is the default route only looks for actions with no parameter or a parameter called 'id'.
Edit: Heh, nevermind Jarret added a route example after posting.
You can try this script out since you do not want to target the Xoom only. I don't have a Xoom, but should work.
function mobile_detect(mobile,tablet,mobile_redirect,tablet_redirect,debug) {
var ismobile = (/iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/i.test(navigator.userAgent.toLowerCase()));
var istablet = (/ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/i.test(navigator.userAgent.toLowerCase()));
if (debug == true) {
alert(navigator.userAgent);
}
if (ismobile && mobile==true) {
if (debug == true) {
alert("Mobile Browser");
}
window.location = mobile_redirect;
} else if (istablet && tablet==true) {
if (debug == true) {
alert("Tablet Browser");
}
window.location = tablet_redirect;
}
}
I created a project on github. Check it out - https://github.com/codefuze/js-mobile-tablet-redirect. Feel free to submit issues if there is anything wrong!
cmd.exe /c '\my-app\my-file.bat'
With the v3 API, you can easily close the InfoWindow
with the InfoWindow.close()
method. You simply need to keep a reference to the InfoWindow
object that you are using. Consider the following example, which opens up an InfoWindow
and closes it after 5 seconds:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API InfoWindow Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 500px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(-25.36388, 131.04492),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
infowindow.open(map, marker);
setTimeout(function () { infowindow.close(); }, 5000);
</script>
</body>
</html>
If you have a separate InfoWindow
object for each Marker
, you may want to consider adding the InfoWindow
object as a property of your Marker
objects:
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
marker.infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
Then you would be able to open and close that InfoWindow
as follows:
marker.infowindow.open(map, marker);
marker.infowindow.close();
The same applies if you have an array of markers:
var markers = [];
marker[0] = new google.maps.Marker({
position: map.getCenter(),
map: map
});
marker[0].infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
// ...
marker[0].infowindow.open(map, marker);
marker[0].infowindow.close();
If you're running with jQuery you can use the datepicker UI library's parseDate function to convert your string to a date:
var d = $.datepicker.parseDate("DD, MM dd, yy", "Sunday, February 28, 2010");
and then follow it up with the formatDate method to get it to the string format you want
var datestrInNewFormat = $.datepicker.formatDate( "mm/dd/yy", d);
If you're not running with jQuery of course its probably not the best plan given you'd need jQuery core as well as the datepicker UI module... best to go with the suggestion from Segfault above to use date.js.
HTH
Don't use jsonObject.toString
on a JSON object.
I was also getting the same issue I tried multiple IPs like my public IP and localhost default IP 127.0.0.1 in windows and default gateway but same response. but I forget to check by
C:> ipconfig
ipconfig cleanly say what is my actual IP address of that adapter with which I have connected like I was connected with Wifi adapter my IP address will show me as:
Wireless LAN adapter Wireless Network Connection:
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : fe80::69fa:9475:431e:fad7%11
IPv4 Address. . . . . . . . . . . : 192.168.15.92
I hope this will help you.
I think the best way would be using a SimpleDateFormat
object.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2014-02-11";
Date dateObject = sdf.parse(dateString); // Handle the ParseException here
Here's a bit of code I've got added to FlappySwift that works:
import SpriteKit
import AVFoundation
class GameScene: SKScene {
// Grab the path, make sure to add it to your project!
var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()
// Initial setup
override func didMoveToView(view: SKView) {
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()
}
// Trigger the sound effect when the player grabs the coin
func didBeginContact(contact: SKPhysicsContact!) {
audioPlayer.play()
}
}
as ehogue said, put this in your CREATE TABLE
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
alternatively, if you already have the table created, use an ALTER TABLE command:
ALTER TABLE `accounts`
ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;
One good way to start learning these commands is using the MySQL GUI Tools, which give you a more "visual" interface for working with your database. The real benefit to that (over Access's method), is that after designing your table via the GUI, it shows you the SQL it's going to run, and hence you can learn from that.
The difference between gcc and g++ are:
gcc | g++
compiles c source | compiles c++ source
use g++ instead of gcc to compile you c++ source.
Basically action is a complement not a negation .
Here x= ~x produce results -(x+1) always .
x = ~2
-(2+1)
-3
Apparently it can be done via jQuery:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301
results
is now an object.
I ran into this problem although mine is slightly different. Posting here to maybe help somebody sometime.
I had
const Layout = ({ children }) => {
<div className="mx-4 my-3">
<Header />
<Menu />
{children}
<Footer />
</div>
};
But it needed to be:
const Layout = ({ children }) => (
<div className="mx-4 my-3">
<Header />
<Menu />
{children}
<Footer />
</div>
);
It's a difference of tabs vs spaces, I guess. I'm not sure why it'd care...
As already pointed out, b += 1
updates b
in-place, while a = a + 1
computes a + 1
and then assigns the name a
to the result (now a
does not refer to a row of A
anymore).
To understand the +=
operator properly though, we need also to understand the concept of mutable versus immutable objects. Consider what happens when we leave out the .reshape
:
C = np.arange(12)
for c in C:
c += 1
print(C) # [ 0 1 2 3 4 5 6 7 8 9 10 11]
We see that C
is not updated, meaning that c += 1
and c = c + 1
are equivalent. This is because now C
is a 1D array (C.ndim == 1
), and so when iterating over C
, each integer element is pulled out and assigned to c
.
Now in Python, integers are immutable, meaning that in-place updates are not allowed, effectively transforming c += 1
into c = c + 1
, where c
now refers to a new integer, not coupled to C
in any way. When you loop over the reshaped arrays, whole rows (np.ndarray
's) are assigned to b
(and a
) at a time, which are mutable objects, meaning that you are allowed to stick in new integers at will, which happens when you do a += 1
.
It should be mentioned that though +
and +=
are meant to be related as described above (and very much usually are), any type can implement them any way it wants by defining the __add__
and __iadd__
methods, respectively.
I think it's confused to mix up dynamic typing, static typing and duck typing. Duck typing is an independent concept and even static typed language like Go, could have a type checking system which implements duck typing. If a type system will check the methods of a (declared) object but not the type, it could be called a duck typing language.
You could use the object data type:
>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)
You can Just save the response(pdf,doc etc..) by option on the right side of the response in postman check this image
For more Details check this
https://learning.getpostman.com/docs/postman/sending_api_requests/responses/
Try using varchar2 instead of varchar and use this :
INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');
We have function total_seconds() with Python 2.7 Please see below code for python 2.6
import datetime
import time
def diffdates(d1, d2):
#Date format: %Y-%m-%d %H:%M:%S
return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))
d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)
The only problem with threads is accessing the same object from different threads without synchronization.
If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.
It really helps to understand the LINQ query syntax and how it is translated to LINQ method calls.
It turns out that
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
will be translated by the compiler to
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.OrderByDescending(p => p.LowestPrice)
.Select(p => p);
This is emphatically not what you want. This sorts by Product.LowestPrice.HasValue
in descending
order and then re-sorts the entire collection by Product.LowestPrice
in descending
order.
What you want is
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.ThenBy(p => p.LowestPrice)
.Select(p => p);
which you can obtain using the query syntax by
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending,
p.LowestPrice
select p;
For details of the translations from query syntax to method calls, see the language specification. Seriously. Read it.
I also had this problem recently, and it was the SELinux which caused it. I was trying to have the post-commit of subversion to notify Jenkins that the code has change so Jenkins would do a build and deploy to Nexus.
I had to do the following to get it to work.
1) First I checked if SELinux is enabled:
less /selinux/enforce
This will output 1 (for on) or 0 (for off)
2) Temporary disable SELinux:
echo 0 > /selinux/enforce
Now test see if it works now.
3) Enable SELinux:
echo 1 > /selinux/enforce
Change the policy for SELinux.
4) First view the current configuration:
/usr/sbin/getsebool -a | grep httpd
This will give you: httpd_can_network_connect --> off
5) Set this to on and your post-commit will work with SELinux:
/usr/sbin/setsebool -P httpd_can_network_connect on
Now it should be working again.
You can use my react-native-simple-shadow-view
Install an share your printer: \localhost\zebra Send ZPL as text, try with copy first:
copy file.zpl \localhost\zebra
very simple, almost no coding.
I ran into this error because I was trying to pass in a date from localStorage
. Passing the date into a new Date
object, and then calling .toISOString() did the trick for me:
const dateFromStorage = localStorage.getItem('someDate');
const date = new Date(dateFromStorage);
const momentDate = moment(date.toISOString());
This suppressed any warnings in the console.
I know there are already few working examples, but I think it's worth to propose my String.toFixed equivalent, some may find it helpful.
That's my toFixed alternative, that don't round numbers, just truncates it or adds zeroes according to given precision. For extra long number it uses JS build-in rounding when precision is to long. Function works for all problematic number I've found on stack.
function toFixedFixed(value, precision = 0) {
let stringValue = isNaN(+value) ? '0' : String(+value);
if (stringValue.indexOf('e') > -1 || stringValue === 'Infinity' || stringValue === '-Infinity') {
throw new Error('To large number to be processed');
}
let [ beforePoint, afterPoint ] = stringValue.indexOf('.') > -1 ? stringValue.split('.') : [ stringValue, ''];
// Force automatic rounding for some long real numbers that ends with 99X, by converting it to string, cutting off last digit, then adding extra nines and casting it on number again
// e.g. 2.0199999999999996: +('2.019999999999999' + '9999') will give 2.02
if (stringValue.length >= 17 && afterPoint.length > 2 && +afterPoint.substr(afterPoint.length - 3) > 995) {
stringValue = String(+(stringValue.substr(0, afterPoint.length - 1) + '9'.repeat(stringValue.split('.').shift().length + 4)));
[ beforePoint, afterPoint ] = String(stringValue).indexOf('.') > -1 ? stringValue.split('.') : [ stringValue, ''];
}
if (precision === 0) {
return beforePoint;
} else if (afterPoint.length > precision) {
return `${beforePoint}.${afterPoint.substr(0, precision)}`;
} else {
return `${beforePoint}.${afterPoint}${'0'.repeat(precision - afterPoint.length)}`;
}
}
Keep in mind that precision may not be handled properly for numbers of length 18 and greater, e.g. 64-bit Chrome will round it or add "e+" / "e-" to keep number's length at 18.
If you want to perform operations on real numbers it's safer to multiply it by Math.sqrt(10, precision)
first, make the calculations, then dive result by multiplier's value.
Example:
0.06 + 0.01
is0.06999999999999999
, and every formatting function that's not rounding will truncate it to0.06
for precision2
.But if you'll perform same operation with multiplier÷r:
(0.06 * 100 + 0.01 * 100) / 100
, you'll get0.07
.
That's why it's so important to use such multiplier/divider when dealing with real numbers in javascript, especially when you're calculating money...
Sure you can.
ALTER TABLE myTable ALTER COLUMN myColumn int NULL
Just substitute int for whatever datatype your column is.
Most likely, somewhere on your webserver will be an Alias directive like this;
Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.1.3.1/"
In my wampserver / localhost setup, it was in c:/wamp/alias/phpmyadmin.conf.
Just change the alias directive and you should be good to go.
You can do it with a simple loop:
var obj = null;
for (var i = 0; i < array.length; i++) {
if (array[i].name == "string 1") {
obj = array[i];
break;
}
}
useState
Use defaultValue
to select the default value.
const statusOptions = [
{ value: 1, label: 'Publish' },
{ value: 0, label: 'Unpublish' }
];
const [statusValue, setStatusValue] = useState('');
const handleStatusChange = e => {
setStatusValue(e.value);
}
return(
<>
<Select options={statusOptions}
defaultValue={[{ value: published, label: published == 1 ? 'Publish' : 'Unpublish' }]}
onChange={handleStatusChange}
value={statusOptions.find(obj => obj.value === statusValue)} required />
</>
)
You can also do this with named ranges so you don't have to copy the cells from Sheet1 to Sheet2:
Define a named range, say Sheet1Vals
for the column that has the values on which you want to base your condition. You can define a new named range by using the Insert\Name\Define...
menu item. Type in your name, then use the cell browser in the Refers to
box to select the cells you want in the range. If the range will change over time (add or remove rows) you can use this formula instead of selecting the cells explicitly:
=OFFSET('SheetName'!$COL$ROW,0,0,COUNTA('SheetName'!$COL:$COL))
.
Add a -1
before the last )
if the column has a header row.
Define a named range, say Sheet2Vals
for the column that has the values you want to conditionally format.
Use the Conditional Formatting dialog to create your conditions. Specify Formula Is
in the dropdown, then put this for the formula:
=INDEX(Sheet1Vals, MATCH([FirstCellInRange],Sheet2Vals))=[Condition]
where [FirstCellInRange]
is the address of the cell you want to format and [Condition]
is the value your checking.
For example, if my conditions in Sheet1 have the values of 1
, 2
and 3
and the column I'm formatting is column B
in Sheet2 then my conditional formats would be something like:
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=1
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=2
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=3
You can then use the format painter to copy these formats to the rest of the cells.
That is illegal syntax. It is not an optional thing for you to return a variable. You MUST return a variable of the type you specify in your method.
public String myMethod()
{
if(condition)
{
return x;
}
}
You are effectively saying, I promise any class can use this method(public) and I promise it will always return a String(String).
Then you are saying IF my condition is true I will return x. Well that is too bad, there is no IF in your promise. You promised that myMethod will ALWAYS return a String. Even if your condition is ALWAYS true the compiler has to assume that there is a possibility of it being false. Therefore you always need to put a return at the end of your non-void method outside of any conditions JUST IN CASE all of your conditions fail.
public String myMethod()
{
if(condition)
{
return x;
}
return ""; //or whatever the default behavior will be if all of your conditions fail to return.
}
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
(select add_date,col2 from table_name)
union
(select add_date,col2 from table_name)
union
(select add_date,col2 from table_name)
order by add_date
If I'm not wrong, both functions are part of your class, you should use it like this:
class MyClass():
def __init__(self, filename):
self.filename = filename
self.stat1 = None
self.stat2 = None
self.stat3 = None
self.stat4 = None
self.stat5 = None
self.parse_file()
def parse_file(self):
#do some parsing
self.stat1 = result_from_parse1
self.stat2 = result_from_parse2
self.stat3 = result_from_parse3
self.stat4 = result_from_parse4
self.stat5 = result_from_parse5
replace your line:
parse_file()
with:
self.parse_file()
Quick Answer:
git stash pop
-> remove from the stash list
git stash apply
-> keep it in the stash list
You probably don't have the correct permissions. Try adding yourself to these groups.
sudo adduser username ttyl
sudo adduser username serial
sudo adduser username uucp
Then restart your system and check if you got added to the groups.
groups username
Good Luck!
It is not recommended to use DataReader
and Command.ExecuteReader
to get just one value from the database. Instead, you should use Command.ExecuteScalar
as following:
String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();
Here is more information about Connecting to database and managing data.
If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]"
does the matching, result will be in $Matches[0]
I use Telegram.Bot
and got the ID the following way:
/authenticate
or foo
)private static async Task Main()
{
var botClient = new TelegramBotClient("key");
botClient.OnUpdate += BotClientOnOnUpdate;
Console.ReadKey();
}
private static async void BotClientOnOnUpdate(object? sender, UpdateEventArgs e)
{
var id = e.Update.ChannelPost.Chat.Id;
await botClient.SendTextMessageAsync(new ChatId(id), $"Hello World! Channel ID is {id}");
}
This translates to the getUpdates
method in the plain API, which has an array of Update
which then contains channel_post.chat.id
I believe right now your output printing as below
~ echo -e "String1\nString2"
String1
String2
You can use xargs
to get multiline stdout into same line.
~ echo -e "String1\nString2" | xargs
String1 String2
~
//String appending
#include <iostream>
using namespace std;
void stringconcat(char *str1, char *str2){
while (*str1 != '\0'){
str1++;
}
while(*str2 != '\0'){
*str1 = *str2;
str1++;
str2++;
}
}
int main() {
char str1[100];
cin.getline(str1, 100);
char str2[100];
cin.getline(str2, 100);
stringconcat(str1, str2);
cout<<str1;
getchar();
return 0;
}
You should use the equals
method since this is implemented to perform the comparison you want. toString()
itself uses an iterator just like equals
but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString
is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).
Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString
and equals
behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.
See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
boolean equals(Object o)
Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.
Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap
which is used by classes such as HashMap
:
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* <p>This implementation first checks if the specified object is this map;
* if so it returns <tt>true</tt>. Then, it checks if the specified
* object is a map whose size is identical to the size of this map; if
* not, it returns <tt>false</tt>. If so, it iterates over this map's
* <tt>entrySet</tt> collection, and checks that the specified map
* contains each mapping that this map contains. If the specified map
* fails to contain such a mapping, <tt>false</tt> is returned. If the
* iteration completes, <tt>true</tt> is returned.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> m = (Map<K,V>) o;
if (m.size() != size())
return false;
try {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key)==null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
toString
fails miserably when comparing a TreeMap
and HashMap
though equals
does compare contents correctly.
Code:
public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");
System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
+ map.toString().equals(map2.toString()));
System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}
Output:
Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}
Try this example.
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<GridView
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/grid"
android:background="#fff7ff"
/>
</LinearLayout>
grid_single.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="@+id/grid_image"
android:layout_width="60dp"
android:layout_height="60dp"
>
</ImageView>
<TextView
android:id="@+id/grid_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textSize="9sp"
android:textColor="#3a0fff">
</TextView>
</LinearLayout>
CustomGrid.java:
package com.example.lalit.gridtest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomGrid extends BaseAdapter {
private Context mContext;
private final String[] web;
private final int[] Imageid;
public CustomGrid(Context c, String[] web, int[] Imageid) {
mContext = c;
this.Imageid = Imageid;
this.web = web;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return web.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
textView.setText(web[position]);
imageView.setImageResource(Imageid[position]);
} else {
grid = (View) convertView;
}
return grid;
}
}
MainActivity.java:
package com.example.lalit.gridtest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
GridView grid;
String[] web = {
"Mom",
"Mahendra",
"Narayan",
"Bhai",
"Deepak",
"Sanjay",
"Navdeep",
"Lovesh",
};
int[] imageId = {
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id){
if (web[position].toString().equals("Mom")) {
try {
String uri ="te:"+ "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if (web[position].toString().equals("Mahendra")) {
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Narayan")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Bhai")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Deepak")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Sanjay")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Navdeep")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Lovesh")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
});
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lalit.gridtest" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I tried clearing the chrome cookies to get rid of postman cookies, as one of the answers given here. But it didn't work for me. I checked my postman version, found that it's an old version 5.5.4. So I just tried a Postman update to its latest version 7.3.4. Cool, the issue fixed !!
function readFile() {_x000D_
_x000D_
if (this.files && this.files[0]) {_x000D_
_x000D_
var FR= new FileReader();_x000D_
_x000D_
FR.addEventListener("load", function(e) {_x000D_
document.getElementById("img").src = e.target.result;_x000D_
document.getElementById("b64").innerHTML = e.target.result;_x000D_
}); _x000D_
_x000D_
FR.readAsDataURL( this.files[0] );_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById("inp").addEventListener("change", readFile);
_x000D_
<input id="inp" type='file'>_x000D_
<p id="b64"></p>_x000D_
<img id="img" height="150">
_x000D_
(P.S: A base64 encoded image (String) 4/3 the size of the original image data)
Check this answer for multiple images upload.
Browser support: http://caniuse.com/#search=file%20api
More info here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
You'll have to pass the new ordinal position to insert
using len
in this case:
In [62]:
a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]