I changed the TextView's color to blue by using for example:
android:textColor="#3399FF"
in the xml file. How to make it underlined is explained here.
Then use its onClick property to specify a method (I'm guessing you could call setOnClickListener(this)
as another way), e.g.:
myTextView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doSomething();
}
});
In that method, I can do whatever I want as normal, such as launch an intent. Note that you still have to do the normal myTextView.setMovementMethod(LinkMovementMethod.getInstance());
thing, like in your acitivity's onCreate() method.
JSON.parse()
is used to convert String to Object.
JSON.stringify()
is used to convert Object to String.
You can refer this too...
<script type="text/javascript">
function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open("GET", "JSON/mylist.json", true);
hr.setRequestHeader("Content-type", "application/json",true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
/* var return_data = hr.responseText; */
var data=JSON.parse(hr.responseText);
var status=document.getElementById("status");
status.innerHTML = "";
/* status.innerHTML=data.u1.country; */
for(var obj in data)
{
status.innerHTML+=data[obj].uname+" is in "+data[obj].country+"<br/>";
}
}
}
hr.send(null);
status.innerHTML = "requesting...";
}
</script>
In my case, it goes well after I installed CMake in my system:)
sudo pacman -S cmake
for manjaro operating system.
You can use this query
update table_name set column_name = replace (column_name , 'oldstring' ,'newstring') where column_name like 'oldstring%'
Use getch()
:
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
Windows alternative should be _getch().
If you're using Windows, this should be the full example:
#include <conio.h>
#include <ctype.h>
int main( void )
{
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
_getch();
}
P.S. as @Rörd noted, if you're on POSIX system, you need to make sure that curses library is setup right.
I have updated the code to make it works for me
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(idx, jqXHR) {
jqXHR.abort();
});
$(this).each(function(idx, jqXHR) {
var index = $.inArray(jqXHR, $.xhrPool);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
});
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = $.inArray(jqXHR, $.xhrPool);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
}
});
If you have GNU parallel you could convert all .avi files below vid_dir
to mp4 in parallel, using all except one of your CPU cores with
find vid_dir -type f -name '*.avi' -not -empty -print0 |
parallel -0 -j -1 ffmpeg -loglevel fatal -i {} {.}.mp4
To convert from/to different formats, change '*.avi'
or .mp4
as needed. GNU parallel is listed in most Linux distributions' repositories in a package which is usually called parallel
.
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
When you download tomcat from their official website (of today that's tomcat version 9.0.26), all the apps you installed to tomcat can handle HTTP requests of unlimited size, given that the apps themselves do not have any limits on request size.
However, when you try to upload an app in tomcat's manager app, that app has a default war file limit of 50MB. If you're trying to install Jenkins for example which is 77 MB as ot today, it will fail.
Tomcat itself has size limit for each port, and this is defined in conf\server.xml
. This is controlled by maxPostSize
attribute of each Connector
(port). If this attribute does not exist, which it is by default, there is no limit on the request size.
To add a limit to a specific port, set a byte size for the attribute. For example, the below config for the default 8080 port limits request size to 200 MB. This means that all the apps installed under port 8080 now has the size limit of 200MB
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxPostSize="209715200" />
After passing the port level size limit, you can still configure app level limit. This also means that app level limit should be less than port level limit. The limit can be done through annotation within each servlet, or in the web.xml file. Again, if this is not set at all, there is no limit on request size.
To set limit through java annotation
@WebServlet("/uploadFiles")
@MultipartConfig( fileSizeThreshold = 0, maxFileSize = 209715200, maxRequestSize = 209715200)
public class FileUploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// ...
}
}
To set limit through web.xml
<web-app>
...
<servlet>
...
<multipart-config>
<file-size-threshold>0</file-size-threshold>
<max-file-size>209715200</max-file-size>
<max-request-size>209715200</max-request-size>
</multipart-config>
...
</servlet>
...
</web-app>
Tomcat's Manager app (by default localhost:8080/manager) is nothing but a default web app. By default that app has a web.xml
configuration of request limit of 50MB. To install (upload) app with size greater than 50MB through this manager app, you have to change the limit. Open the manager app's web.xml file from webapps\manager\WEB-INF\web.xml
and follow the above guide to change the size limit and finally restart tomcat.
I like the look of that apex utility. However its also good to know about the standard oracle functions you can use for this: subStr and inStr http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm
Make sure:
In my case I had 1 and 2 correct but forgot to name my file with .php extension. How I forgot, no idea but it sure gave me a hard time trying to figure out the problem
Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/
and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1
.
See this link for the official GlassFish documentation about logging.
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
NOTE: Potentially outdated. ECMAScript 2017 includes
String.prototype.padStart
.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the -
and read it.
I think the reason those suggesting using the C:\PROGRA~1 name have received downvotes is because those names are seen as a legacy feature of Windows best forgotten, which may also be unstable, at least between different installations, although probably not on the same machine.
Also, as someone pointed out in a comment to another answer, Windows can be configured not to have the 8.3 legacy names in the filesystem at all.
My answer is focused to a extended case derived from the one exposed at top.
Suppose you have group of elements from which you want to hide the child elements except first. As an example:
<html>
<div class='some-group'>
<div class='child child-0'>visible#1</div>
<div class='child child-1'>xx</div>
<div class='child child-2'>yy</div>
</div>
<div class='some-group'>
<div class='child child-0'>visible#2</div>
<div class='child child-1'>aa</div>
<div class='child child-2'>bb</div>
</div>
</html>
We want to hide all .child
elements on every group. So this will not help because will hide all .child
elements except visible#1
:
$('.child:not(:first)').hide();
The solution (in this extended case) will be:
$('.some-group').each(function(i,group){
$(group).find('.child:not(:first)').hide();
});
Problem: While importing the " org.apache.poi.xssf.usermodel.XSSFWorkbook"class showing an error in eclipse.
Solution: Use This maven dependency to resolve this problem:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
-Hari Krishna Neela
In my case, the function CString was not found. But adding an empty string to the value works, too.
Dim Test As Integer, Test2 As Variant
Test = 10
Test2 = Test & ""
//Test2 is now "10" not 10
SQLAlchemy introduced that in version 1.0.0
:
Bulk operations - SQLAlchemy docs
With these operations, you can now do bulk inserts or updates!
For instance, you can do:
s = Session()
objects = [
User(name="u1"),
User(name="u2"),
User(name="u3")
]
s.bulk_save_objects(objects)
s.commit()
Here, a bulk insert will be made.
Examples from Ned Batchelder highly recommended for iterators and generators
A method without generators that do something to even numbers
def evens(stream):
them = []
for n in stream:
if n % 2 == 0:
them.append(n)
return them
while by using a generator
def evens(stream):
for n in stream:
if n % 2 == 0:
yield n
return
statementCalling the evens
method (generator) is as usual
num = [...]
for n in evens(num):
do_smth(n)
Iterator
A book full of pages is an iterable, A bookmark is an iterator
and this bookmark has nothing to do except to move next
litr = iter([1,2,3])
next(litr) ## 1
next(litr) ## 2
next(litr) ## 3
next(litr) ## StopIteration (Exception) as we got end of the iterator
To use Generator ... we need a function
To use Iterator ... we need next
and iter
As been said:
A Generator function returns an iterator object
The Whole benefit of Iterator:
Store one element a time in memory
The question has been answered, my contribution consists in clarifying one thing that may confuse beginners:
Some of the suggested and correct answers used firstChild.data
and others used firstChild.nodeValue
instead. In case you are wondering what is the different between them, you should remember they do the same thing because nodeValue
is just an alias for data
.
The reference to my statement can be found as a comment on the source code of minidom:
#
nodeValue
is an alias fordata
No, the powers that be at Google chose not to support that.
https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ
This is my solution
var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
console.log("My contents is \"" + cells[i].innerHTML + "\"");
}
As ExpandoObject
inherits the IDictionary<string, object>
you can use the following check
dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();
if (((IDictionary<string, object>)myVariable).ContainsKey("MyProperty"))
//Do stuff
You can make a utility method to perform this check, that will make the code much cleaner and re-usable
Solution:
1. Shut down Pg server
2. It will disconnect all active connection
3. Restart Pg Server
4. Try your command
Here is the code
Source: forums.devx.com/showthread.php?t=153784
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
/**
* list resources available from the classpath @ *
*/
public class ResourceList{
/**
* for all elements of java.class.path get a Collection of resources Pattern
* pattern = Pattern.compile(".*"); gets all resources
*
* @param pattern
* the pattern to match
* @return the resources in the order they are found
*/
public static Collection<String> getResources(
final Pattern pattern){
final ArrayList<String> retval = new ArrayList<String>();
final String classPath = System.getProperty("java.class.path", ".");
final String[] classPathElements = classPath.split(System.getProperty("path.separator"));
for(final String element : classPathElements){
retval.addAll(getResources(element, pattern));
}
return retval;
}
private static Collection<String> getResources(
final String element,
final Pattern pattern){
final ArrayList<String> retval = new ArrayList<String>();
final File file = new File(element);
if(file.isDirectory()){
retval.addAll(getResourcesFromDirectory(file, pattern));
} else{
retval.addAll(getResourcesFromJarFile(file, pattern));
}
return retval;
}
private static Collection<String> getResourcesFromJarFile(
final File file,
final Pattern pattern){
final ArrayList<String> retval = new ArrayList<String>();
ZipFile zf;
try{
zf = new ZipFile(file);
} catch(final ZipException e){
throw new Error(e);
} catch(final IOException e){
throw new Error(e);
}
final Enumeration e = zf.entries();
while(e.hasMoreElements()){
final ZipEntry ze = (ZipEntry) e.nextElement();
final String fileName = ze.getName();
final boolean accept = pattern.matcher(fileName).matches();
if(accept){
retval.add(fileName);
}
}
try{
zf.close();
} catch(final IOException e1){
throw new Error(e1);
}
return retval;
}
private static Collection<String> getResourcesFromDirectory(
final File directory,
final Pattern pattern){
final ArrayList<String> retval = new ArrayList<String>();
final File[] fileList = directory.listFiles();
for(final File file : fileList){
if(file.isDirectory()){
retval.addAll(getResourcesFromDirectory(file, pattern));
} else{
try{
final String fileName = file.getCanonicalPath();
final boolean accept = pattern.matcher(fileName).matches();
if(accept){
retval.add(fileName);
}
} catch(final IOException e){
throw new Error(e);
}
}
}
return retval;
}
/**
* list the resources that match args[0]
*
* @param args
* args[0] is the pattern to match, or list all resources if
* there are no args
*/
public static void main(final String[] args){
Pattern pattern;
if(args.length < 1){
pattern = Pattern.compile(".*");
} else{
pattern = Pattern.compile(args[0]);
}
final Collection<String> list = ResourceList.getResources(pattern);
for(final String name : list){
System.out.println(name);
}
}
}
If you are using Spring Have a look at PathMatchingResourcePatternResolver
One thing I've used with good results is the following (I don't know if its mentioned already because I can't remember its name).
You precompute a table T with a random number for each character in your key's alphabet [0,255]. You hash your key 'k0 k1 k2 ... kN' by taking T[k0] xor T[k1] xor ... xor T[kN]. You can easily show that this is as random as your random number generator and its computationally very feasible and if you really run into a very bad instance with lots of collisions you can just repeat the whole thing using a fresh batch of random numbers.
As usual in Angular, you can rely on dependency injection:
import { DatePipe } from '@angular/common';
class MyService {
constructor(private datePipe: DatePipe) {}
transformDate(date) {
return this.datePipe.transform(date, 'yyyy-MM-dd');
}
}
Add DatePipe
to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe
:
providers: [DatePipe,...]
Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate
function directly.
import { formatDate } from '@angular/common';
class MyService {
constructor(@Inject(LOCALE_ID) private locale: string) {}
transformDate(date) {
return formatDate(date, 'yyyy-MM-dd', this.locale);
}
}
Before Angular 5: Be warned though that the DatePipe
was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).
If you're using older Angular versions, you should add the Intl
polyfill to your project to avoid any problem.
See this related question for a more detailed answer.
Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.
Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).
Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).
mayby one little change from the top answer, because DB_NAME()
returns always content db of execution. so, for me better like below:
sp_MSforeachdb 'select DB_name(db_id(''?'')) as DB, * From ?..sysobjects where xtype in (''U'', ''P'') And name like ''[_]x[_]%'''
In my case I was looking for tables their names started with _x_
Cheers, Ondrej
https://facebook.github.io/react/tips/expose-component-functions.html for more answers ref here Call methods on React children components
By looking into the refs of the "reason" component, you're breaking encapsulation and making it impossible to refactor that component without carefully examining all the places it's used. Because of this, we strongly recommend treating refs as private to a component, much like state.
In general, data should be passed down the tree via props. There are a few exceptions to this (such as calling .focus() or triggering a one-time animation that doesn't really "change" the state) but any time you're exposing a method called "set", props are usually a better choice. Try to make it so that the inner input component worries about its size and appearance so that none of its ancestors do.
If you are using the latest Skype, go to:
Tools -> Options -> Advanced -> connection.
Disable the 'Use port 80 and 443 for alternatve.. '
Sign Out and Close all Skype windows. Try restart your Apache again.
You can get the spark version by using the following command:
spark-submit --version
spark-shell --version
spark-sql --version
You can visit the below site to know the spark-version used in CDH 5.7.0
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
Sounds like mssql jdbc is buffering the entire resultset for you. You can add a connect string parameter saying selectMode=cursor or responseBuffering=adaptive. If you are on version 2.0+ of the 2005 mssql jdbc driver then response buffering should default to adaptive.
You have missed one style ".btn-primary:active:focus" which causes that still during btn click default bootstrap color show up for a second. This works in my code:
.btn-primary, .btn-primary:hover, .btn-primary:active, .btn-primary:visited, .btn-primary:focus, .btn-primary:active:focus {
background-color: #8064A2;}
On some investigation, the answer appears to be (a).
When I go to change the settings, the settings file goes into a .vscode directory in my project directory.
This code worked for me:
$(function(){
$('input:radio').change(function(){
alert('changed');
});
});
Another alternative can be to execute the Keydown or KeyUp in the tag of the Form
<form name="nameForm" [formGroup]="groupForm" (keydown.enter)="executeFunction()" >
Previous answers are good enough, but they might update original data. In case if you don't want the original data to be affected, you can try my code.
newhash=hash.reject{|k| k=='_id'}.merge({id:hash['_id']})
First it will ignore the key '_id' then merge with the updated one.
No. See also this link Handle conditional null in HQL for tips and tricks on how to handle comparisons with both null and non-null values.
You just need to have your class inherit from Comparable.
then implement the compareTo method the way you like.
while(dr.read())
{
returnPersonList.add(
new Person(dr.GetInt32(1), dr.GetInt32(0), dr.GetString(2)));
}
where:
public class Person
{
public Person(int age, int id, string name)
{
Age = age;
Id = id;
Name = name;
}
}
Look for this:
ANY page in your project that has a missing, or different Namespace...
If you have ANY page in your project with <NO Namespace
> , OR a
DIFFERENT Namespace than Default.aspx, you will get this
"Cannot load Default.aspx", or this: "Default.aspx does not belong here".
ALSO: If you have a Redirect to a page in your Solution/Project and the page which is to be Redirected To has a bad namespace -- you may not get a compiler error, until you try and run. If the Redirect is removed or commented-out, the error goes away...
BTW -- What the hell do these error messages mean? Is this MS.Access, with the "misdirection" -- ??
DGK
Logically, Cody's answer should work. However I don't think the command prompt handles a code block logically. For the life of me I can't get that to work properly with any more than a single command within the block. In my case, extensive testing revealed that all of the commands within the block are being cached, and executed simultaneously at the end of the block. This of course doesn't yield the expected results. Here is an oversimplified example:
if %ERRORLEVEL%==0 (
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
)
This should provide var3 with the following value:
blue_cheese
but instead yields:
_
because all 3 commands are cached and executed simultaneously upon exiting the code block.
I was able to overcome this problem by re-writing the if block to only execute one command - goto - and adding a few labels. Its clunky, and I don't much like it, but at least it works.
if %ERRORLEVEL%==0 goto :error0
goto :endif
:error0
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
:endif
It sounds like your workbook got set to Manual Calculation. You can change this to Automatic by going to Formulas > Calculation > Calculation Options > Automatic.
Manual calculation can be useful to reduce computational load and improve responsiveness in workbooks with large amounts of formulas. The idea is that you can look at data and make changes, then choose when you want to make your computer go through the effort of calculation.
In my case my provisioning profile was invalid because apple has changed some of its terms and conditions. To fix problem I had to
For simple process watching use watch
instead
Unless you need the 'maven-assembly-plugin' for reasons other than setting the mainClass, you could use the 'maven-jar-plugin' plugin.
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<mainClass>your.package.yourprogram.YourMainClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
You can see the plugin in practise in the ATLauncher.
The 'mainClass' element should be set to the class that you have the entry point to your program in eg:
package your.package.yourprogram;
public class YourMainClass {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress)
, which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformation
namespace contains a class called PingReply
that has properties designed to translate the ICMP
response and deliver useful information about the pinged server such as:
The following is a simple example using WinForms
to demonstrate how ping works in c#. By providing a valid IP address in textBox1
and clicking button1
, we are creating an instance of the Ping
class, a local variable PingReply
, and a string to store the IP or URL address. We assign PingReply
to the ping Send
method, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Success
status. Finally, we extract from PingReply
the information we need to display for the user, which is described above.
using System;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace PingTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Ping p = new Ping();
PingReply r;
string s;
s = textBox1.Text;
r = p.Send(s);
if (r.Status == IPStatus.Success)
{
lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
+ " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
}
}
private void textBox1_Validated(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
{
MessageBox.Show("Please use valid IP or web address!!");
}
}
}
}
There is input type month in HTML5 which allows to select month and year. Month selector works with autocomplete.
Check the example in JSFiddle.
<!DOCTYPE html>
<html>
<body>
<header>
<h1>Select a month below</h1>
</header>
Month example
<input type="month" />
</body>
</html>
This works for me
$('ul.questions li a').click(function(event) {
event.preventDefault();
$('.tab').hide();
window.location.hash = this.hash;
$($(this).attr('href')).fadeIn('slow');
});
Check here http://jsbin.com/edicu for a demo with almost identical code
Combining and organizing all the current answers into one answer, then adding my own research:
Brief summary of Microsoft gadget development:
What are they written in? Windows Vista/Seven gadgets are developed in a mix of XML, HTML, CSS, and some IE scripting language. It is also possible to use C# with the latest release of Script#.
How are they packaged/deployed? The actual gadgets are stored in *.gadget files, which are simply the text source files listed above compressed into a single zip file.
Useful references for gadget development:
where do I start? Good introductory references to Windows Vista/Seven gadget development:
If you are willing to use offline resources, this book appears to be an excellent resource:
What do I need to know? Some other useful references; not necessarily instructional
Update: Well, this has proven to be a popular answer~ Sharing my own recent experience with Windows 7 gadget development:
Perhaps the easiest way to get started with Windows 7 gadget development is to modify a gadget that has already been developed. I recently did this myself because I wanted a larger clock gadget. Unable to find any, I tinkered with a copy of the standard Windows clock gadget until it was twice as large. I recommend starting with the clock gadget because it is fairly small and well-written. Here is the process I used:
C:\Program Files\Windows Sidebar\Gadgets\Clock.Gadget\
<name>Clock</name>
This is the name that will be displayed in the "Gadgets Gallery" window.%LOCALAPPDATA%\Microsoft\Windows Sidebar\
)Huge difference.
As the name implies, a double
has 2x the precision of float
[1]. In general a double
has 15 decimal digits of precision, while float
has 7.
Here's how the number of digits are calculated:
double
has 52 mantissa bits + 1 hidden bit: log(253)÷log(10) = 15.95 digits
float
has 23 mantissa bits + 1 hidden bit: log(224)÷log(10) = 7.22 digits
This precision loss could lead to greater truncation errors being accumulated when repeated calculations are done, e.g.
float a = 1.f / 81;
float b = 0;
for (int i = 0; i < 729; ++ i)
b += a;
printf("%.7g\n", b); // prints 9.000023
while
double a = 1.0 / 81;
double b = 0;
for (int i = 0; i < 729; ++ i)
b += a;
printf("%.15g\n", b); // prints 8.99999999999996
Also, the maximum value of float is about 3e38
, but double is about 1.7e308
, so using float
can hit "infinity" (i.e. a special floating-point number) much more easily than double
for something simple, e.g. computing the factorial of 60.
During testing, maybe a few test cases contain these huge numbers, which may cause your programs to fail if you use floats.
Of course, sometimes, even double
isn't accurate enough, hence we sometimes have long double
[1] (the above example gives 9.000000000000000066 on Mac), but all floating point types suffer from round-off errors, so if precision is very important (e.g. money processing) you should use int
or a fraction class.
Furthermore, don't use +=
to sum lots of floating point numbers, as the errors accumulate quickly. If you're using Python, use fsum
. Otherwise, try to implement the Kahan summation algorithm.
[1]: The C and C++ standards do not specify the representation of float
, double
and long double
. It is possible that all three are implemented as IEEE double-precision. Nevertheless, for most architectures (gcc, MSVC; x86, x64, ARM) float
is indeed a IEEE single-precision floating point number (binary32), and double
is a IEEE double-precision floating point number (binary64).
.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.
What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.
You can also use shorthand for describe as desc
for table description.
desc [db_name.]table_name;
or
use db_name;
desc table_name;
You can also use explain
for table description.
explain [db_name.]table_name;
See official doc
Will give output like:
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(10) | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
| age | int(10) | YES | | NULL | |
| sex | varchar(10) | YES | | NULL | |
| sal | int(10) | YES | | NULL | |
| location | varchar(20) | YES | | Pune | |
+----------+-------------+------+-----+---------+-------+
//
syntaxregex.test(string)
, not string.test(regex)
So
jQuery(function () {
$(".mail").keyup(function () {
var VAL = this.value;
var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');
if (email.test(VAL)) {
alert('Great, you entered an E-Mail-address');
}
});
});
What about something like this?
//$elem is the jQuery object passed along.
var $currentText = $elem.context.firstChild.data.toUpperCase();
** I needed to make mine uppercase.
you can also use like that
export class SampleComponent {
numbers:Array<any> = [];
constructor() {
this.numbers = Array.from({length:10},(v,k)=>k+1);
}
}
HTML
<p *ngFor="let i of numbers">
{{i}}
</p>
In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.
When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).
Remember to call wait() on the child process to prevent any lingering zombies.
Shimi_tap's answer is the right way to fix the problem. If you want to use old merger tool you can add this to build.gradle file
android { useOldManifestMerger true }
You can implement a SoapExtension that logs the full request and response to a log file. You can then enable the SoapExtension in the web.config, which makes it easy to turn on/off for debugging purposes. Here is an example that I have found and modified for my own use, in my case the logging was done by log4net but you can replace the log methods with your own.
public class SoapLoggerExtension : SoapExtension
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Stream oldStream;
private Stream newStream;
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override object GetInitializer(Type serviceType)
{
return null;
}
public override void Initialize(object initializer)
{
}
public override System.IO.Stream ChainStream(System.IO.Stream stream)
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
Log(message, "AfterSerialize");
CopyStream(newStream, oldStream);
newStream.Position = 0;
break;
case SoapMessageStage.BeforeDeserialize:
CopyStream(oldStream, newStream);
Log(message, "BeforeDeserialize");
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
public void Log(SoapMessage message, string stage)
{
newStream.Position = 0;
string contents = (message is SoapServerMessage) ? "SoapRequest " : "SoapResponse ";
contents += stage + ";";
StreamReader reader = new StreamReader(newStream);
contents += reader.ReadToEnd();
newStream.Position = 0;
log.Debug(contents);
}
void ReturnStream()
{
CopyAndReverse(newStream, oldStream);
}
void ReceiveStream()
{
CopyAndReverse(newStream, oldStream);
}
public void ReverseIncomingStream()
{
ReverseStream(newStream);
}
public void ReverseOutgoingStream()
{
ReverseStream(newStream);
}
public void ReverseStream(Stream stream)
{
TextReader tr = new StreamReader(stream);
string str = tr.ReadToEnd();
char[] data = str.ToCharArray();
Array.Reverse(data);
string strReversed = new string(data);
TextWriter tw = new StreamWriter(stream);
stream.Position = 0;
tw.Write(strReversed);
tw.Flush();
}
void CopyAndReverse(Stream from, Stream to)
{
TextReader tr = new StreamReader(from);
TextWriter tw = new StreamWriter(to);
string str = tr.ReadToEnd();
char[] data = str.ToCharArray();
Array.Reverse(data);
string strReversed = new string(data);
tw.Write(strReversed);
tw.Flush();
}
private void CopyStream(Stream fromStream, Stream toStream)
{
try
{
StreamReader sr = new StreamReader(fromStream);
StreamWriter sw = new StreamWriter(toStream);
sw.WriteLine(sr.ReadToEnd());
sw.Flush();
}
catch (Exception ex)
{
string message = String.Format("CopyStream failed because: {0}", ex.Message);
log.Error(message, ex);
}
}
}
[AttributeUsage(AttributeTargets.Method)]
public class SoapLoggerExtensionAttribute : SoapExtensionAttribute
{
private int priority = 1;
public override int Priority
{
get { return priority; }
set { priority = value; }
}
public override System.Type ExtensionType
{
get { return typeof (SoapLoggerExtension); }
}
}
You then add the following section to your web.config where YourNamespace and YourAssembly point to the class and assembly of your SoapExtension:
<webServices>
<soapExtensionTypes>
<add type="YourNamespace.SoapLoggerExtension, YourAssembly"
priority="1" group="0" />
</soapExtensionTypes>
</webServices>
Xml declaration is optional so your xml is well-formed without it. But it is recommended to use it so that wrong assumptions are not made by the parsers, specifically about the encoding used.
I have the same error and it fixed it including in the file the following
#include <stdint.h>
at the beginning of your file.
Note that your initial query is probably not returning what you want:
SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate
You are grouping by book date, but you are not using any grouping function on the second column of your query.
The query you are probably looking for is:
SELECT availables.bookdate AS Date, count(*) as subtotal, sum(DATEDIFF(now(),availables.updated_at) as Age)
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:
<table>
<tr>
<td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
Hello World
</td>
</tr>
</table>
if (@available(iOS 11.0, *)) {
self.navigationController.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
self.navigationController.navigationBar.prefersLargeTitles = true;
// Change Color
self.navigationController.navigationBar.largeTitleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
} else {
// Fallback on earlier versions
}
It is saying the value is undefined
because it is a constructor function
, not a class
with a constructor
. In order to use it, you would need to use Customer()
or customer()
.
First, you need to load file1.js before file2.js, like slebetman said:
<script defer src="file1.js" type="module"></script>
<script defer src="file2.js" type="module"></script>
Then, you could change your file1.js as follows:
export default class Customer(){
constructor(){
this.name="Jhon";
this.getName=function(){
return this.name;
};
}
}
And the file2.js as follows:
import { Customer } from "./file1";
var customer=new Customer();
Please correct me if I am wrong.
You can add this in your css file:
[data-role=page]{height: 100% !important; position:relative !important;}
[data-role=footer]{bottom:0; position:absolute !important; top: auto !important; width:100%;}
So the page data-role now have 100% height, and footer is in absolute position.
Also Yappo have wrote an excellent plugin that you can find here: jQuery Mobile in a iScroll plugin http://yappo.github.com/projects/jquery.mobile.iscroll/livedemo.html
hope you found the answer!
An answer update
You can now use the data-position="fixed"
attribute to keep your footer element on the bottom.
Docs and demos: http://view.jquerymobile.com/master/demos/toolbar-fixed/
var isProduction = (process.argv.indexOf("production")>-1);
CLI gulp production
calls my production task and sets a flag for any conditionals.
I found a shorter solution that does exactly what I want https://github.com/http-party/node-http-proxy
After installing http-proxy
npm install http-proxy --save
Use it like below in your server/index/app.js
var proxyServer = require('http-route-proxy');
app.use('/api/BLABLA/', proxyServer.connect({
to: 'other_domain.com:3000/BLABLA',
https: true,
route: ['/']
}));
I really have spent days looking everywhere to avoid this issue, tried plenty of solutions and none of them worked but this one.
Hope it is going to help someone else too :)
You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.
As I mentioned in the comment, having to use the dot()
function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.
Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @
infix-operator for matrix multiplication, thanks to pep 465.
Edit: Regarding your comment:
Yes. The whole of numpy is based on arrays.
Yes. linalg.norm(v)
is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.
To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.
An example in ipython:
In [1]: import math
In [2]: import numpy as np
In [3]: a = np.array([4,2,7])
In [4]: np.linalg.norm(a)
Out[4]: 8.3066238629180749
In [5]: math.sqrt(sum([n**2 for n in a]))
Out[5]: 8.306623862918075
In [6]: b = a/np.linalg.norm(a)
In [7]: np.linalg.norm(b)
Out[7]: 1.0
Note that In [5]
is an alternative way to calculate the length. In [6]
shows normalizing the vector.
private String[] getStringArray(JSONArray jsonArray) throws JSONException {_x000D_
if (jsonArray != null) {_x000D_
String[] stringsArray = new String[jsonArray.length()];_x000D_
for (int i = 0; i < jsonArray.length(); i++) {_x000D_
stringsArray[i] = jsonArray.getString(i);_x000D_
}_x000D_
return stringsArray;_x000D_
} else_x000D_
return null;_x000D_
}
_x000D_
ObservableCollection Caveat
Mentioned above (Said Roohullah Allem)
What makes the ObservableCollection class unique is that this class supports an event named CollectionChanged.
Keep this in mind...If you adding a large number of items to an ObservableCollection
the UI will also update that many times. This can really gum up or freeze your UI.
A work around would be to create a new list, add all the items then set your property to the new list. This hits the UI once. Again...this is for adding a large number of items.
Try this :
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
$("#target").text(splitText);
});
</script>
<body>
<a id="target" href = test.html></a>
</body>
</html>
ASP.NET build manager is building the website by going through the folders alphabetically, and for each folder it figures out it dependencies and builds the dependencies first and then the selected folder.
In this case the problematic folder which is ~/Controls, is selected to be built at the beginning, from yet an unknown reason, it builds some of the controls there as a separate assembly instead of inside the same assembly as other controls (seems to be connected to the fact that some controls are dependent on other controls in the same folder).
Then the next folder which is built (~/File-Center/Control) is dependent on the root folder ~/ which is dependent on ~/Controls, so the folder ~/Controls is being built again only this time the controls which were separated to their own assembly are now joined to the same assembly as other controls with the separated assembly still being referenced.
So at this point 2 assembly (at least) have the same controls and the build fails.
Although we still don't know why this happened, we were able to work around it by changing the Controls folder name to ZControls, this way it is not built before ~/File-Center/Control, only after and this way it is built as it should.
Instead of converting each date, you can use the following code:
long difference = (sDt4.getTime() - sDt3.getTime()) / 1000;
System.out.println(difference);
And then see that the result is:
1
As I discovered from this similar post (ignorecase in AWK), on old versions of awk (such as on vanilla Mac OS X), you may need to use 'tolower($0) ~ /pattern/'
.
IGNORECASE
or (?i)
or /pattern/i
will either generate an error or return true for every line.
This is exactly what ajax is for. See here:
Basically, you ajax/test.php and put the returned HTML code to the element which has the result id.
$('#result').load('ajax/test.php');
Of course, you will need to put the functionality which takes time to a new php file (or call the old one with a GET parameter which will activate that functionality only).
You can Use sender argument
@IBAction func TickToeButtonClick(sender: AnyObject) {
sender.setTitle("my text here", forState: .normal)
}
There are multiple ways of doing that you can use either place
or grid
or even the pack
method.
Sample code:
from tkinter import *
root = Tk()
l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.
To place a widget to on basis of columns and rows , use the grid method:
but = Button(root, text="hello" )
but.grid(row=0, column=1)
This should work
function updatePostID(val)
{
document.getElementById('PostID').value = val;
//and probably call document.forms[0].submit();
}
Then have a hidden field or other control for the PostID
@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)
In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse
var jsonArrayString = @"
[
{
""country"": ""India"",
""city"": ""Mall Road, Gurgaon"",
},
{
""country"": ""India"",
""city"": ""Mall Road, Kanpur"",
}
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());
I used (this is a unix environment) :
export SBT_OPTS="$SBT_OPTS -Dhttp.proxyHost=myproxy-Dhttp.proxyPort=myport"
This did not work for my setup :
export JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyHost=myproxy-Dhttp.proxyPort=myport"
In sbt.sh file :
JAVA_OPTS environment variable, if unset uses "$java_opts"
SBT_OPTS environment variable, if unset uses "$default_sbt_opts"
But apparently SBT_OPTS is used instead of JAVA_OPTS
You need to bind handleCustomerClick
:
class Customers extends Component {
constructor() {
super();
this.handleCustomerClick = this.handleCustomerClick(this)
}
Building on @Waterscroll's response, if you want to use async and await in node 8+:
const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';
async function toRun() {
try {
const files = await readdir(directory);
const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
return Promise.all(unlinkPromises);
} catch(err) {
console.log(err);
}
}
toRun();
It depends on what you need to do. You can use replace
since you want to replace the value:
select replace(email, '.com', '.org')
from yourtable
Then to UPDATE
your table with the new ending, then you would use:
update yourtable
set email = replace(email, '.com', '.org')
You can also expand on this by checking the last 4 characters of the email value:
update yourtable
set email = replace(email, '.com', '.org')
where right(email, 4) = '.com'
However, the issue with replace()
is that .com
can be will in other locations in the email not just the last one. So you might want to use substring()
the following way:
update yourtable
set email = substring(email, 1, len(email) -4)+'.org'
where right(email, 4) = '.com';
Using substring()
will return the start of the email value, without the final .com
and then you concatenate the .org
to the end. This prevents the replacement of .com
elsewhere in the string.
Alternatively you could use stuff()
, which allows you to do both deleting and inserting at the same time:
update yourtable
set email = stuff(email, len(email) - 3, 4, '.org')
where right(email, 4) = '.com';
This will delete 4 characters at the position of the third character before the last one (which is the starting position of the final .com
) and insert .org
instead.
See SQL Fiddle with Demo for this method as well.
// **For multiple permission you can use this code :**
// **First:**
//Write down in onCreate method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST);
}
//**Second:**
//Write down in a activity.
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.GONE);
Intent i = new Intent(SplashActivity.this,
HomeActivity.class);
startActivity(i);
finish();
}
}, SPLASH_DISPLAY_LENGTH);
} else {
finish();
}
return;
}
}
CORRECTION: Please vote for Peter Štibraný's answer - it is more correct and complete!
A "JSESSIONID" is the unique id of the http session - see the javadoc here. There, you'll find the following sentence
Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.
So when you first hit a site, a new session is created and bound to the SevletContext. If you deploy multiple applications, the session is not shared.
You can also invalidate the current session and therefore create a new one. e.g. when switching from http to https (after login), it is a very good idea, to create a new session.
Hope, this answers your question.
You need to remove the
min-height:440px;
to
height:440px;
and then add
overflow: auto;
property to the class of the required div
$mylabel.text( $mylabel.text().replace('-', '') );
Since text()
gets the value, and text( "someValue" )
sets the value, you just place one inside the other.
Would be the equivalent of doing:
var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );
EDIT:
I hope I understood the question correctly. I'm assuming $mylabel
is referencing a DOM element in a jQuery object, and the string is in the content of the element.
If the string is in some other variable not part of the DOM, then you would likely want to call the .replace()
function against that variable before you insert it into the DOM.
Like this:
var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );
or a more verbose version:
var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );
Regarding whether the stack is implemented in the hardware, this Wikipedia article might help.
Some processors families, such as the x86, have special instructions for manipulating the stack of the currently executing thread. Other processor families, including PowerPC and MIPS, do not have explicit stack support, but instead rely on convention and delegate stack management to the operating system's Application Binary Interface (ABI).
That article and the others it links to might be useful to get a feel for stack usage in processors.
I'd like to add another use case for an internal struct
/class
and its usability. An inner struct
is often used to declare a data only member of a class that packs together relevant information and as such we can enclose it all in a struct
instead of loose data members lying around.
The inner struct
/class
is but a data only compartment, ie it has no functions (except maybe constructors).
#include <iostream>
class E
{
// E functions..
public:
struct X
{
int v;
// X variables..
} x;
// E variables..
};
int main()
{
E e;
e.x.v = 9;
std::cout << e.x.v << '\n';
E e2{5};
std::cout << e2.x.v << '\n';
// You can instantiate an X outside E like so:
//E::X xOut{24};
//std::cout << xOut.v << '\n';
// But you shouldn't want to in this scenario.
// X is only a data member (containing other data members)
// for use only inside the internal operations of E
// just like the other E's data members
}
This practice is widely used in graphics, where the inner struct
will be sent as a Constant Buffer to HLSL.
But I find it neat and useful in many cases.
Excluding node_modules from current directory
node_modules
Excluding node_modules in any immediate subdirectories
*/node_modules
Here is the official docs
This is an online/offline solution and very easy to convert. SCSS to CSS converter
All the random methods end up calling random.random()
so the best way is to call it directly:
[int(1000*random.random()) for i in xrange(10000)]
For example,
random.randint
calls random.randrange
.random.randrange
has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n)
.NumPy is much faster still of course.
use this style
<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
<item name="android:homeAsUpIndicator">@drawable/back_button_image</item>
</style>
The reason for using dictionaries in the first place is performance. Although it is correct that you can use named vectors and lists for the task the issue is that they are becoming quite slow and memory hungry with more data.
Yet what many people don't know is that R has indeed an inbuilt dictionary data structure: environments with the option hash = TRUE
See the following example for how to make it work:
# vectorize assign, get and exists for convenience
assign_hash <- Vectorize(assign, vectorize.args = c("x", "value"))
get_hash <- Vectorize(get, vectorize.args = "x")
exists_hash <- Vectorize(exists, vectorize.args = "x")
# keys and values
key<- c("tic", "tac", "toe")
value <- c(1, 22, 333)
# initialize hash
hash = new.env(hash = TRUE, parent = emptyenv(), size = 100L)
# assign values to keys
assign_hash(key, value, hash)
## tic tac toe
## 1 22 333
# get values for keys
get_hash(c("toe", "tic"), hash)
## toe tic
## 333 1
# alternatively:
mget(c("toe", "tic"), hash)
## $toe
## [1] 333
##
## $tic
## [1] 1
# show all keys
ls(hash)
## [1] "tac" "tic" "toe"
# show all keys with values
get_hash(ls(hash), hash)
## tac tic toe
## 22 1 333
# remove key-value pairs
rm(list = c("toe", "tic"), envir = hash)
get_hash(ls(hash), hash)
## tac
## 22
# check if keys are in hash
exists_hash(c("tac", "nothere"), hash)
## tac nothere
## TRUE FALSE
# for single keys this is also possible:
# show value for single key
hash[["tac"]]
## [1] 22
# create new key-value pair
hash[["test"]] <- 1234
get_hash(ls(hash), hash)
## tac test
## 22 1234
# update single value
hash[["test"]] <- 54321
get_hash(ls(hash), hash)
## tac test
## 22 54321
Edit: On the basis of this answer I wrote a blog post with some more context: http://blog.ephorie.de/hash-me-if-you-can
arr = ["I", "do", "love", "JavaScript", "and", "I", "also", "do", "love", "Java"];_x000D_
_x000D_
uniqueArr = [... new Set(arr)];_x000D_
_x000D_
// or_x000D_
_x000D_
reallyUniqueArr = arr.filter((item, pos, ar) => ar.indexOf(item) === pos)_x000D_
_x000D_
console.log(`${uniqueArr}\n${reallyUniqueArr}`)
_x000D_
Following
$(document).ready(function() {
});
can be replaced
$(window).bind("load", function() {
// insert your code here
});
There is once more way which i'm using to increase the page load time.
$(document).ready(function() {
$(window).load(function() {
//insert all your ajax callback code here.
//Which will run only after page is fully loaded in background.
});
});
How are you doing the compiling and linking? You'll need to specify both files, something like:
gcc testpoint.c point.c
...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main
. You'll need/want to eliminate one (undoubtedly the one in point.c).
In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make
to do the work. In this case you'd have something like this:
OBJS=testpoint.o point.o
testpoint.exe: $(OBJS)
gcc $(OJBS)
The first is just a macro for the names of the object files. You get it expanded with $(OBJS)
. The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.
Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:
.c.o:
$(CC) -c $(CFLAGS) $<
This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc
) and allows you to specify any flags you care about in a macro named CFLAGS
(e.g., CFLAGS=-O3
to turn on optimization) and $<
is a special macro that expands to the name of the source file.
You typically store this in a file named Makefile
, and to build your program, you just type make
at the command line. It implicitly looks for a file named Makefile
, and runs whatever rules it contains.
The good point of this is that make
automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).
Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.
sudo apt-get install docker # DO NOT do this
is a different library on ubuntu.
Use sudo apt-get install docker-ce
to install the correct docker.
I would use itertools.chain
- this will also cater for > 1 element in each sublist:
from itertools import chain
list(chain.from_iterable([[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]))
Outer Div must set its position
to relative
or fixed
, and the Inner Div must set its position
to absolute
, top
and left
to 50%
and apply a transform: translate(-50%, -50%)
.
div.cn {_x000D_
position: relative;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background: gray;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
div.inner {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
-webkit-transform: translate(-50%, -50%); _x000D_
transform: translate(-50%, -50%); _x000D_
background: red;_x000D_
_x000D_
}
_x000D_
<div class="cn">_x000D_
<div class="inner">_x000D_
test_x000D_
</div>_x000D_
</div>
_x000D_
Tested in:
JSON.stringify
takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>
tag to get newlines to show.
txtarea = new JTextArea();
txtarea.setRows(25);
txtarea.setColumns(25);
txtarea.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane (txtarea);
panel2.add(scroll); //Object of Jpanel
Above given lines automatically shows you both horizontal & vertical Scrollbars..
You can also try:
{
"dateProp": { $gt: new Date('06/15/2016').getTime() }
}
I had the same exception and I was excluding javassist
because of its issue with powermock
. Then I was adding it again as below but it was not working:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
<scope>test</scope>
</dependency>
Finally I found out that I have to remove <scope>test</scope>
from javassist
dependency. Hope it helps someone.
I have created a custom regex to deal with names:
I have tried these types of names and found working perfect
My RegEx looks like this:
^([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?)
MVC4 Model:
[RegularExpression("^([a-zA-Z]{2,}\\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\\s?([a-zA-Z]{1,})?)", ErrorMessage = "Valid Charactors include (A-Z) (a-z) (' space -)") ]
Please note the double \\
for escape characters
For those of you that are new to RegEx I thought I'd include a explanation.
^ // start of line
[a-zA-Z]{2,} // will except a name with at least two characters
\s // will look for white space between name and surname
[a-zA-Z]{1,} // needs at least 1 Character
\'?-? // possibility of **'** or **-** for double barreled and hyphenated surnames
[a-zA-Z]{2,} // will except a name with at least two characters
\s? // possibility of another whitespace
([a-zA-Z]{1,})? // possibility of a second surname
You can use ESCAPE
:
WHERE columnName LIKE '%\%%' ESCAPE '\'
I had this problem with getting "command not found" after install but I was installed into /usr/local as described in the solution above.
My problem seemed to be caused by me running the install with sudo. I did the following.
What helped me... changing sendmail parameters from -bs to -t.
'sendmail' => '/your/sendmail/path -t',
I also ran into this issue just now while messing with laravel.
I am using wampserver for windows and had to copy the /bin/apache/apacheversion/bin/php.ini file to /bin/php/phpversion/php.ini
Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp
Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:
I hope that helps
According to Bootstrap 4 docs:
Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript.
E.g:
$('#idOfMyModal').on('shown.bs.modal', function () {
$('input:first').trigger('focus')
});
Link.
you can add produces = "text/plain;charset=UTF-8" to RequestMapping
@RequestMapping(value = "/rest/create/document", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String create(Document document, HttpServletRespone respone) throws UnsupportedEncodingException {
Document newDocument = DocumentService.create(Document);
return jsonSerializer.serialize(newDocument);
}
Simplest way for me:
from urlextract import URLExtract
from requests import get
url = "sample.com/samplepage/"
req = requests.get(url)
text = req.text
# or if you already have the html source:
# text = "This is html for ex <a href='http://google.com/'>Google</a> <a href='http://yahoo.com/'>Yahoo</a>"
text = text.replace(' ', '').replace('=','')
extractor = URLExtract()
print(extractor.find_urls(text))
output:
['http://google.com/', 'http://yahoo.com/']
What is a DLL?
Dynamic Link Libraries (DLL)s are like EXEs but they are not directly executable. They are similar to .so files in Linux/Unix. That is to say, DLLs are MS's implementation of shared libraries.
DLLs are so much like an EXE that the file format itself is the same. Both EXE and DLLs are based on the Portable Executable (PE) file format. DLLs can also contain COM components and .NET libraries.
What does a DLL contain?
A DLL contains functions, classes, variables, UIs and resources (such as icons, images, files, ...) that an EXE, or other DLL uses.
Types of libraries:
On virtually all operating systems, there are 2 types of libraries. Static libraries and dynamic libraries. In windows the file extensions are as follows: Static libraries (.lib) and dynamic libraries (.dll). The main difference is that static libraries are linked to the executable at compile time; whereas dynamic linked libraries are not linked until run-time.
More on static and dynamic libraries:
You don't normally see static libraries though on your computer, because a static library is embedded directly inside of a module (EXE or DLL). A dynamic library is a stand-alone file.
A DLL can be changed at any time and is only loaded at runtime when an EXE explicitly loads the DLL. A static library cannot be changed once it is compiled within the EXE. A DLL can be updated individually without updating the EXE itself.
Loading a DLL:
A program loads a DLL at startup, via the Win32 API LoadLibrary, or when it is a dependency of another DLL. A program uses the GetProcAddress to load a function or LoadResource to load a resource.
Further reading:
Please check MSDN or Wikipedia for further reading. Also the sources of this answer.
Usually this is when you have a POST form which needs to take a file upload as data... this will tell the server how it will encode the data transferred, in such case it won't get encoded because it will just transfer and upload the files to the server, Like for example when uploading an image or a pdf
Just because you have a project inside the workspace directory doesn't mean Eclipse opens it or even sees it automatically. You must use File - Import - General - Import existing project into workspace to have your project in Eclipse.
For me the error was caused by wrong type hint of url string. I used:
export class TodoService {
apiUrl: String = 'https://jsonplaceholder.typicode.com/todos' // wrong uppercase String
constructor(private httpClient: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.httpClient.get<Todo[]>(this.apiUrl)
}
}
where I should have used
export class TodoService {
apiUrl: string = 'https://jsonplaceholder.typicode.com/todos' // lowercase string!
constructor(private httpClient: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.httpClient.get<Todo[]>(this.apiUrl)
}
}
In Kotlin, you can do:
ContextCompat.getColor(requireContext(), R.color.stage_hls_fallback_snackbar)
if requireContext() is accessible from where you are calling the function. I was getting an error when trying
ContextCompat.getColor(context, R.color.stage_hls_fallback_snackbar)
foreach($_POST as $key=>$value)
{
if(empty(trim($value))
echo "$key input required of value ";
}
The ISO C99 standard specifies that these macros must only be defined if explicitly requested.
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
... now PRIu64 will work
Sometimes uninstalling the app for all users helps. Go to Application list in settings go to your app or scroll till the end of the list, then uninstall it. Hope this helps
To get the definition of the SQL codes, the easiest way is to use db2 cli!
at the unix or dos command prompt, just type
db2 "? SQL302"
this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)
hope this helped.
Go to http://getbootstrap.com/customize/ and toggle just what you want from the BS3 framework and then click "Compile and Download" and you'll get the CSS and JS that you chose.
Open up the CSS and remove all but the grid. They include some normalize stuff too. And you'll need to adjust all the styles on your site to box-sizing: border-box - http://www.w3schools.com/cssref/css3_pr_box-sizing.asp
Yes there is. The preferred syntax is to favor str.format
over the deprecated %
operator.
print "First number is {} and second number is {}".format(first, second)
You'll see the message Cannot GET /
if you don't specify which page it is that you're trying to get, in other words if your URL is something like http://localhost:8180
. Make sure you enter a page name, e.g. http://localhost:8180/index.html
.
Actually you just need to tell doctrine who's your repository class, if you don't, doctrine uses default repo instead of yours.
@ORM\Entity(repositoryClass="Company\NameOfBundle\Repository\NameOfRepository")
StackFrame caller = (new System.Diagnostics.StackTrace()).GetFrame(1);
string methodName = caller.GetMethod().Name;
will be enough, I think.
One thing that i didn't see in other answers is To clarify another answers that there is a difference between returning std::unique_ptr that has been created within a function, and one that has been given to that function.
The example could be like this:
class Test
{int i;};
std::unique_ptr<Test> foo1()
{
std::unique_ptr<Test> res(new Test);
return res;
}
std::unique_ptr<Test> foo2(std::unique_ptr<Test>&& t)
{
// return t; // this will produce an error!
return std::move(t);
}
//...
auto test1=foo1();
auto test2=foo2(std::unique_ptr<Test>(new Test));
I had a similar use case during testing hibernate event listeners which are only called on commit.
The solution was to wrap the code to be persistent into another method annotated with REQUIRES_NEW
. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.
Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.
There are different regex engines but I think most of them will work with this:
apple|banana
I cleaned up SimpleAES (above) for my use. Fixed convoluted encrypt/decrypt methods; separated methods for encoding byte buffers, strings, and URL-friendly strings; made use of existing libraries for URL encoding.
The code is small, simpler, faster and the output is more concise. For instance, [email protected]
produces:
SimpleAES: "096114178117140150104121138042115022037019164188092040214235183167012211175176167001017163166152"
SimplerAES: "YHKydYyWaHmKKnMWJROkvFwo1uu3pwzTr7CnARGjppg%3d"
Code:
public class SimplerAES
{
private static byte[] key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 });
// a hardcoded IV should not be used for production AES-CBC code
// IVs should be unpredictable per ciphertext
private static byte[] vector = __Replace_Me_({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 221, 112, 79, 32, 114, 156 });
private ICryptoTransform encryptor, decryptor;
private UTF8Encoding encoder;
public SimplerAES()
{
RijndaelManaged rm = new RijndaelManaged();
encryptor = rm.CreateEncryptor(key, vector);
decryptor = rm.CreateDecryptor(key, vector);
encoder = new UTF8Encoding();
}
public string Encrypt(string unencrypted)
{
return Convert.ToBase64String(Encrypt(encoder.GetBytes(unencrypted)));
}
public string Decrypt(string encrypted)
{
return encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));
}
public byte[] Encrypt(byte[] buffer)
{
return Transform(buffer, encryptor);
}
public byte[] Decrypt(byte[] buffer)
{
return Transform(buffer, decryptor);
}
protected byte[] Transform(byte[] buffer, ICryptoTransform transform)
{
MemoryStream stream = new MemoryStream();
using (CryptoStream cs = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
return stream.ToArray();
}
}
your code would be
a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [a[1],a[5],a[7]]
print(ind_pos)
you get [88, 85, 16]
Found Promise.prototype.catch()
examples on MDN below very helpful.
(The accepted answer mentions then(null, onErrorHandler)
which is basically the same as catch(onErrorHandler)
.)
Using and chaining the catch method
var p1 = new Promise(function(resolve, reject) { resolve('Success'); }); p1.then(function(value) { console.log(value); // "Success!" throw 'oh, no!'; }).catch(function(e) { console.log(e); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('Not fired due to the catch'); }); // The following behaves the same as above p1.then(function(value) { console.log(value); // "Success!" return Promise.reject('oh, no!'); }).catch(function(e) { console.log(e); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('Not fired due to the catch'); });
Gotchas when throwing errors
// Throwing an error will call the catch method most of the time var p1 = new Promise(function(resolve, reject) { throw 'Uh-oh!'; }); p1.catch(function(e) { console.log(e); // "Uh-oh!" }); // Errors thrown inside asynchronous functions will act like uncaught errors var p2 = new Promise(function(resolve, reject) { setTimeout(function() { throw 'Uncaught Exception!'; }, 1000); }); p2.catch(function(e) { console.log(e); // This is never called }); // Errors thrown after resolve is called will be silenced var p3 = new Promise(function(resolve, reject) { resolve(); throw 'Silenced Exception!'; }); p3.catch(function(e) { console.log(e); // This is never called });
If it is resolved
//Create a promise which would not call onReject var p1 = Promise.resolve("calling next"); var p2 = p1.catch(function (reason) { //This is never called console.log("catch p1!"); console.log(reason); }); p2.then(function (value) { console.log("next promise's onFulfilled"); /* next promise's onFulfilled */ console.log(value); /* calling next */ }, function (reason) { console.log("next promise's onRejected"); console.log(reason); });
ToString("X2") prints the input in Hexadecimal
You can use [(ngModel)]
, but you'll need to update your value
to [value]
otherwise the value is evaluating as a string. It would look like this:
<label>This rule is true if:</label>
<label class="form-check-inline">
<input class="form-check-input" type="radio" name="mode" [value]="true" [(ngModel)]="rule.mode">
</label>
<label class="form-check-inline">
<input class="form-check-input" type="radio" name="mode" [value]="false" [(ngModel)]="rule.mode">
</label>
If rule.mode
is true, then that radio is selected. If it's false, then the other.
The difference really comes down to the value
. value="true"
really evaluates to the string 'true', whereas [value]="true"
evaluates to the boolean true.
Very common problem in android
It can be broken down into 3 Pieces
1 ) start Activity B (Happens in Activity A)
2 ) Set requested data (Happens in activity B)
3 ) Receive requested data (Happens in activity A)
1) startActivity B
Intent i = new Intent(A.this, B.class);
startActivity(i);
2) Set requested data
In this part, you decide whether you want to send data back or not when a particular event occurs.
Eg: In activity B there is an EditText and two buttons b1, b2.
Clicking on Button b1 sends data back to activity A
Clicking on Button b2 does not send any data.
Sending data
b1......clickListener
{
Intent resultIntent = new Intent();
resultIntent.putExtra("Your_key","Your_value");
setResult(RES_CODE_A,resultIntent);
finish();
}
Not sending data
b2......clickListener
{
setResult(RES_CODE_B,new Intent());
finish();
}
user clicks back button
By default, the result is set with Activity.RESULT_CANCEL response code
3) Retrieve result
For that override onActivityResult method
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RES_CODE_A) {
// b1 was clicked
String x = data.getStringExtra("RES_CODE_A");
}
else if(resultCode == RES_CODE_B){
// b2 was clicked
}
else{
// back button clicked
}
}
First of all you should know which statements are affected by the automatic semicolon insertion (also known as ASI for brevity):
var
statementdo-while
statementcontinue
statementbreak
statementreturn
statementthrow
statementThe concrete rules of ASI, are described in the specification §11.9.1 Rules of Automatic Semicolon Insertion
Three cases are described:
LineTerminator
.}
e.g.:
{ 1
2 } 3
is transformed to
{ 1
;2 ;} 3;
The NumericLiteral
1
meets the first condition, the following token is a line terminator.
The 2
meets the second condition, the following token is }
.
e.g.:
a = b
++c
is transformed to:
a = b;
++c;
Restricted productions:
UpdateExpression :
LeftHandSideExpression [no LineTerminator here] ++
LeftHandSideExpression [no LineTerminator here] --
ContinueStatement :
continue ;
continue [no LineTerminator here] LabelIdentifier ;
BreakStatement :
break ;
break [no LineTerminator here] LabelIdentifier ;
ReturnStatement :
return ;
return [no LineTerminator here] Expression ;
ThrowStatement :
throw [no LineTerminator here] Expression ;
ArrowFunction :
ArrowParameters [no LineTerminator here] => ConciseBody
YieldExpression :
yield [no LineTerminator here] * AssignmentExpression
yield [no LineTerminator here] AssignmentExpression
The classic example, with the ReturnStatement
:
return
"something";
is transformed to
return;
"something";
You can use this table date_formats for converting your date to different formats. My shortest code:
func getDayOfWeek(today: String) -> Int{
let formatter:NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let todayDate = formatter.dateFromString(today)
formatter.dateFormat = "e" // "eeee" -> Friday
let weekDay = formatter.stringFromDate(todayDate!)
return Int(weekDay)!
}
getDayOfWeek("2015-12-18") // 6
For something like $x from chrome command line api (to select multiple elements) try:
var xpath = function(xpathToExecute){
var result = [];
var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ ){
result.push( nodesSnapshot.snapshotItem(i) );
}
return result;
}
This MDN overview helped: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript
The only way to use custom fonts is through the source code.
Just remember that Android runs on devices with very limited resources and fonts might require a good amount of RAM. The built-in Droid fonts are specially made and, if you note, have many characters and decorations missing.
If for some reason you don't want to use the plugin, then here's the script you can use to copy the resources to your android studio project:
echo "..:: Copying resources ::.."
echo "Enter folder:"
read srcFolder
echo "Enter filename with extension:"
read srcFile
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-xxxhdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-xxxhdpi/"$srcFile"/
echo "xxxhdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-xxhdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-xxhdpi/"$srcFile"/
echo "xxhdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-xhdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-xhdpi/"$srcFile"/
echo "xhdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-hdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-hdpi/"$srcFile"/
echo "hdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-mdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-mdpi/"$srcFile"/
echo "mdpi copied"
This can happen due to too many connection same time or many chat at same time. Also it can happen due too many session.
The best way to sort out this issue is restart MySQL.
service mysqld restart
or
service mysql restart
or
/etc/init.d/mysqld restart
So the problem with a lot of these solutions is you're assuming the window appears instantly (nothing happens instantly, and things happen significantly less instantly in IE). Also you're assuming that there will only be one window prior to clicking the element, which is not always the case. Also IE will not return the window handles in a predictable order. So I would do the following.
public String clickAndSwitchWindow(WebElement elementToClick, Duration
timeToWaitForWindowToAppear) {
Set<String> priorHandles = _driver.getWindowHandles();
elementToClick.click();
try {
new WebDriverWait(_driver,
timeToWaitForWindowToAppear.getSeconds()).until(
d -> {
Set<String> newHandles = d.getWindowHandles();
if (newHandles.size() > priorHandles.size()) {
for (String newHandle : newHandles) {
if (!priorHandles.contains(newHandle)) {
d.switchTo().window(newHandle);
return true;
}
}
return false;
} else {
return false;
}
});
} catch (Exception e) {
Logging.log_AndFail("Encountered error while switching to new window after clicking element " + elementToClick.toString()
+ " seeing error: \n" + e.getMessage());
}
return _driver.getWindowHandle();
}
You can consider using a UI confirmation.
With yesnopopup.bat
@echo off
for /f "tokens=* delims=" %%# in ('yesnopopup.bat') do (
set "result=%%#"
)
if /i result==no (
echo user rejected the script
exit /b 1
)
echo continue
rem --- other commands --
the user will see the following and depending on the choice the script will continue:
with absolutely the same script you can use also iexpYNbutton.bat which will produce similar popup.
With buttons.bat you can try the following script:
@echo off
for /f "tokens=* delims=" %%# in ('buttons.bat "Yep!" "Nope!" ') do (
set "result=%%#"
)
if /i result==2 (
echo user rejected the script
exit /b 1
)
echo continue
rem --- other commands --
and the user will see:
for (var i = 0; i < 10; i = i + 2) {
// code here
}?
So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.
In test.jsp
Create a javascript
<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to
Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.
To do that i would highly recommendation to use session!
So what you want to do is in your servlet:
session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);
than in the test.jsp
<%
session.setMaxInactiveInterval(2);
%>
<script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
if (Msg != "null") {
function alertName(){
alert("Form has been submitted");
}
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
So everytime you submit that form a session will be pass on! If session is not null the function will run!
With Shell.Application you can emulate the way explorer.exe zips files and folders The script is called zipjs.bat:
:: unzip content of a zip to given folder.content of the zip will be not preserved (-keep no).Destination will be not overwritten (-force no)
call zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep no -force no
:: lists content of a zip file and full paths will be printed (-flat yes)
call zipjs.bat list -source C:\myZip.zip\inZipDir -flat yes
:: lists content of a zip file and the content will be list as a tree (-flat no)
call zipjs.bat list -source C:\myZip.zip -flat no
:: prints uncompressed size in bytes
zipjs.bat getSize -source C:\myZip.zip
:: zips content of folder without the folder itself
call zipjs.bat zipDirItems -source C:\myDir\ -destination C:\MyZip.zip -keep yes -force no
:: zips file or a folder (with the folder itslelf)
call zipjs.bat zipItem -source C:\myDir\myFile.txt -destination C:\MyZip.zip -keep yes -force no
:: unzips only part of the zip with given path inside
call zipjs.bat unZipItem -source C:\myDir\myZip.zip\InzipDir\InzipFile -destination C:\OtherDir -keep no -force yes
call zipjs.bat unZipItem -source C:\myDir\myZip.zip\InzipDir -destination C:\OtherDir
:: adds content to a zip file
call zipjs.bat addToZip -source C:\some_file -destination C:\myDir\myZip.zip\InzipDir -keep no
call zipjs.bat addToZip -source C:\some_file -destination C:\myDir\myZip.zip
Makecab is the default compressing tool coming with windows. Though it can use different compression algorithms (including zip) file format is always a .cab
file. With some extensions it can be used on linux machines too.
compressing a file:
makecab file.txt "file.cab"
Compressing an entire folder needs a little bit more work. Here a directory is compressed with cabDir.bat:
call cabDir.bat ./myDir compressedDir.cab
Uncompressing is rather easy with expand
command:
EXPAND cabfile -F:* .
More hackier way is by creating self-extracting executable with extrac32 command:
copy /b "%windir%\system32\extrac32.exe"+"mycab.cab" "expandable.exe"
call expandable.exe
With the build 17063 of windows we have the tar command:
::compress directory
tar -cvf archive.tar c:\my_dir
::extract to dir
tar -xvf archive.tar.gz -C c:\data
.net (and powershell) offers a lot of ways to compress and uncompress files. The most straightforward is with gzip stream. The script is called gzipjs.bat:
::zip
call gzipjs.bat -c my.file my.zip
::unzip
call gzipjs.bat -u my.zip my.file
My Solution for this problem not using any STL methods but only C++ string's own methods is as following:
void processString(string &s) {
if ( s.empty() ) return;
//delete leading and trailing spaces of the input string
int notSpaceStartPos = 0, notSpaceEndPos = s.length() - 1;
while ( s[notSpaceStartPos] == ' ' ) ++notSpaceStartPos;
while ( s[notSpaceEndPos] == ' ' ) --notSpaceEndPos;
if ( notSpaceStartPos > notSpaceEndPos ) { s = ""; return; }
s = s.substr(notSpaceStartPos, notSpaceEndPos - notSpaceStartPos + 1);
//reduce multiple spaces between two words to a single space
string temp;
for ( int i = 0; i < s.length(); i++ ) {
if ( i > 0 && s[i] == ' ' && s[i-1] == ' ' ) continue;
temp.push_back(s[i]);
}
s = temp;
}
I have used this method to pass a LeetCode problem Reverse Words in a String
I got this error when I only updated the jquery library without updating the jqueryui library in parallel. I was using jquery 1.8.3 with jqueryui 1.9.0. However, when I updated jquery 1.8.3 to 1.9.1 I got the above error. When I commented out the offending .close
method lines, it then threw an error about not finding .browser
in the jquery library which was deprecated in jquery 1.8.3 and removed from jquery 1.9.1. So bascially, the jquery 1.9.1 library was not compatible with the jquery ui 1.9.0 library despite the jquery ui download page saying it works with jquery 1.6+. Essentially, there are unreported bugs when trying to use differing versions of the two. If you use the jquery version that comes bundled with the jqueryui download, I'm sure you'll be fine, but it's when you start using different versions that you off the beaten path and get errors like this. So, in summary, this error is from mis-matched versions (in my case anyway).
First Fragment Sending String To Next Fragment
public class MainActivity extends AppCompatActivity {
private Button Add;
private EditText edt;
FragmentManager fragmentManager;
FragClass1 fragClass1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Add= (Button) findViewById(R.id.BtnNext);
edt= (EditText) findViewById(R.id.editText);
Add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragClass1=new FragClass1();
Bundle bundle=new Bundle();
fragmentManager=getSupportFragmentManager();
fragClass1.setArguments(bundle);
bundle.putString("hello",edt.getText().toString());
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.activity_main,fragClass1,"");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
}
Next Fragment to fetch the string.
public class FragClass1 extends Fragment {
EditText showFrag1;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.lay_frag1,null);
showFrag1= (EditText) view.findViewById(R.id.edtText);
Bundle bundle=getArguments();
String a=getArguments().getString("hello");//Use This or The Below Commented Code
showFrag1.setText(a);
//showFrag1.setText(String.valueOf(bundle.getString("hello")));
return view;
}
}
I used Frame Layout easy to use.
Don't Forget to Add Background color or else fragment will overlap.
This is for First Fragment.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/colorPrimary"
tools:context="com.example.sumedh.fragmentpractice1.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/BtnNext"/>
</FrameLayout>
Xml for Next Fragment.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="@color/colorAccent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtText"/>
</LinearLayout>
You can use
$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);
or define auto-size:
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
Make Sure in left panel App review tab selected (Your app is currently live and available to the public.) tab is ON and App status is GREEN
Happy Programming
I made a quick project in visual studio 2008 for a .net 3.5 C# windows form application and was able to create the following code. I found events for both the enter and leave methods.
In the InitializeComponent() function. I added the event handler using the Visual Studio designer.
this.button1.MouseLeave += new System.EventHandler( this.button1_MouseLeave );
this.button1.MouseEnter += new System.EventHandler( this.button1_MouseEnter );
In the button event handler methods set the background images.
/// <summary>
/// Handles the MouseEnter event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_MouseEnter( object sender, EventArgs e )
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
/// <summary>
/// Handles the MouseLeave event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_MouseLeave( object sender, EventArgs e )
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
}
In EF 6.2 this works perfectly, sending the delete directly to the database without first loading the entities:
context.Widgets.Where(predicate).Delete();
With a fixed predicate it's quite straightforward:
context.Widgets.Where(w => w.WidgetId == widgetId).Delete();
And if you need a dynamic predicate have a look at LINQKit (Nuget package available), something like this works fine in my case:
Expression<Func<Widget, bool>> predicate = PredicateBuilder.New<Widget>(x => x.UserID == userID);
if (somePropertyValue != null)
{
predicate = predicate.And(w => w.SomeProperty == somePropertyValue);
}
context.Widgets.Where(predicate).Delete();
This might be a better fix for some people.
$(".menu_link").click(function(){
// show menu code
});
$(".menu_link").mouseleave(function(){
//hide menu code, you may add a timer for 3 seconds before code to be run
});
I know mouseleave does not only mean a click outside, it also means leaving that element's area.
Once the menu itself is inside the menu_link
element then the menu itself should not be a problem to click on or move on.
There are quite a few working answers here, but I found this the easiest. This command will open up an editor, where you can just replace pick
with squash
in order to remove/merge them into one
git rebase -i HEAD~4
where, 4
is the number of commits you want to squash into one. This is explained here as well.
in terminal do:
sudo mysql -u root -p
enter the password.
select user from mysql.user;
now delete the user 'the_username'
DROP USER the_unername;
replace 'the_username' with the user that you want to delete.
It's quite an old question, but in case it could be useful for anyone, starting from a combination of good responses found here, I've ended using this pattern:
pattern="([^\s][A-z0-9À-ž\s]+)"
It will require at least two characters, making sure it does not start with an empty space but allowing spaces between words, and also allowing special characters such as a, ó, ä, ö
.
There is a pure CSS solution that the other answers have missed.
The "content:" property is mostly used to insert text content into an element, but can also be used to insert image content.
.my-div:before {
content: url("image.png");
}
This will cause the div to resize its height to the actual pixel size of the image. To resize the width too, add:
.my-div {
display: inline-block;
}
You have to create one Context Class.
public class Context {
private final static Context instance = new Context();
public static Context getInstance() {
return instance;
}
private Connection con;
public void setConnection(Connection con)
{
this.con=con;
}
public Connection getConnection() {
return con;
}
private TabRoughController tabRough;
public void setTabRough(TabRoughController tabRough) {
this.tabRough=tabRough;
}
public TabRoughController getTabRough() {
return tabRough;
}
}
You have to just set instance of controller in initialization using
Context.getInstance().setTabRough(this);
and you can use it from your whole application just using
TabRoughController cont=Context.getInstance().getTabRough();
Now you can pass parameter to any controller from whole application.
You can use
window.clipboardData.getData('Text')
to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard
Removes everything between &
and ;
which all such symbols have. if you juts want to get rid of them.
text.replace(/&.*;/g,'');
It means "a python object", i.e. not one of the builtin scalar types supported by numpy.
np.array([object()]).dtype
=> dtype('O')
I had the same problem and figured it out from your comments, but thought I would add the reason I caused the error to occur (for other beginners).
I had opened and edited .bash_profile using the open command in Terminal, which opened it in Text Editor. I typed in an addition to .bash_profile and it used improper quote characters. I opened .bash_profile in Atom and fixed up the error. I also associated the file with Atom for future editing.
str1.toLowerCase().contains(str2.toLowerCase())
Here is a quickly hacked up version of this using SVG I just did. Works well for me on my iPhone. Also works in a desktop browser using normal mouse events.
It's been a while, but last time I had something similar:
ROLLBACK TRAN
or trying to
COMMIT
what had allready been done free'd everything up so I was able to clear things out and start again.
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
The Bootstrap 3 documentation talks about this in the CSS documentation tab in the section labelled "Requires custom widths", which states:
Inputs, selects, and textareas are 100% wide by default in Bootstrap. To use the inline form, you'll have to set a width on the form controls used within.
If you use your browser and Firebug or Chrome tools to suppress or reduce the "width" style, you should see things line up they way you want. Clearly you can then create the appropriate CSS to fix the issue.
However, I find it odd that I need to do this at all. I couldn't help but feel this manipulation was both annoying and in the long term, error prone. Ultimately, I used a dummy class and some JS to globally shim all my inline inputs. It was small number of cases, so not much of a concern.
Nonetheless, I too would love to hear from someone who has the "right" solution, and could eliminate my shim/hack.
Hope this helps, and props to you for not blowing a gasket at all the people that ignored your request as a Bootstrap 3 concern.
I am maintaining one flag in shared pref which indicates whether gcm token sent to server or not. In Splash screen every time I am calling one method sendDevicetokenToServer. This method checks if user id is not empty and gcm send status then send token to server.
public static void sendRegistrationToServer(final Context context) {
if(Common.getBooleanPerf(context,Constants.isTokenSentToServer,false) ||
Common.getStringPref(context,Constants.userId,"").isEmpty()){
return;
}
String token = FirebaseInstanceId.getInstance().getToken();
String userId = Common.getUserId(context);
if(!userId.isEmpty()) {
HashMap<String, Object> reqJson = new HashMap<>();
reqJson.put("deviceToken", token);
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<JsonElement> call = apiService.updateDeviceToken(reqJson,Common.getUserId(context),Common.getAccessToken(context));
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> serverResponse) {
try {
JsonElement jsonElement = serverResponse.body();
JSONObject response = new JSONObject(jsonElement.toString());
if(context == null ){
return;
}
if(response.getString(Constants.statusCode).equalsIgnoreCase(Constants.responseStatusSuccess)) {
Common.saveBooleanPref(context,Constants.isTokenSentToServer,true);
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable throwable) {
Log.d("", "RetroFit2.0 :getAppVersion: " + "eroorrrrrrrrrrrr");
Log.e("eroooooooorr", throwable.toString());
}
});
}
}
In MyFirebaseInstanceIDService class
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
Common.saveBooleanPref(this,Constants.isTokenSentToServer,false);
Common.sendRegistrationToServer(this);
FirebaseMessaging.getInstance().subscribeToTopic("bloodRequest");
}
The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.
Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.
If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/
is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/
or http://s3-external-1.amazonaws.com/bucket/
.¹
The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].
S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com
. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.
If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.
However... the two endpoints do not offer the same functionality.
Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.
Choose the correct type of endpoint (REST or web site) for your application:
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff
¹ s3-external-1.amazonaws.com
has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com
. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2
had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1
so s3-external-2
appears to have no purpose except backwards-compatibility.
You can use HTML5 pattern attribute to do this:
<form>
<input type='text' pattern='[A-Za-z\\s]*'/>
</form>
If the user enters an input that conflicts with the pattern, it will show an error dialogue automatically.
break
and continue
breaks the readability for the reader, although it's often useful.
Not as much as "goto" concept, but almost.
Besides, if you take some new languages like Scala (inspired by Java and functional programming languages like Ocaml), you will notice that break
and continue
simply disappeared.
Especially in functional programming, this style of code is avoided:
Why scala doesn't support break and continue?
To sum up: break
and continue
are widely used in Java for an imperative style, but for any coders that used to practice functional programming, it might be.. weird.
I had the same problem like you. Here's my error code.
@Component
public class GetExprsAndEnvId {
@Value("hello")
private String Mysecret;
public GetExprsAndEnvId() {
System.out.println("construct");
}
public void print(){
System.out.println(this.Mysecret);
}
public String getMysecret() {
return Mysecret;
}
public void setMysecret(String mysecret) {
Mysecret = mysecret;
}
}
This is no problem like this, but we need to use it like this:
@Autowired
private GetExprsAndEnvId getExprsAndEnvId;
not like this:
getExprsAndEnvId = new GetExprsAndEnvId();
Here, the field annotated with @Value is null because Spring doesn't know about the copy of GetExprsAndEnvId that is created with new and didn't know to how to inject values in it.
when your add permission in manifest then in eclipse go to project and clic
k on clean project
.row {
letter-spacing: -.31em;
word-spacing: -.43em;
}
.col-md-4 {
float: none;
display: inline-block;
vertical-align: middle;
}
Note: .col-md-4 could be any grid column, its just an example here.
Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:
using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
if (stream != null)
{
stream.ReadTimeout = Timeout.Infinite;
using (var reader = new StreamReader(stream, Encoding.UTF8, false))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line != String.Empty)
{
Console.WriteLine("Count {0}", count++);
}
Console.WriteLine(line);
}
}
}
}
Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.
If you are using Atlassian SourceTree app, you could use the reset option in the context menu.
PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp://
for protocol, e.g.
file_get_contents('ssh2.sftp://user:[email protected]:22/path/to/filename');
or - when also using the ssh2 extension
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
See http://php.net/manual/en/wrappers.ssh2.php
On a side note, there is also quite a bunch of questions about this topic already:
I made a nice helper class which converts an object with get methods to an array. It doesn't rely on properties, just methods.
So i have a the following review object which contain two methods:
Review
Comment
The script I wrote will transform it into an array with properties what looks like this:
{
amount_reviews: 21,
reviews: [
{
subject: "In een woord top 1!",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque laoreet lacus quis eros venenatis, sed tincidunt mi rhoncus. Aliquam ut pharetra diam, nec lobortis dolor."
},
{
subject: "En een zwembad 2!",
description: "Maecenas et aliquet mi, a interdum mauris. Donec in egestas sem. Sed feugiat commodo maximus. Pellentesque porta consectetur commodo. Duis at finibus urna."
},
{
subject: "In een woord top 3!",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque laoreet lacus quis eros venenatis, sed tincidunt mi rhoncus. Aliquam ut pharetra diam, nec lobortis dolor."
},
{
subject: "En een zwembad 4!",
description: "Maecenas et aliquet mi, a interdum mauris. Donec in egestas sem. Sed feugiat commodo maximus. Pellentesque porta consectetur commodo. Duis at finibus urna."
},
{
subject: "In een woord top 5!",
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque laoreet lacus quis eros venenatis, sed tincidunt mi rhoncus. Aliquam ut pharetra diam, nec lobortis dolor."
}
]}
Source: PHP Serializer which converts an object to an array that can be encoded to JSON.
All you have to do is wrap json_encode around the output.
Some information about the script:
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
Describe Formatted/Extended will show the data definition of the table in hive
hive> describe Formatted dbname.tablename;
For the iOS9, Apple made a radical decision with iOS 9, disabling all unsecured HTTP traffic from iOS apps, as a part of App Transport Security (ATS).
To simply disable ATS, you can follow this steps by open Info.plist, and add the following lines:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
see this article!
identify UNC par or local drive path by searching index of ":"
if its is UNC PATH you cam map UNC path
code to execute drive name is mapped drive name < UNC Mapped Drive or Local Drive>.
using System.IO;
private long GetTotalFreeSpace(string driveName)
{
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady && drive.Name == driveName)
{
return drive.TotalFreeSpace;
}
}
return -1;
}
unmap after you requirement done.
Unable to resolve host “”; No address associated with hostname
you must have to check below code here on your manifest :
<uses-permission android:name="android.permission.INTERNET" />
and most important at least for me:-
enabled wifi connection or internet connection on your mobile device
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert($(myContent).text());
That results in hello world. Does that answer your question?
http://jsfiddle.net/D2tEf/ for an example
I to use this type of declaration:
const identity: { <T>(arg: T): T } = (arg) => arg;
It allows defining additional props to your function if you ever need to and in some cases, it helps keeping the function body cleaner from the generic definition.
If you don't need the additional props (namespace sort of thing), it can be simplified to:
const identity: <T>(arg: T) => T = (arg) => arg;
The aptitude --download-only ...
approach only works if you have a debian distro with internet connection in your hands.
If you don't, I think it is better to run the following script on the disconnected debian machine:
apt-get --print-uris --yes install <my_package_name> | grep ^\' | cut -d\' -f2 >downloads.list
move the downloads.list file into a connected linux (or non linux) machine, and run:
wget --input-file myurilist
this downloads all your files into the current directory.After that you can copy them on an USB key and install in your disconnected debian machine.
credits: http://www.tuxradar.com/answers/517
PS I basically copied the blog post because it was not very readable, and in case the post will disappear.
you can identify your button from there name tag like below, You need to check like this in you controller
if (Request.Form["submit"] != null)
{
//Write your code here
}
else if (Request.Form["process"] != null)
{
//Write your code here
}
pandas.isnull()
(also pd.isna()
, in newer versions) checks for missing values in both numeric and string/object arrays. From the documentation, it checks for:
NaN in numeric arrays, None/NaN in object arrays
Quick example:
import pandas as pd
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
pd.isnull(s)
Out[9]:
0 False
1 True
2 False
dtype: bool
The idea of using numpy.nan
to represent missing values is something that pandas
introduced, which is why pandas
has the tools to deal with it.
Datetimes too (if you use pd.NaT
you won't need to specify the dtype)
In [24]: s = Series([Timestamp('20130101'),np.nan,Timestamp('20130102 9:30')],dtype='M8[ns]')
In [25]: s
Out[25]:
0 2013-01-01 00:00:00
1 NaT
2 2013-01-02 09:30:00
dtype: datetime64[ns]``
In [26]: pd.isnull(s)
Out[26]:
0 False
1 True
2 False
dtype: bool
By the way, for C-mode, I add (setq-default c-basic-offset 4)
to .emacs. See http://www.emacswiki.org/emacs/IndentingC for details.
In 2020 this is still not available in the Firebase SDK however it is available in Firebase Extensions (Beta) however it's pretty complex to setup and use...
A reasonable approach
Helpers... (create/delete seems redundant but is cheaper than onUpdate)
export const onCreateCounter = () => async (
change,
context
) => {
const collectionPath = change.ref.parent.path;
const statsDoc = db.doc("counters/" + collectionPath);
const countDoc = {};
countDoc["count"] = admin.firestore.FieldValue.increment(1);
await statsDoc.set(countDoc, { merge: true });
};
export const onDeleteCounter = () => async (
change,
context
) => {
const collectionPath = change.ref.parent.path;
const statsDoc = db.doc("counters/" + collectionPath);
const countDoc = {};
countDoc["count"] = admin.firestore.FieldValue.increment(-1);
await statsDoc.set(countDoc, { merge: true });
};
export interface CounterPath {
watch: string;
name: string;
}
Exported Firestore hooks
export const Counters: CounterPath[] = [
{
name: "count_buildings",
watch: "buildings/{id2}"
},
{
name: "count_buildings_subcollections",
watch: "buildings/{id2}/{id3}/{id4}"
}
];
Counters.forEach(item => {
exports[item.name + '_create'] = functions.firestore
.document(item.watch)
.onCreate(onCreateCounter());
exports[item.name + '_delete'] = functions.firestore
.document(item.watch)
.onDelete(onDeleteCounter());
});
In action
The building root collection and all sub collections will be tracked.
Here under the /counters/
root path
Now collection counts will update automatically and eventually! If you need a count, just use the collection path and prefix it with counters
.
const collectionPath = 'buildings/138faicnjasjoa89/buildingContacts';
const collectionCount = await db
.doc('counters/' + collectionPath)
.get()
.then(snap => snap.get('count'));
Limitations
As this approach uses a single database and document, it is limited to the Firestore constraint of 1 Update per Second for each counter. It will be eventually consistent, but in cases where large amounts of documents are added/removed the counter will lag behind the actual collection count.
A Pair class :
public class Pair<K, V> {
private final K element0;
private final V element1;
public static <K, V> Pair<K, V> createPair(K element0, V element1) {
return new Pair<K, V>(element0, element1);
}
public Pair(K element0, V element1) {
this.element0 = element0;
this.element1 = element1;
}
public K getElement0() {
return element0;
}
public V getElement1() {
return element1;
}
}
usage :
Pair<Integer, String> pair = Pair.createPair(1, "test");
pair.getElement0();
pair.getElement1();
Immutable, only a pair !
Interestingly enough, building on the answer from @olefevre, one can not only do 50/50 layouts with "invisible struts", but all sorts of layouts involving powers of two.
For example, here is a layout that cuts the width into four equal parts (actually three, with weights of 1, 1, 2):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<View
android:id="@+id/strut"
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:background="#000000" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/strut" >
<View
android:id="@+id/left_strut"
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_toLeftOf="@+id/strut"
android:layout_centerHorizontal="true"
android:background="#000000" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/left_strut"
android:text="Far Left" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/left_strut"
android:text="Near Left" />
</RelativeLayout>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/strut"
android:layout_alignParentRight="true"
android:text="Right" />
</RelativeLayout>
The fillOval
fits an oval inside a rectangle, with width=r, height = r
you get a circle.
If you want fillOval(x,y,r,r)
to draw a circle with the center at (x,y) you will have to displace the rectangle by half its width and half its height.
public void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
x = x-(r/2);
y = y-(r/2);
g.fillOval(x,y,r,r);
}
This will draw a circle with center at x,y