Make sure you have run the MongoDB's Service before you want to connect the console.
run and start the server:
$ sudo mongod
then:
$ mongo
...
>
You can use this code, this code is for AES-256-CBC or you can use it for other AES encryption. Key length error mainly comes in 256-bit encryption.
This error comes due to the encoding or charset name we pass in the SecretKeySpec. Suppose, in my case, I have a key length of 44, but I am not able to encrypt my text using this long key; Java throws me an error of invalid key length. Therefore I pass my key as a BASE64 in the function, and it converts my 44 length key in the 32 bytes, which is must for the 256-bit encryption.
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Base64;
public class Encrypt {
static byte [] arr = {1,2,3,4,5,6,7,8,9};
// static byte [] arr = new byte[16];
public static void main(String...args) {
try {
// System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
Base64.Decoder decoder = Base64.getDecoder();
// static byte [] arr = new byte[16];
Security.setProperty("crypto.policy", "unlimited");
String key = "Your key";
// System.out.println("-------" + key);
String value = "Hey, i am adnan";
String IV = "0123456789abcdef";
// System.out.println(value);
// log.info(value);
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
// IvParameterSpec iv = new IvParameterSpec(arr);
// System.out.println(key);
SecretKeySpec skeySpec = new SecretKeySpec(decoder.decode(key), "AES");
// System.out.println(skeySpec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// System.out.println("ddddddddd"+IV);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
// System.out.println(cipher.getIV());
byte[] encrypted = cipher.doFinal(value.getBytes());
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
System.out.println("encrypted string,,,,,,,,,,,,,,,,,,,: " + encryptedString);
// vars.put("input-1",encryptedString);
// log.info("beanshell");
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
You want "rbind".
b$b <- NA
new <- rbind(a, b)
rbind requires the data frames to have the same columns.
The first line adds column b to data frame b.
Results
> a <- data.frame(a=c(0,1,2), b=c(3,4,5), c=c(6,7,8))
> a
a b c
1 0 3 6
2 1 4 7
3 2 5 8
> b <- data.frame(a=c(9,10,11), c=c(12,13,14))
> b
a c
1 9 12
2 10 13
3 11 14
> b$b <- NA
> b
a c b
1 9 12 NA
2 10 13 NA
3 11 14 NA
> new <- rbind(a,b)
> new
a b c
1 0 3 6
2 1 4 7
3 2 5 8
4 9 NA 12
5 10 NA 13
6 11 NA 14
Just search
open_basedir =
in php.ini and disable it. That's the simplest solution to solve this issue.
Before Changes open_basedir =
After Changes ;open_basedir =
P.s - After changes don't forget to restart your server.
Enjoy ;)
print("\n".join(sys.path))
(The outer parentheses are included for Python 3 compatibility and are usually omitted in Python 2.)
The SET
command is TSQL specific - here's the PLSQL equivalent to what you posted:
v_date1 DATE := TO_DATE('03-AUG-2010', 'DD-MON-YYYY');
SELECT u.visualid
FROM USAGE u
WHERE u.usetime > v_date1;
There's also no need for prefixing variables with "@"; I tend to prefix variables with "v_" to distinguish between variables & columns/etc.
I used this code to convert all columns to numeric except the first one:
library(dplyr)
# check structure, row and column number with: glimpse(df)
# convert to numeric e.g. from 2nd column to 10th column
df <- df %>%
mutate_at(c(2:10), as.numeric)
In addition to the native versions, but you may want to try BitNami MAMP Stacks (disclaimer, I am one of the developers). They are completely free, all-in-one bundles of Apache, MySQL, PHP and a several other third-party libraries and utilities that are useful when developing locally. In particular, they are completely self-contained so you can have several one installed at the same time, with different versions of Apache and MySQL and they will not interfere with each other. You can get them from http://bitnami.org/stack/mampstack or directly from the Mac OS X app store https://itunes.apple.com/app/mamp-stack/id571310406
I'm surprised no one has mentioned the obvious bash
solution utilizing only while
and read
.
while read -n1 character; do
echo "$character"
done < <(echo -n "$words")
Note the use of echo -n
to avoid the extraneous newline at the end. printf
is another good option and may be more suitable for your particular needs. If you want to ignore whitespace then replace "$words"
with "${words// /}"
.
Another option is fold
. Please note however that it should never be fed into a for loop. Rather, use a while loop as follows:
while read char; do
echo "$char"
done < <(fold -w1 <<<"$words")
The primary benefit to using the external fold
command (of the coreutils package) would be brevity. You can feed it's output to another command such as xargs
(part of the findutils package) as follows:
fold -w1 <<<"$words" | xargs -I% -- echo %
You'll want to replace the echo
command used in the example above with the command you'd like to run against each character. Note that xargs
will discard whitespace by default. You can use -d '\n'
to disable that behavior.
I just tested fold
with some of the Asian characters and realized it doesn't have Unicode support. So while it is fine for ASCII needs, it won't work for everyone. In that case there are some alternatives.
I'd probably replace fold -w1
with an awk array:
awk 'BEGIN{FS=""} {for (i=1;i<=NF;i++) print $i}'
Or the grep
command mentioned in another answer:
grep -o .
FYI, I benchmarked the 3 aforementioned options. The first two were fast, nearly tying, with the fold loop slightly faster than the while loop. Unsurprisingly xargs
was the slowest... 75x slower.
Here is the (abbreviated) test code:
words=$(python -c 'from string import ascii_letters as l; print(l * 100)')
testrunner(){
for test in test_while_loop test_fold_loop test_fold_xargs test_awk_loop test_grep_loop; do
echo "$test"
(time for (( i=1; i<$((${1:-100} + 1)); i++ )); do "$test"; done >/dev/null) 2>&1 | sed '/^$/d'
echo
done
}
testrunner 100
Here are the results:
test_while_loop
real 0m5.821s
user 0m5.322s
sys 0m0.526s
test_fold_loop
real 0m6.051s
user 0m5.260s
sys 0m0.822s
test_fold_xargs
real 7m13.444s
user 0m24.531s
sys 6m44.704s
test_awk_loop
real 0m6.507s
user 0m5.858s
sys 0m0.788s
test_grep_loop
real 0m6.179s
user 0m5.409s
sys 0m0.921s
If you have more than one enviroment, you may add the following way in the angular.json
:
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your_project:build"
},
"configurations": {
"production": {
"browserTarget": "your_project:build:production"
},
"es5": {
"browserTarget": "your_project:build:es5"
},
"local": {
"browserTarget": "your_project:build:local",
"port": 4201
},
"uat": {
"browserTarget": "your_project:build:uat"
}
}
},
This way only the local points to another port.
In the HKEY_USERS\oneyouwanttoknow\
you can look at \Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
and it will reveal their profile paths. c:\users\whothisis\Desktop
, etc.
Use find
on the command line:
find /my/directory -name '*.js'
Complete working code would look like this:
<script>
$(document).ready(function(){
setInterval(function(){
$("#here").load(window.location.href + " #here" );
}, 3000);
});
</script>
<div id="here">dynamic content ?</div>
self reloading div container refreshing every 3 sec.
Check the document encoding.
I had this same problem. I develop on Windows XP using Notepad++ and WampServer to run Apache locally and all was fine. After uploading to hosting provider that uses Apache on Unix I got this error. I had no extra PHP tags or white-space from extra lines after the closing tag.
For me this was caused by the encoding of the text documents. I used the "Convert to UTF-8 without BOM" option in Notepad++(under Encoding tab) and reloaded to the web server. Problem fixed, no code/editing changes required.
If what your asking is to only show rows that have 1 link for them then you can use the following:
SELECT * FROM posted WHERE link NOT IN
(SELECT link FROM posted GROUP BY link HAVING COUNT(LINK) > 1)
Again this is assuming that you want to cut out anything that has a duplicate link.
I am answering this old question just because it still shows up in google queries and I think one optimal answer is missing. Try this code: use ::before or ::after
If you choose to use a generic collection, such as List<MyObject>
instead of ArrayList
, you'll find that the List<MyObject>
will provide both generic and non-generic enumerators that you can use.
using System.Collections;
class MyObjects : IEnumerable<MyObject>
{
List<MyObject> mylist = new List<MyObject>();
public MyObject this[int index]
{
get { return mylist[index]; }
set { mylist.Insert(index, value); }
}
public IEnumerator<MyObject> GetEnumerator()
{
return mylist.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception
. For example:
public class FooException extends Exception {
public FooException() { super(); }
public FooException(String message) { super(message); }
public FooException(String message, Throwable cause) { super(message, cause); }
public FooException(Throwable cause) { super(cause); }
}
Methods that can potentially throw or propagate this exception must declare it:
public void calculate(int i) throws FooException, IOException;
... and code calling this method must either handle or propagate this exception (or both):
try {
int i = 5;
myObject.calculate(5);
} catch(FooException ex) {
// Print error and terminate application.
ex.printStackTrace();
System.exit(1);
} catch(IOException ex) {
// Rethrow as FooException.
throw new FooException(ex);
}
You'll notice in the above example that IOException
is caught and rethrown as FooException
. This is a common technique used to encapsulate exceptions (typically when implementing an API).
Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException
(which itself is a subclass of java.lang.Exception
):
public class FooRuntimeException extends RuntimeException {
...
}
Methods can throw or propagate FooRuntimeException
exception without declaring it; e.g.
public void calculate(int i) {
if (i < 0) {
throw new FooRuntimeException("i < 0: " + i);
}
}
Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.
The java.lang.Throwable
class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception
and java.lang.Error
are both subclasses of Throwable
. Anything that subclasses Throwable
may be thrown or caught. However, it is typically bad practice to catch or throw Error
as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError
). Likewise you should avoid catching Throwable
, which could result in you catching Error
s in addition to Exception
s.
If you don care about the range, the following expression will be useful to validate from 1.1.1.1 to 999.999.999.999
"[1-9]{1,3}\\.[1-9]{1,3}\\.[1-9]{1,3}\\.[1-9]{1,3}"
Another way to solve this problem is to install the missing libs that you need.
You can download the libs and see how to install here.
A SQL View is a virtual table, which is based on SQL SELECT query. A view references one or more existing database tables or other views. It is the snap shot of the database whereas a stored procedure is a group of Transact-SQL statements compiled into a single execution plan.
View is simple showcasing data stored in the database tables whereas a stored procedure is a group of statements that can be executed.
A view is faster as it displays data from the tables referenced whereas a store procedure executes sql statements.
Check this article : View vs Stored Procedures . Exactly what you are looking for
I feel your pain, I'm trying to do the same thing. In my case I just want to clear the user.
I've created a base controller class that all my controllers inherit from. In it I override OnAuthentication
and set the filterContext.HttpContext.User to null
That's the best I've managed to far...
public abstract class ApplicationController : Controller
{
...
protected override void OnAuthentication(AuthenticationContext filterContext)
{
base.OnAuthentication(filterContext);
if ( ... )
{
// You may find that modifying the
// filterContext.HttpContext.User
// here works as desired.
// In my case I just set it to null
filterContext.HttpContext.User = null;
}
}
...
}
If you are using NUnit, take a look at this post. Basically you'll need to have your app.config in the same directory as your .nunit file.
Tables and table cells don't use the min-height
property, setting their height
will be the min-height as tables will expand if the content stretches them.
To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):
import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"
evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)
in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script
. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.
You can also use .reverse(). It's a native array function
<div ng-repeat="friend in friends.reverse()">{{friend.name}}</div>
I recently wrote a post about how I've been doing it at Udacity for the last couple years. This method has meant we've been able to update Bootstrap whenever we wanted to without having merge conflicts, thrown out work, etc. etc.
The post goes more in depth with examples, but the basic idea is:
This does mean using LESS, and compiling it down to CSS before shipping it to the client (client-side LESS if finicky, and I generally avoid it) but it is EXTREMELY good for maintainability/upgradability, and getting LESS compilation is really really easy. The linked github code has an example using grunt, but there are many ways to achieve this -- even GUIs if that's your thing.
Using this solution, your example problem would look like:
When it comes time to upgrade your bootstrap, you just swap out the pristine bootstrap copy and everything will still work (if bootstrap makes breaking changes, you'll need to update your overrides, but you'd have to do that anyway)
Blog post with walk-through is here.
Code example on github is here.
Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).
requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)
Sends a GET request. Returns
Response
object.Parameters:
- url – URL for the new
Request
object.- params – (optional) Dictionary of GET Parameters to send with the
Request
.- headers – (optional) Dictionary of HTTP Headers to send with the
Request
.- cookies – (optional) CookieJar object to send with the
Request
.- auth – (optional) AuthObject to enable Basic HTTP Auth.
- timeout – (optional) Float describing the timeout of the request.
A good solution here for VSCode users, if a string breaking down into multiple lines causes the problem (I faced this when I had to test a long JWT token, and somehow using template literals didn't do the trick.)
break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return
to break the execution flow of the current function and return to the caller.
function loop() {
if (isPlaying) {
jet1.draw();
drawAllEnemies();
requestAnimFrame(loop);
if (game == 1) {
return
}
}
}
Note: This does not cover the logic behind the if condition or when to return from the method, for that we need to have more context regarding the drawAllEnemies
and requestAnimFrame
method as well as how game
value is updated
I'm not sure if this will still be useful to people, but with ES6 I have a way to do it that I find clean and useful.
class MyClass {
constructor ( arg1, arg2, arg3 )
myFunction1 () {...}
myFunction2 () {...}
myFunction3 () {...}
}
module.exports = ( arg1, arg2, arg3 ) => { return new MyClass( arg1,arg2,arg3 ) }
And then you get your expected behaviour.
var MyClass = require('/MyClass.js')( arg1, arg2, arg3 )
Example 1
>>> email= "[email protected]"
>>> email.split()
#OUTPUT
["[email protected]"]
Example 2
>>> email= "[email protected], [email protected]"
>>> email.split(',')
#OUTPUT
["[email protected]", "[email protected]"]
For arrays you can use:
Array.FindIndex<T>
:
int keyIndex = Array.FindIndex(words, w => w.IsKey);
For lists you can use List<T>.FindIndex
:
int keyIndex = words.FindIndex(w => w.IsKey);
You can also write a generic extension method that works for any Enumerable<T>
:
///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
int retVal = 0;
foreach (var item in items) {
if (predicate(item)) return retVal;
retVal++;
}
return -1;
}
And you can use LINQ as well:
int keyIndex = words
.Select((v, i) => new {Word = v, Index = i})
.FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;
If you want to easily know the screen density and size of an Android device, you can use this free app (no permission required): https://market.android.com/details?id=com.jotabout.screeninfo
I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.
You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:
function getContextPath() {
return "<%=request.getContextPath()%>";
}
It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.
At this point I agree with @BalusC to use EL:
function getContextPath() {
return "${pageContext.request.contextPath}";
}
or depending on the version of JSP fallback to JSTL:
function getContextPath() {
return "<c:out value="${pageContext.request.contextPath}" />";
}
Change the line where you print the output to:
printf("\nmaximum of %d and %d is = %d",a,b,c);
See the docs here
You can also use (focusout) event:
Use (eventName)
for while binding event to DOM, basically ()
is used for event binding. Also you can use ngModel
to get two way binding for your model
. With the help of ngModel
you can manipulate model
variable value inside your component
.
Do this in HTML file
<input type="text" [(ngModel)]="model" (focusout)="someMethodWithFocusOutEvent($event)">
And in your (component) .ts file
export class AppComponent {
model: any;
constructor(){ }
someMethodWithFocusOutEvent(){
console.log('Your method called');
// Do something here
}
}
I did quickly fix it by going into "Design View" of the main Table of same Form and putting underline (_) between any field names that had spaces. I am now able to use the built in filters without the annoying popup about syntax problems.
Code Snippet
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Excel.Application excelApp = null;
private void button1_Click(object sender, EventArgs e)
{
excelApp.get_Range("A1:A360,B1:E1", Type.Missing).Merge(Type.Missing);
}
private void Form1_Load(object sender, EventArgs e)
{
excelApp = Marshal.GetActiveObject("Excel.Application") as Excel.Application ;
}
}
Thanks
Use break;
to escape the first loop:
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
break;
}
If you want to also escape the second loop, you might need to use a flag and check in the out loop's guard:
boolean breakFlag = false;
while (!breakFlag)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
breakFlag = true;
break;
}
}
}
Or, if you want to just exit the function completely from within the nested loop, put in a return;
instead of a break;
.
But these aren't really considered best practices. You should find some way to add the necessary Boolean logic into your while
guards.
My problem was that I had a DNS entry for gitlab.example.com
to point to my load balancer. So when I tried command ssh [email protected]
I was really connecting to the wrong machine.
I made an entry in my ~/.ssh/config
file:
Host gitlab.example.com
Hostname 192.168.1.50
That wasted a lot of time...
this one worked for me
app.use(express.static(path.join(__dirname, 'public')));
app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/shopping-cart/javascripts',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/shopping-cart/stylesheets',express.static(path.join(__dirname, 'public/stylesheets')));
app.use('/user/stylesheets',express.static(path.join(__dirname, 'public/stylesheets')));
app.use('/user/javascripts',express.static(path.join(__dirname, 'public/javascripts')));
its not .val() if you want to get file /home/user/default.png it will get with .val() just default.png
BE CAREFUL with those other answers as they will not play properly with bodyParser if you're looking to also support json, urlencoded, etc. To get it to work with bodyParser you should condition your handler to only register on the Content-Type
header(s) you care about, just like bodyParser itself does.
To get the raw body content of a request with Content-Type: "text/plain"
into req.rawBody
you can do:
app.use(function(req, res, next) {
var contentType = req.headers['content-type'] || ''
, mime = contentType.split(';')[0];
if (mime != 'text/plain') {
return next();
}
var data = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.rawBody = data;
next();
});
});
We can get official code From the internet! Refer this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim
Running the following code before any other code will create trim() if it's not natively available.
if (!String.prototype.trim) { (function() { // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; String.prototype.trim = function() { return this.replace(rtrim, ''); }; })(); }
for more: I just found there is js project for supporting EcmaScript 5: https://github.com/es-shims/es5-shim by reading the source code, we can get more knowledge about trim.
defineProperties(StringPrototype, { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ trim: function trim() { if (typeof this === 'undefined' || this === null) { throw new TypeError("can't convert " + this + ' to object'); } return String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, ''); } }, hasTrimWhitespaceBug);
If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "Year dropdown shows last 20 years
" demo , and hit view source:
$("#restricting").datepicker({
yearRange: "-20:+0", // this is the option you're looking for
showOn: "both",
buttonImage: "templates/images/calendar.gif",
buttonImageOnly: true
});
You'll want to do the same (obviously changing -20
to -100
or something).
Just create an interface that extends DocumentListener and implements all DocumentListener methods:
@FunctionalInterface
public interface SimpleDocumentListener extends DocumentListener {
void update(DocumentEvent e);
@Override
default void insertUpdate(DocumentEvent e) {
update(e);
}
@Override
default void removeUpdate(DocumentEvent e) {
update(e);
}
@Override
default void changedUpdate(DocumentEvent e) {
update(e);
}
}
and then:
jTextField.getDocument().addDocumentListener(new SimpleDocumentListener() {
@Override
public void update(DocumentEvent e) {
// Your code here
}
});
or you can even use lambda expression:
jTextField.getDocument().addDocumentListener((SimpleDocumentListener) e -> {
// Your code here
});
WITH uniq AS (
SELECT DISTINCT posts.id as post_id
FROM posts
JOIN votes ON votes.post_id = posts.id
-- GROUP BY not needed anymore
-- GROUP BY posts.id
)
SELECT COUNT(*)
FROM uniq;
A more convenient way:
Create an executable script as mentioned above:
#!/bin/sh
cd /Applications/Adobe\ Flash\ Builder\ 4.6
open -n Adobe\ Flash\ Builder\ 4.6.app
In you current instance of Flashbuilder or Eclipse, add a new external tool configuration. This is the button next to the debug/run/profile buttons on your toolbar. In that dialog, click on "Program" and add a new one. Give it the name you want and in the "Location" field, put the path to the script from step 1:
/Users/username/bin/flashbuilder
You can stop at step 2, but I prefer adding a custom icon to the toolbar. I use a the Quick Launch plugin to do that:
After adding the plugin, go to "Run"->"Organize Quick Lauches" and add the external tool config from step 2. Then you can configure the icon for it.
After you save that, you'll see the icon in your toolbar. Now you can just click it every time you want a new Flashbuilder/Eclipse instance.
~Controller
namespace ListBindingTest.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
List<String> tmp = new List<String>();
tmp.Add("one");
tmp.Add("two");
tmp.Add("Three");
return View(tmp);
}
[HttpPost]
public ActionResult Send(IList<String> input)
{
return View(input);
}
}
}
~ Strongly Typed Index View
@model IList<String>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using(Html.BeginForm("Send", "Home", "POST"))
{
@Html.EditorFor(x => x)
<br />
<input type="submit" value="Send" />
}
</div>
</body>
</html>
~ Strongly Typed Send View
@model IList<String>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Send</title>
</head>
<body>
<div>
@foreach(var element in @Model)
{
@element
<br />
}
</div>
</body>
</html>
This is all that you had to do man, change his MyViewModel model to IList.
BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.
Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.
When writing datetime value to sql db
//Convert the time into UTC and build Timestamp object.
Timestamp ts = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")));
//use setTimestamp on preparedstatement
preparedStatement.setTimestamp(1, ts);
When reading the value back from DB into java,
Then, change it to your desired timezone. Here I am changing it to Toronto timezone.
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
Timestamp timestamp = resultSet.getTimestamp(1);
ZonedDateTime timeInUTC = timestamp.toLocalDateTime().atZone(ZoneId.of("UTC"));
LocalDateTime timeInToronto = LocalDateTime.ofInstant(timeInUTC.toInstant(), ZoneId.of("America/Toronto"));
when you click div with addproduct class one event is fired for that particular element, not five. you're doing something wrong in you code if event is fired 5 times.
Quick update to mid 2015:
You can use the Postgres Foreign Data interface, to store the files in more suitable database. For example put the files in a GridFS which is part of MongoDB. Then use https://github.com/EnterpriseDB/mongo_fdw to access it in Postgres.
That has the advantages, that you can access/read/write/backup it in Postrgres and MongoDB, depending on what gives you more flexiblity.
There are also foreign data wrappers for file systems: https://wiki.postgresql.org/wiki/Foreign_data_wrappers#File_Wrappers
As an example you can use this one: https://multicorn.readthedocs.org/en/latest/foreign-data-wrappers/fsfdw.html (see here for brief usage example)
That gives you the advantage of the consistency (all linked files are definitely there) and all the other ACIDs, while there are still on the actual file system, which means you can use any file system you want and the webserver can serve them directly (OS caching applies too).
Same error can raise by mixing: tabs + spaces.
with open('/foo', 'w') as f:
(spaces OR tab) print f <-- success
(spaces AND tab) print f <-- fail
Hierarchy of log4j logging levels are as follows in Highest to Lowest order :
TRACE log level provides highest logging which would be helpful to troubleshoot issues. DEBUG log level is also very useful to trouble shoot the issues.
You can also refer this link for more information about log levels : https://logging.apache.org/log4j/2.0/manual/architecture.html
If you are searching for haml then this is the answer for hidden field to set value to a hidden field like
%input#forum_id.hidden
In your jquery just convert the value to string and then append it using attr property in jquery. hope this also works in other languages also.
$('#forum_id').attr('val',forum_id.toString());
Use a server implementation to send messages to your client and use data type of messages rather than notification type of messages.
This will help you get a callback to onMessageReceived
irrespective if your app is in background or foreground and you can generate your custom notification then
From a performance point of view, in python3.X
[i[0] for i in a]
and list(zip(*a))[0]
are equivalentlist(map(operator.itemgetter(0), a))
Code
import timeit
iterations = 100000
init_time = timeit.timeit('''a = [(i, u'abc') for i in range(1000)]''', number=iterations)/iterations
print(timeit.timeit('''a = [(i, u'abc') for i in range(1000)]\nb = [i[0] for i in a]''', number=iterations)/iterations - init_time)
print(timeit.timeit('''a = [(i, u'abc') for i in range(1000)]\nb = list(zip(*a))[0]''', number=iterations)/iterations - init_time)
output
3.491014136001468e-05
3.422205176000717e-05
The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.
This explains the "strange results".
"Better" results can be obtained using the expressions below:
//*[text() = 'qwerty']
The above selects every element in the document that has at least one text-node child with value 'qwerty'.
//*[text() = 'qwerty' and not(text()[2])]
The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.
No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me
class line_details {
var $commission_one=array();
foreach($_SESSION['commission'] as $key=>$data){
$row= explode('-', $key);
$this->commission_one[$row['0']]= $row['1'];
}
}
First, you need to configure your computer to get a static IP from your router. Instructions for how to do this can be found: here
For example, let's say you picked the IP address 192.168.1.102. After the above step is completed, you should be able to get to the website on your local machine by going to both http://localhost and http://192.168.1.102, since your computer will now always have that IP address on your network.
If you look up your IP address (such as http://www.ip-adress.com/), the IP you see is actually the IP of your router. When your friend accesses your website, you'll give him this IP. However, you need to tell your router that when it gets a request for a webpage, forward that request to your server. This is done through port forwarding.
Two examples of how to do this can be found here and here, although the exact screens you see will vary depending on the manufacturer of your router (Google for exact instructions, if needed).
For the Linksys router I have, I enter http://192.168.1.1/, enter my username/password, Applications & Gaming tab > Port Range Forward. Enter the application name (whatever you want to call it), start port (80), end port (80), protocol (TCP), ip address (using the above example, you would enter 192.168.1.102, which is the static IP you assigned your server), and be sure to check to enable the forwarding. Restart your router and the changes should take effect.
Having done all that, your friend should now be able to access your webpage by going to his web browser on his machine and entering http://IP.address.of.your.computer (the same one you see when you go here ).
As mentioned earlier, the IP address assigned to you by your ISP will eventually change whether you sign offline or not. I strongly recommend using DynDns, which is absolutely free. You can choose a hostname at their domain (such as cuga.kicks-ass.net) and your friend can then always access your website by simply going to http://cuga.kicks-ass.net in his browser. Here is their site again: DynDns
I hope this helps.
Matter of style, but as Matt said, definitely consider marking constructors with default arguments which would allow implicit conversion as 'explicit' to avoid unintended automatic conversion. It's not a requirement (and may not be preferable if you're making a wrapper class which you want to implicitly convert to), but it can prevent errors.
I personally like defaults when appropriate, because I dislike repeated code. YMMV.
It's because of being too sure about what you (me) are doing!
On my machine there is IIS 7 installed but the required ASP.NET component (Control Panel->Programs->Turn On/Off->ASP.NET) was not.
So installing this solved the problem
You can mix C++ in with Objectiv-C (Objective C++). Write a C++ method in your Objective C++ class that simply calls [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)self.layer];
and call it from your C++.
I haven't tried it before my self, but give it a shot, and share the results with us.
I'm working on an app and face issue of killing my service by on app kill. I researched on google and found that I have to make it foreground. following is the code:
public class UpdateLocationAndPrayerTimes extends Service {
Context context;
@Override
public void onCreate() {
super.onCreate();
context = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
StartForground();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void StartForground() {
LocationChangeDetector locationChangeDetector = new LocationChangeDetector(context);
locationChangeDetector.getLatAndLong();
Notification notification = new NotificationCompat.Builder(this)
.setOngoing(false)
.setSmallIcon(android.R.color.transparent)
//.setSmallIcon(R.drawable.picture)
.build();
startForeground(101, notification);
}
}
hops that it may helps!!!!
The best practice is definitely to avoid loops or recursions in Matlab.
Between sum(A(:))
and sum(sum(A))
.
In my experience, arrays in Matlab seems to be stored in a continuous block in memory as stacked column vectors. So the shape of A does not quite matter in sum()
. (One can test reshape()
and check if reshaping is fast in Matlab. If it is, then we have a reason to believe that the shape of an array is not directly related to the way the data is stored and manipulated.)
As such, there is no reason sum(sum(A))
should be faster. It would be slower if Matlab actually creates a row vector recording the sum of each column of A first and then sum over the columns. But I think sum(sum(A))
is very wide-spread amongst users. It is likely that they hard-code sum(sum(A))
to be a single loop, the same to sum(A(:))
.
Below I offer some testing results. In each test, A=rand(size) and size is specified in the displayed texts.
First is using tic toc.
Size 100x100
sum(A(:))
Elapsed time is 0.000025 seconds.
sum(sum(A))
Elapsed time is 0.000018 seconds.
Size 10000x1
sum(A(:))
Elapsed time is 0.000014 seconds.
sum(A)
Elapsed time is 0.000013 seconds.
Size 1000x1000
sum(A(:))
Elapsed time is 0.001641 seconds.
sum(A)
Elapsed time is 0.001561 seconds.
Size 1000000
sum(A(:))
Elapsed time is 0.002439 seconds.
sum(A)
Elapsed time is 0.001697 seconds.
Size 10000x10000
sum(A(:))
Elapsed time is 0.148504 seconds.
sum(A)
Elapsed time is 0.155160 seconds.
Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.
Error in test27 (line 70)
A=rand(100000000,1);
Below is using cputime
Size 100x100
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 10000x1
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 1000x1000
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 1000000
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.
Error in test27_2 (line 70)
A=rand(100000000,1);
In my experience, both timers are only meaningful up to .1s. So if you have similar experience with Matlab timers, none of the tests can discern sum(A(:))
and sum(sum(A))
.
I tried the largest size allowed on my computer a few more times.
Size 10000x10000
sum(A(:))
Elapsed time is 0.151256 seconds.
sum(A)
Elapsed time is 0.143937 seconds.
Size 10000x10000
sum(A(:))
Elapsed time is 0.149802 seconds.
sum(A)
Elapsed time is 0.145227 seconds.
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.2808
The cputime for sum(sum(A)) in seconds is
0.312
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
They seem equivalent.
Either one is good. But sum(sum(A))
requires that you know the dimension of your array is 2.
SELECT CONVERT(varchar(11),getdate(),101) -- mm/dd/yyyy
SELECT CONVERT(varchar(11),getdate(),103) -- dd/mm/yyyy
Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST()
function to make it as an character expression because CHARINDEX()
works on character expression.
Also I think there is no need of OR condition.
select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0
then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end
EDIT:
select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end
See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp
I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice
and delete
for removing every 'c'
from the items
Array.
var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
items.splice(items.indexOf('c'), 1);
}
console.log(items); // ["a", "b", "d", "a", "b", "d"]
items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
delete items[items.indexOf('c')];
}
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
?
Maybe something like this:
SELECT count(*) FROM user_tab_columns WHERE table_name = 'FOO'
this will count number of columns in a the table FOO
You can also just
select count(*) from all_tab_columns where owner='BAR' and table_name='FOO';
where the owner is schema and note that Table Names are upper case
$.getJSON("http://jsonip.com?callback=?", function (data) {
alert("Your ip: " + data.ip);
});
suggestion here looks like a good candidate for this question as well
Performing click event on a disabled element? Javascript jQuery
jQuery('input#submit').click(function(e) {
if ( something ) {
return false;
}
});
Keep in mind that you probably shouldn't be using either one of those methods. Microsoft's Anti-Cross Site Scripting Library includes replacements for HttpUtility.UrlEncode
and HttpUtility.HtmlEncode
that are both more standards-compliant, and more secure. As a bonus, you get a JavaScriptEncode
method as well.
This is confusing for everyone when it comes IISExpress. There is nothing to read console messages. So for example, in the ASPCORE MVC apps it configures using appsettings.json which does nothing if you are using IISExpress.
For right now you can just add loggerFactory.AddDebug(LogLevel.Debug); in your Configure section and it will at least show you your logs in the Debug Output window.
Good news CORE 2.0 this will all be changing: https://github.com/aspnet/Announcements/issues/255
Output: 6 7
Reason: static variable is initialised only once (unlike auto variable) and further definition of static variable would be bypassed during runtime. And if it is not initialised manually, it is initialised by value 0 automatically. So,
void foo() {
static int x = 5; // assigns value of 5 only once
x++;
printf("%d", x);
}
int main() {
foo(); // x = 6
foo(); // x = 7
return 0;
}
In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click
on android:theme = "@style/AppTheme"
in the Android manifest file. It will open styles.xml
file where you can change the parent attribute of the style tag.
At parent=
in styles.xml
you can browse all available styles by using auto-complete inside the ""
. E.g. try parent="Theme."
with your cursor right after the .
and then pressing Ctrl + Space
.
You can also preview themes in the preview window in Android Studio.
in my case there was a copy or replace window for that particular file open and hence the unlink error. i closed it and there is no unlink error
yu have to install the correct version for your computer 32 or 63 bits thats all
I propose to use
SET time_zone = 'proper timezone';
being done once right after connect to database. and after this all timestamps will be converted automatically when selecting them.
Vanilla JS solution:
var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));
Note that dispatchEvent
doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).
So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional comments to warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for:
typeof document.body.dispatchEvent === 'function'
.
Above table is an employee salary table with salary1,salary2,salary3,salary4 as columns.Query below will return the max value out of four columns
select
(select Max(salval) from( values (max(salary1)),(max(salary2)),(max(salary3)),(max(Salary4)))alias(salval)) as largest_val
from EmployeeSalary
Running above query will give output as largest_val(10001)
Logic of above query is as below:
select Max(salvalue) from(values (10001),(5098),(6070),(7500))alias(salvalue)
output will be 10001
$("#closeLink").click(closeIt);
Let's say you want to call your function passing some args to it i.e., closeIt(1, false)
. Then, you should build an anonymous function and call closeIt
from it.
$("#closeLink").click(function() {
closeIt(1, false);
});
maybe you can try using
SELECT user_name
FROM user_master
WHERE upper(user_name) LIKE '%ME%'
Check out http://www.odata.org/
It defines the MERGE method, so in your case it would be something like this:
MERGE /customer/123
<customer>
<status>DISABLED</status>
</customer>
Only the status
property is updated and the other values are preserved.
You can use the init files. Check the MySQL official documentation on How to Reset the Root Password (including comments for alternative solutions).
So basically using init files, you can add any SQL queries that you need for fixing your access (such as GRAND
, CREATE
, FLUSH PRIVILEGES
, etc.) into init file (any file).
Here is my example of recovering root account:
echo "CREATE USER 'root'@'localhost' IDENTIFIED BY 'root';" > your_init_file.sql
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;" >> your_init_file.sql
echo "FLUSH PRIVILEGES;" >> your_init_file.sql
and after you've created your file, you can run:
killall mysqld
mysqld_safe --init-file=$PWD/your_init_file.sql
then to check if this worked, press Ctrl+Z and type: bg
to run the process from the foreground into the background, then verify your access by:
mysql -u root -proot
mysql> show grants;
+-------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' |
See also:
Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs
Yes, yes yes.
The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.
Use this icons with bootstrap (glyphicon):
<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>
http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h
http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h
To access the convert datatable value in Json method follow the below steps:
$.ajax({
type: "POST",
url: "/Services.asmx/YourMethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = $.parseJSON(data.d);
$.each(parsed, function (i, jsondata) {
$("#dividtodisplay").append("Title: " + jsondata.title + "<br/>" + "Latitude: " + jsondata.lat);
});
},
error: function (XHR, errStatus, errorThrown) {
var err = JSON.parse(XHR.responseText);
errorMessage = err.Message;
alert(errorMessage);
}
});
First you need to start karma server with
karma start
Then, you can use grep to filter a specific test or describe block:
karma run -- --grep=testDescriptionFilter
If you're concerned about server performance then look at capping the number of running sox processes. If the cap has been hit you can always cache the request and inform the user when it's finished in whichever way suits your application.
Alternatively, have the n worker scripts on other machines that pull requests from the db and call sox, and then push the resulting output file to where it needs to be.
Function declaration;
import os
def mkdir_p(filename):
try:
folder=os.path.dirname(filename)
if not os.path.exists(folder):
os.makedirs(folder)
return True
except:
return False
usage :
filename = "./download/80c16ee665c8/upload/backup/mysql/2014-12-22/adclient_sql_2014-12-22-13-38.sql.gz"
if (mkdir_p(filename):
print "Created dir :%s" % (os.path.dirname(filename))
just posting in case anyone else has the same error...
I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.
The solution was to make the function asynchronous
function functionName(args) {}
becomes
async function functionName(args) {}
This can happen if you miss adding the Top-level build file.
Just add build.gradle to top level.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.xx.y'
}
}
allprojects {
repositories {
mavenCentral()
}
}
The code is valid (i.e, will compile and execute) in both cases.
One of my lecturers at Uni told us that it is not desirable to have continue
, return
statements in any loop - for
or while
. The reason for this is that when examining the code, it is not not immediately clear whether the full length of the loop will be executed or the return
or continue
will take effect.
See Why is continue inside a loop a bad idea? for an example.
The key point to keep in mind is that for simple scenarios like this it doesn't (IMO) matter but when you have complex logic determining the return value, the code is 'generally' more readable if you have a single return statement instead of several.
With regards to the Garbage Collection - I have no idea why this would be an issue.
We don't have to reinvent the wheel. Just use a library to save the time and headache.
https://github.com/dankogai/js-base64 is good and I confirm it supports unicode very well.
Base64.encode('dankogai'); // ZGFua29nYWk=
Base64.encode('???'); // 5bCP6aO85by+
Base64.encodeURI('???'); // 5bCP6aO85by-
Base64.decode('ZGFua29nYWk='); // dankogai
Base64.decode('5bCP6aO85by+'); // ???
// note .decodeURI() is unnecessary since it accepts both flavors
Base64.decode('5bCP6aO85by-'); // ???
byte[] toByteArray(int value) {
return ByteBuffer.allocate(4).putInt(value).array();
}
byte[] toByteArray(int value) {
return new byte[] {
(byte)(value >> 24),
(byte)(value >> 16),
(byte)(value >> 8),
(byte)value };
}
int fromByteArray(byte[] bytes) {
return ByteBuffer.wrap(bytes).getInt();
}
// packing an array of 4 bytes to an int, big endian, minimal parentheses
// operator precedence: <<, &, |
// when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to right
int fromByteArray(byte[] bytes) {
return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}
// packing an array of 4 bytes to an int, big endian, clean code
int fromByteArray(byte[] bytes) {
return ((bytes[0] & 0xFF) << 24) |
((bytes[1] & 0xFF) << 16) |
((bytes[2] & 0xFF) << 8 ) |
((bytes[3] & 0xFF) << 0 );
}
When packing signed bytes into an int, each byte needs to be masked off because it is sign-extended to 32 bits (rather than zero-extended) due to the arithmetic promotion rule (described in JLS, Conversions and Promotions).
There's an interesting puzzle related to this described in Java Puzzlers ("A Big Delight in Every Byte") by Joshua Bloch and Neal Gafter . When comparing a byte value to an int value, the byte is sign-extended to an int and then this value is compared to the other int
byte[] bytes = (…)
if (bytes[0] == 0xFF) {
// dead code, bytes[0] is in the range [-128,127] and thus never equal to 255
}
Note that all numeric types are signed in Java with exception to char being a 16-bit unsigned integer type.
Check against any long running queries in your database.
Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)
You can use sql server profiler and filter on duration / reads to see which querys need optimization.
I also see you're probably keeping a global connection?
blnMainConnectionIsCreatedLocal
Let .net do the pooling for you and open / close your connection with a using statement.
Suggestions:
Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// do some stuff
} //conn disposed
As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.
Try:
-webkit-transition: all .2s linear, background-position 0;
This worked for me on something similar..
I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.
Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.
As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.
var album_text = [];
$("input[name='album_text[]']").each(function() {
var value = $(this).val();
if (value) {
album_text.push(value);
}
});
if (album_text.length === 0) {
$('#error_message').html("Error");
}
else {
//send data
}
Some notes on what you were doing and what I changed.
$(this)
is always a valid jQuery object so there's no reason to ever check if ($(this))
. It may not have any DOM objects inside it, but you can check that with $(this).length
if you need to, but that is not necessary here because the .each()
loop wouldn't run if there were no items so $(this)
inside your .each()
loop will always be something.[]
rather than new Array()
.if (value)
when value is expected to be a string will both protect from value == null
, value == undefined
and value == ""
so you don't have to do if (value && (value != ""))
. You can just do: if (value)
to check for all three empty conditions.if (album_text.length === 0)
will tell you if the array is empty as long as it is a valid, initialized array (which it is here).What are you trying to do with this selector $("input[name='album_text[]']")
?
Simple class to calculate rolling average and also rolling standard deviation:
#define _stdev(cnt, sum, ssq) sqrt((((double)(cnt))*ssq-pow((double)(sum),2)) / ((double)(cnt)*((double)(cnt)-1)))
class moving_average {
private:
boost::circular_buffer<int> *q;
double sum;
double ssq;
public:
moving_average(int n) {
sum=0;
ssq=0;
q = new boost::circular_buffer<int>(n);
}
~moving_average() {
delete q;
}
void push(double v) {
if (q->size() == q->capacity()) {
double t=q->front();
sum-=t;
ssq-=t*t;
q->pop_front();
}
q->push_back(v);
sum+=v;
ssq+=v*v;
}
double size() {
return q->size();
}
double mean() {
return sum/size();
}
double stdev() {
return _stdev(size(), sum, ssq);
}
};
Why not do a where IN a sub-select...
Pre-query into a temp table or something...
CREATE TABLE SomeTempTable AS
SELECT YourColumn
FROM SomeTable
WHERE UserPickedMultipleRecordsFromSomeListOrSomething
then...
SELECT * FROM OtherTable
WHERE YourColumn IN ( SELECT YourColumn FROM SomeTempTable )
In Linux, run file on the Eclipse executable, like this:
$ file /usr/bin/eclipse
eclipse: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped
You can use setCustomValidity
function when oninvalid
event occurs.
Like below:-
<input class="form-control" type="email" required=""
placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">
</input>
To clear the message once you start entering use oninput="setCustomValidity('')
attribute to clear the message.
<input class="form-control" type="email" required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>
One does not imply the other. For a language to be statically typed it means that the types of all variables are known or inferred at compile time.
A strongly typed language does not allow you to use one type as another. C is a weakly typed language and is a good example of what strongly typed languages don't allow. In C you can pass a data element of the wrong type and it will not complain. In strongly typed languages you cannot.
One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.
package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
Name string
Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
return candidate{name, 0} // enforce the default value here
}
Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.
There is no need to involve any image classes, you can simply call WebClient.DownloadFile
:
string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}
Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:
private static void DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Check that the remote file was found. The ContentType
// check is performed since a request for a non-existent
// image file might be redirected to a 404-page, which would
// yield the StatusCode "OK", even though the image was not
// found.
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
{
// if the remote file was found, download oit
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}
In brief, it makes a request for the file, verifies that the response code is one of OK
, Moved
or Redirect
and also that the ContentType
is an image. If those conditions are true, the file is downloaded.
To extend Rodrigo's solution a little - for requests that are executed frequently, you may only want to display the loading image if the request takes more than a minimum time interval, otherwise the image will be continually popping up and quickly disappearing
var loading = false;
$.ajaxSetup({
beforeSend: function () {
// Display loading icon if AJAX call takes >1 second
loading = true;
setTimeout(function () {
if (loading) {
// show loading image
}
}, 1000);
},
complete: function () {
loading = false;
// hide loading image
}
});
Based on Jon Skeet answer i've made a class that permits to do it easily at work:
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* <p>
* This permits to easily implement a failsafe implementation of the enums's valueOf
* Better use it inside the enum so that only one of this object instance exist for each enum...
* (a cache could solve this if needed)
* </p>
*
* <p>
* Basic usage exemple on an enum class called MyEnum:
*
* private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
* public static MyEnum failSafeValueOf(String enumName) {
* return FAIL_SAFE.valueOf(enumName);
* }
*
* </p>
*
* <p>
* You can also use it outside of the enum this way:
* FailSafeValueOf.create(MyEnum.class).valueOf("EnumName");
* </p>
*
* @author Sebastien Lorber <i>([email protected])</i>
*/
public class FailSafeValueOf<T extends Enum<T>> {
private final Map<String,T> nameToEnumMap;
private FailSafeValueOf(Class<T> enumClass) {
Map<String,T> map = Maps.newHashMap();
for ( T value : EnumSet.allOf(enumClass)) {
map.put( value.name() , value);
}
nameToEnumMap = ImmutableMap.copyOf(map);
}
/**
* Returns the value of the given enum element
* If the
* @param enumName
* @return
*/
public T valueOf(String enumName) {
return nameToEnumMap.get(enumName);
}
public static <U extends Enum<U>> FailSafeValueOf<U> create(Class<U> enumClass) {
return new FailSafeValueOf<U>(enumClass);
}
}
And the unit test:
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* @author Sebastien Lorber <i>([email protected])</i>
*/
public class FailSafeValueOfTest {
private enum MyEnum {
TOTO,
TATA,
;
private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
public static MyEnum failSafeValueOf(String enumName) {
return FAIL_SAFE.valueOf(enumName);
}
}
@Test
public void testInEnum() {
assertNotNull( MyEnum.failSafeValueOf("TOTO") );
assertNotNull( MyEnum.failSafeValueOf("TATA") );
assertNull( MyEnum.failSafeValueOf("TITI") );
}
@Test
public void testInApp() {
assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TOTO") );
assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TATA") );
assertNull( FailSafeValueOf.create(MyEnum.class).valueOf("TITI") );
}
}
Notice that i used Guava to make an ImmutableMap but actually you could use a normal map i think since the map is never returned...
For me it was the issue with the date. Updated it and the issue was resolved.
Allow read/write:
if request.time < timestamp.date(2020, 5, 21);
Edit: If you are still confused and unable to figure out what's the issue just have a look at the rules section in your firebase console.
Replace all commas with underscore in the column names
data.columns= data.columns.str.replace(' ','_',regex=True)
The message you're getting isn't an error; it's just letting you know that you're not using a Network Security Configuration. If you want to add one, take a look at this page on the Android Developers website: https://developer.android.com/training/articles/security-config.html.
Actually there is no way to do this through JavaScript, unless you use some external source. Even then, it might not be 100% correct.
The method below is exactly reproducible, so there's no need to run clone again if both sides were consistent, just run the script on the other side too.
git log -n1 --format=%H >.git/info/grafts
git filter-branch -f
rm .git/info/grafts
If you then want to clean it up, try this script:
http://sam.nipl.net/b/git-gc-all-ferocious
I wrote a script which "kills history" for each branch in the repository:
http://sam.nipl.net/b/git-kill-history
see also: http://sam.nipl.net/b/confirm
My problem was with Google Chrome cache. I tested this by running my web application on Firefox and I didn't got that error there. So then I decided trying emptying cache of Google Chrome and it worked.
Laravel 4.2
@SamMonk gave the best alternative, I followed his example and build the final piece of code
<select class="chosen-select" multiple="multiple" name="places[]" id="places">
@foreach($places as $place)
<option value="{{$place->id}}" @foreach($job->places as $p) @if($place->id == $p->id)selected="selected"@endif @endforeach>{{$place->name}}</option>
@endforeach
</select>
In my project I'm going to have many table relationships like this so I wrote an extension to keep it clean. To load it, put it in some configuration file like "app/start/global.php". I've created a file "macros.php" under "app/" directory and included it in the EOF of global.php
// app/start/global.php
require app_path().'/macros.php';
// macros.php
Form::macro("chosen", function($name, $defaults = array(), $selected = array(), $options = array()){
// For empty Input::old($name) session, $selected is an empty string
if(!$selected) $selected = array();
$opts = array(
'class' => 'chosen-select',
'id' => $name,
'name' => $name . '[]',
'multiple' => true
);
$options = array_merge($opts, $options);
$attributes = HTML::attributes($options);
// need an empty array to send if all values are unselected
$ret = '<input type="hidden" name="' . HTML::entities($name) . '[]">';
$ret .= '<select ' . $attributes . '>';
foreach($defaults as $def) {
$ret .= '<option value="' . $def->id . '"';
foreach($selected as $p) {
// session array or passed stdClass obj
$current = @$p->id ? $p->id: $p;
if($def->id == $current) {
$ret .= ' selected="selected"';
}
}
$ret .= '>' . HTML::entities($def->name) . '</option>';
}
$ret .= '</select>';
return $ret;
});
List without pre-selected items (create view)
{{ Form::chosen('places', $places, Input::old('places')) }}
Preselections (edit view)
{{ Form::chosen('places', $places, $job->places) }}
Complete usage
{{ Form::chosen('places', $places, $job->places, ['multiple': false, 'title': 'I\'m a selectbox', 'class': 'bootstrap_is_mainstream']) }}
also try to increase gradle version in your project's build.gradle. It helped me
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
Note, the localhost is a special string that FB allows here. If you didn't configure your debugging environment under localhost, you'll have to push it underneath that name as far as I can tell.
You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.
string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');
if (lnSpace > -1)
{
string lcFirst = lcStart.Substring(0, lnSpace);
string lcRest = lcStart.Substring(lnSpace + 1);
}
Not sure why but none of the above solution work for me. So sharing what worked:
public void readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
}
}
}
}
df[df.columns[i]]
where i
is the position/number of the column(starting from 0).
So, i = 0
is for the first column.
You can also get the last column using i = -1
It is now much easier to map the Caps Lock key to Esc with macOS Sierra.
Open System Preferences ? Keyboard.
Click the Modifier Keys button in the bottom right-hand corner.
Click the drop down box next to the hardware key that you’d like to remap, and select Escape.
Click OK and close System Preferences.
Here is the code sample for Creating a segue programmatically
:
class ViewController: UIViewController {
...
// 1. Define the Segue
private var commonSegue: UIStoryboardSegue!
...
override func viewDidLoad() {
...
// 2. Initialize the Segue
self.commonSegue = UIStoryboardSegue(identifier: "CommonSegue", source: ..., destination: ...) {
self.commonSegue.source.showDetailViewController(self.commonSegue.destination, sender: self)
}
...
}
...
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// 4. Prepare to perform the Segue
if self.commonSegue == segue {
...
}
...
}
...
func actionFunction() {
// 3. Perform the Segue
self.prepare(for: self.commonSegue, sender: self)
self.commonSegue.perform()
}
...
}
Looks like the problem is with Python 3.8. Use Python 3.7 instead. Steps I took to solve this.
Worked for me.
you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown
$("#dropdownid").val(); for value
$("#dropdownid").text(); for selected value
catch these into two variables and take it as inputs to ajax call for a php file
$.ajax
({
url:"callingphpfile.php",//url of fetching php
method:"POST", //type
data:"val1="+value+"&val2="+selectedtext,
success:function(data) //return the data
{
}
and in php you can get it as
if (isset($_POST["val1"])) {
$val1= $_POST["val1"] ;
}
if (isset($_POST["val2"])) {
$selectedtext= $_POST["val1"];
}
Is there a reason that you can't do this via Javascript? My advice would be to target the selectors with a universal rule (.foo
) and then parse back over to get the last foo with Javascript and set any additional styling you'll need.
Or as suggested by Stein, just add two classes if you can:
<div class="foo"></div>
<div class="foo last"></div>
.foo {}
.foo.last {}
A programatic way would be to do it in the component itself. I struggled three weeks on this issue, but gave up on angular docs and read the actual code that made routerlinkactive work and Thats about the best docs I can find.
import {
Component,AfterContentInit,OnDestroy, ViewChild,OnInit, ViewChildren, AfterViewInit, ElementRef, Renderer2, QueryList,NgZone,ApplicationRef
}
from '@angular/core';
import { Location } from '@angular/common';
import { Subscription } from 'rxjs';
import {
ActivatedRoute,ResolveStart,Event, Router,RouterEvent, NavigationEnd, UrlSegment
} from '@angular/router';
import { Observable } from "rxjs";
import * as $ from 'jquery';
import { pairwise, map } from 'rxjs/operators';
import { filter } from 'rxjs/operators';
import {PageHandleService} from '../pageHandling.service'
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements AfterContentInit,AfterViewInit,OnInit,OnDestroy{
public previousUrl: any;
private subscription: Subscription;
@ViewChild("superclass", { static: false } as any) superclass: ElementRef;
@ViewChildren("megaclass") megaclass: QueryList<ElementRef>;
constructor( private element: ElementRef, private renderer: Renderer2, private router: Router, private activatedRoute: ActivatedRoute, private location: Location, private pageHandleService: PageHandleService){
this.subscription = router.events.subscribe((s: Event) => {
if (s instanceof NavigationEnd) {
this.update();
}
});
}
ngOnInit(){
}
ngAfterViewInit() {
}
ngAfterContentInit(){
}
private update(): void {
if (!this.router.navigated || !this.superclass) return;
Promise.resolve().then(() => {
this.previousUrl = this.router.url
this.megaclass.toArray().forEach( (superclass) => {
var superclass = superclass
console.log( superclass.nativeElement.children[0].classList )
console.log( superclass.nativeElement.children )
if (this.previousUrl == superclass.nativeElement.getAttribute("routerLink")) {
this.renderer.addClass(superclass.nativeElement.children[0], "box")
console.log("add class")
} else {
this.renderer.removeClass(superclass.nativeElement.children[0], "box")
console.log("remove class")
}
});
})
//update is done
}
ngOnDestroy(): void { this.subscription.unsubscribe(); }
//class is done
}
Note:
For the programatic way, make sure to add the router-link and it takes a child element. If you want to change that, you need to get rid of the children on superclass.nativeElement
.
The following works as you would like in bash
and zsh
:
$ array=(pluto pippo)
$ delete=pluto
$ echo ${array[@]/$delete}
pippo
$ array=( "${array[@]/$delete}" ) #Quotes when working with strings
If need to delete more than one element:
...
$ delete=(pluto pippo)
for del in ${delete[@]}
do
array=("${array[@]/$del}") #Quotes when working with strings
done
Caveat
This technique actually removes prefixes matching $delete
from the elements, not necessarily whole elements.
Update
To really remove an exact item, you need to walk through the array, comparing the target to each element, and using unset
to delete an exact match.
array=(pluto pippo bob)
delete=(pippo)
for target in "${delete[@]}"; do
for i in "${!array[@]}"; do
if [[ ${array[i]} = $target ]]; then
unset 'array[i]'
fi
done
done
Note that if you do this, and one or more elements is removed, the indices will no longer be a continuous sequence of integers.
$ declare -p array
declare -a array=([0]="pluto" [2]="bob")
The simple fact is, arrays were not designed for use as mutable data structures. They are primarily used for storing lists of items in a single variable without needing to waste a character as a delimiter (e.g., to store a list of strings which can contain whitespace).
If gaps are a problem, then you need to rebuild the array to fill the gaps:
for i in "${!array[@]}"; do
new_array+=( "${array[i]}" )
done
array=("${new_array[@]}")
unset new_array
You have to check unique identifier column and you have to give a diff value to that particular field if you give the same value it will not work. It enforces uniqueness of the key.
Here is the code:
Insert into production.product
(Name,ProductNumber,MakeFlag,FinishedGoodsFlag,Color,SafetyStockLevel,ReorderPoint,StandardCost,ListPrice,Size
,SizeUnitMeasureCode,WeightUnitMeasureCode,Weight,DaysToManufacture,
ProductLine,
Class,
Style ,
ProductSubcategoryID
,ProductModelID
,SellStartDate
,SellEndDate
,DiscontinuedDate
,rowguid
,ModifiedDate
)
values ('LL lemon' ,'BC-1234',0,0,'blue',400,960,0.00,100.00,Null,Null,Null,null,1,null,null,null,null,null,'1998-06-01 00:00:00.000',null,null,'C4244F0C-ABCE-451B-A895-83C0E6D1F468','2004-03-11 10:01:36.827')
You've pretty much nailed it, however Mustache templates can also be compiled.
Mustache is missing helpers and the more advanced blocks because it strives to be logicless. Handlebars' custom helpers can be very useful, but often end up introducing logic into your templates.
Mustache has many different compilers (JavaScript, Ruby, Python, C, etc.). Handlebars began in JavaScript, now there are projects like django-handlebars, handlebars.java, handlebars-ruby, lightncandy (PHP), and handlebars-objc.
For Mysql You can use this Query
UPDATE table1 a, table2 b SET a.coloumn = b.coloumn WHERE a.id= b.id
#function call
read_names(names.txt)
#function def
def read_names(filename):
with open(filename, 'r') as fileopen:
name_list = [line.strip() for line in fileopen]
print (name_list)
Please follow the below snippet.. it works..
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xyz</groupId>
<artifactId>test</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>TestProject</name>
<description>Sample Project</description>
<dependencies>
<!-- mention your dependencies here -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<archive>
<manifest>
<mainClass>com.xyz.ABC.</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Please note, you have to provide the full classified class name (class name including package name without .java
or .class
) of main class inside <mainClass></mainClass>
tag.
A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively.
The key difference(noticed when reading the Spring Docs) between @Autowired
and @Inject
is that, @Autowired
has the 'required' attribute while the @Inject has no 'required' attribute.
As many people mentioned, it looks like you are looking in your JRE instead of the JDK for the tools.jar file.
I would also like to mention that on recent versions of the JDK, there is no more tools.jar file. I downloaded the most recent JDK as of today (JDK version 12) and I could not find any tools.jar. I had to download JDK version 8 (1.8.0) here https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html to get the tools.jar file. I downloaded that version, took the tools.jar file and put it into my recent version's lib folder.
To round out the possibilities, you can use writeLines()
with sink()
, if you want:
> sink("tempsink", type="output")
> writeLines("Hello\nWorld")
> sink()
> file.show("tempsink", delete.file=TRUE)
Hello
World
To me, it always seems most intuitive to use print()
, but if you do that the output won't be what you want:
...
> print("Hello\nWorld")
...
[1] "Hello\nWorld"
You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(
If you don't wrap the text node in a <span>
like @Jacob suggests, you could instead give the surrounding element padding
as opposed to margin
:
<p id="theParagraph">The text node!</p>
p#theParagraph
{
border: 1px solid red;
padding-bottom: 10px;
}
You also run into this issue when you are creating routine in a class module.
When you try to run the code externally, you get this error.
You can't assign macro to button to a member of a class module either.
If you try to run from within the code by pressing green play button you will also see the same error.
Either move the routine in to a regular module or create a new routine in a regular module that calls the class member.
JsonMappingException: out of START_ARRAY token
exception is thrown by Jackson object mapper as it's expecting an Object {}
whereas it found an Array [{}]
in response.
This can be solved by replacing Object
with Object[]
in the argument for geForObject("url",Object[].class)
.
References:
To make it more generic of keeping both columns in df1
and df2
:
import pyspark.sql.functions as F
# Keep all columns in either df1 or df2
def outter_union(df1, df2):
# Add missing columns to df1
left_df = df1
for column in set(df2.columns) - set(df1.columns):
left_df = left_df.withColumn(column, F.lit(None))
# Add missing columns to df2
right_df = df2
for column in set(df1.columns) - set(df2.columns):
right_df = right_df.withColumn(column, F.lit(None))
# Make sure columns are ordered the same
return left_df.union(right_df.select(left_df.columns))
There's a couple of ways you can do this. If the onchange
listener is a function set via the element.onchange
property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:
element.onchange();
If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener
/attachEvent
, you need to do a bit of feature detection to correctly fire the event:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
It matches p
elements with class some_class
that are directly under a div
.
You should use labels attribute inside plot function and the value of this attribute should be the vector containing the values that you want for each point to have.
Uncheck Always Show Toolbar in Full Screen
in View
menu:
and go to fullscreen then:
Alt+Cmd+F - on Mac
F11 - on Windows
In this example, you can replace the <namespace>
and <app-name>
to get the logs when there are multiple Containers defined in a Pod.
kubectl -n <namespace> logs -f deployment/<app-name> \
--all-containers=true --since=10m
You can use
hdfs fsck /
to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with
hdfs fsck / | egrep -v '^\.+$' | grep -v eplica
which ignores lines with nothing but dots and lines talking about replication.
Once you find a file that is corrupt
hdfs fsck /path/to/corrupt/file -locations -blocks -files
Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.
You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.
Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.
Once you determine what happened and you cannot recover any more blocks, just use the
hdfs fs -rm /path/to/file/with/permanently/missing/blocks
command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
There is an another variant of collect method provided by LongStream class and similarly by IntStream and DoubleStream classes too .
<R> R collect(Supplier<R> supplier,
ObjLongConsumer<R> accumulator,
BiConsumer<R,R> combiner)
Performs a mutable reduction operation on the elements of this stream. A mutable reduction is one in which the reduced value is a mutable result container, such as an ArrayList, and elements are incorporated by updating the state of the result rather than by replacing the result. This produces a result equivalent to:
R result = supplier.get();
for (long element : this stream)
accumulator.accept(result, element);
return result;
Like reduce(long, LongBinaryOperator), collect operations can be parallelized without requiring additional synchronization. This is a terminal operation.
And answer to your question with this collect method is as below :
LongStream.of(1L, 2L, 3L, 3L).filter(i -> i > 2)
.collect(ArrayList::new, (list, value) -> list.add(value)
, (list1, list2) -> list1.addAll(list2));
Below is the method reference variant which is quite smart but some what tricky to understand :
LongStream.of(1L, 2L, 3L, 3L).filter(i -> i > 2)
.collect(ArrayList::new, List::add , List::addAll);
Below will be the HashSet variant :
LongStream.of(1L, 2L, 3L, 3).filter(i -> i > 2)
.collect(HashSet::new, HashSet::add, HashSet::addAll);
Similarly LinkedList variant is like this :
LongStream.of(1L, 2L, 3L, 3L)
.filter(i -> i > 2)
.collect(LinkedList::new, LinkedList::add, LinkedList::addAll);
Just stumbled upon the same problem and most answers here seem to only solve it for Angular internal routing, and then some of them for route parameters which is not the same as request parameters.
I am guessing that I have a similar use case to the original question by Lars.
For me the use case is e.g. referral tracking:
Angular running on mycoolpage.com
, with hash routing, so mycoolpage.com
redirects to mycoolpage.com/#/
. For referral, however, a link such as mycoolpage.com?referrer=foo
should also be usable. Unfortunately, Angular immediately strips the request parameters, going directly to mycoolpage.com/#/
.
Any kind of 'trick' with using an empty component + AuthGuard and getting queryParams
or queryParamMap
did, unfortunately, not work for me. They were always empty.
My hacky solution ended up being to handle this in a small script in index.html
which gets the full URL, with request parameters. I then get the request param value via string manipulation and set it on window object. A separate service then handles getting the id from the window object.
index.html script
const paramIndex = window.location.href.indexOf('referrer=');
if (!window.myRef && paramIndex > 0) {
let param = window.location.href.substring(paramIndex);
param = param.split('&')[0];
param = param.substr(param.indexOf('=')+1);
window.myRef = param;
}
Service
declare var window: any;
@Injectable()
export class ReferrerService {
getReferrerId() {
if (window.myRef) {
return window.myRef;
}
return null;
}
}
Use either auto-fill
or auto-fit
as the first argument of the repeat()
notation.
<auto-repeat>
variant of the repeat()
notation:
repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
auto-fill
When
auto-fill
is given as the repetition number, if the grid container has a definite size or max size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
The grid will repeat as many tracks as possible without overflowing its container.
In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.
The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.
auto-fit
The
auto-fit
keyword behaves the same asauto-fill
, except that after grid item placement any empty repeated tracks are collapsed.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to 0
.
A collapsed track is treated as having a fixed track sizing function of 0px
.
Unlike the auto-fill
image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.
auto-fill
vs auto-fit
The difference between the two is noticeable when the minmax()
function is used.
Use minmax(186px, 1fr)
to range the items from 186px
to a fraction of the leftover space in the grid container.
When using auto-fill
, the items will grow once there is no space to place empty tracks.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
When using auto-fit
, the items will grow to fill the remaining space because all the empty tracks will be collapsed to 0px
.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
Playground:
Inspecting auto-fill tracks
Inspecting auto-fit tracks
If you want to refer to names from the header rather than column numbers, you can use something like this:
fname <- "test.csv"
headset <- read.csv(fname, header = TRUE, nrows = 10)
classes <- sapply(headset, class)
classes[names(classes) %in% c("time")] <- "character"
dataset <- read.csv(fname, header = TRUE, colClasses = classes)
This will be helpful for the right bottom rounded button
HTML :
<a class="fixedButton" href>
<div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
</a>
CSS:
.fixedButton{
position: fixed;
bottom: 0px;
right: 0px;
padding: 20px;
}
.roundedFixedBtn{
height: 60px;
line-height: 80px;
width: 60px;
font-size: 2em;
font-weight: bold;
border-radius: 50%;
background-color: #4CAF50;
color: white;
text-align: center;
cursor: pointer;
}
Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/
On recents versions in application.yml
config:
---
spring:
profiles: dev
server:
compression:
enabled: true
mime-types: text/html,text/css,application/javascript,application/json
---
try this
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(OnSuccessListener<InstanceIdResult> { instanceIdResult ->
fcm_token = instanceIdResult.token}
As mentioned in a comment above, you can have expressions within the template strings/literals. Example:
const one = 1;_x000D_
const two = 2;_x000D_
const result = `One add two is ${one + two}`;_x000D_
console.log(result); // output: One add two is 3
_x000D_
Remove javascript:
from onclick="..
, onsubmit="..
declarations
javascript:
prefix is used only in href=""
or similar attributes (not events related)
Scope defines the area, where functions, variables and such are available. The availability of a variable for example is defined within its the context, let's say the function, file, or object, they are defined in. We usually call these local variables.
The lexical part means that you can derive the scope from reading the source code.
Lexical scope is also known as static scope.
Dynamic scope defines global variables that can be called or referenced from anywhere after being defined. Sometimes they are called global variables, even though global variables in most programmin languages are of lexical scope. This means, it can be derived from reading the code that the variable is available in this context. Maybe one has to follow a uses or includes clause to find the instatiation or definition, but the code/compiler knows about the variable in this place.
In dynamic scoping, by contrast, you search in the local function first, then you search in the function that called the local function, then you search in the function that called that function, and so on, up the call stack. "Dynamic" refers to change, in that the call stack can be different every time a given function is called, and so the function might hit different variables depending on where it is called from. (see here)
To see an interesting example for dynamic scope see here.
For further details see here and here.
Some examples in Delphi/Object Pascal
Delphi has lexical scope.
unit Main;
uses aUnit; // makes available all variables in interface section of aUnit
interface
var aGlobal: string; // global in the scope of all units that use Main;
type
TmyClass = class
strict private aPrivateVar: Integer; // only known by objects of this class type
// lexical: within class definition,
// reserved word private
public aPublicVar: double; // known to everyboday that has access to a
// object of this class type
end;
implementation
var aLocalGlobal: string; // known to all functions following
// the definition in this unit
end.
The closest Delphi gets to dynamic scope is the RegisterClass()/GetClass() function pair. For its use see here.
Let's say that the time RegisterClass([TmyClass]) is called to register a certain class cannot be predicted by reading the code (it gets called in a button click method called by the user), code calling GetClass('TmyClass') will get a result or not. The call to RegisterClass() does not have to be in the lexical scope of the unit using GetClass();
Another possibility for dynamic scope are anonymous methods (closures) in Delphi 2009, as they know the variables of their calling function. It does not follow the calling path from there recursively and therefore is not fully dynamic.
Try this
Demo is here
$(document).delegate('input[type="text"]','click', function() {
$(this).replaceWith('<input type="password" value="'+this.value+'" id="'+this.id+'">');
});
$(document).delegate('input[type="password"]','click', function() {
$(this).replaceWith('<input type="text" value="'+this.value+'" id="'+this.id+'">');
});
Chrome://chrome/settings/Privacy/Content settings/JavaScript
and there you can PASTE your website's URL in Manage exceptions..
and change the JavaScript priority from ALLOW to BLOCK.
A slightly simpler method:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}
Figured it out. Used this instead.
$('.div_class').load('http://en.wikipedia.org/wiki/Cross-origin_resource_sharing #toctitle');
Try this :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var res = Find(html);
}
public static List<LinkItem> Find(string file)
{
List<LinkItem> list = new List<LinkItem>();
// 1.
// Find all matches in file.
MatchCollection m1 = Regex.Matches(file, @"(<a.*?>.*?</a>)",
RegexOptions.Singleline);
// 2.
// Loop over each match.
foreach (Match m in m1)
{
string value = m.Groups[1].Value;
LinkItem i = new LinkItem();
// 3.
// Get href attribute.
Match m2 = Regex.Match(value, @"href=\""(.*?)\""",
RegexOptions.Singleline);
if (m2.Success)
{
i.Href = m2.Groups[1].Value;
}
// 4.
// Remove inner tags from text.
string t = Regex.Replace(value, @"\s*<.*?>\s*", "",
RegexOptions.Singleline);
i.Text = t;
list.Add(i);
}
return list;
}
public struct LinkItem
{
public string Href;
public string Text;
public override string ToString()
{
return Href + "\n\t" + Text;
}
}
}
Input:
string html = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> 2.<a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> ";
Result:
[0] = {www.aaa.xx/xx.zz?id=xxxx&name=xxxx}
[1] = {http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx}
Scraping HTML extracts important page elements. It has many legal uses for webmasters and ASP.NET developers. With the Regex type and WebClient, we implement screen scraping for HTML.
Another easy way:you can use a web browser
control for getting href
from tag a
,like this:(see my example)
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"https://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"www.aaa.xx/xx.zz/xxx\" ....></a>";
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
List<string> href = new List<string>();
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("a"))
{
href.Add(el.GetAttribute("href"));
}
}
I was able to reduce my gradle build from 43 seconds down to 25 seconds on my old core2duo laptop (running linux mint) by adding the following to the gradle.properties file in android studio
org.gradle.parallel=true
org.gradle.daemon=true
source on why the daemon setting makes builds faster: https://www.timroes.de/2013/09/12/speed-up-gradle/
Several good solutions here. If you're still on Win2K and can't install anything on the remote computer, this also works:
Open the Computer Management Console (right click My Computer, choose Manage; open from Administrative Tools in the Start Menu; or open from the MMC using the snap-in).
Right click on your computer name and choose "Connect to Remote Computer"
Put in the computer name and credentials and you have full access to many admin functions including the services control panel.
you can do that by simple way, simply change the variable value that used in for loop to the end value as shown in example
Sub TEST_ONLY()
For i = 1 To 10
ActiveSheet.Cells(i, 1).Value = i
If i = 5 Then
i = 10
End If
Next i
End Sub
_x000D_
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name
($key) and value
($field) for each field, as iterate over the fields of a row.
Wrapped in <table>
so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
Deleting and Recreating a project with same name is tricky. If you try to follow above suggested steps and try to create a project with same name as the one you just deleted, you will run into error like
'C:/xxxxxx/pom.xml' already exists in VFS
Here is what I found would work.
Insert an XML comment. ;-)
/// <summary>
/// Describe your member here.
/// </summary>
public string Something
{
get;
set;
}
This may appear like a joke at the first glance, but it may actually be useful. For me it turned out to be helpful to think about what methods do even for private methods (unless really trivial, of course).
//validation class
public class EditTextValidation {
public static boolean isValidText(CharSequence target) {
return target != null && target.length() != 0;
}
public static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public static boolean isValidPhoneNumber(CharSequence target) {
if (target.length() != 10) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
//activity or fragment
val userName = registerNameET.text?.trim().toString()
val mobileNo = registerMobileET.text?.trim().toString()
val emailID = registerEmailIDET.text?.trim().toString()
when {
!EditTextValidation.isValidText(userName) -> registerNameET.error = "Please provide name"
!EditTextValidation.isValidEmail(emailID) -> registerEmailIDET.error =
"Please provide email"
!EditTextValidation.isValidPhoneNumber(mobileNo) -> registerMobileET.error =
"Please provide mobile number"
else -> {
showToast("Hello World")
}
}
**Hope it will work for you... It is a working example.
If you have java installed of course keytool is in there. What you need to do is to add it on your PATH variable.
Retrieving the day of the week's number is dramatically simplified in Swift 3 because DateComponents
is no longer optional. Here it is as an extension:
extension Date {
func dayNumberOfWeek() -> Int? {
return Calendar.current.dateComponents([.weekday], from: self).weekday
}
}
// returns an integer from 1 - 7, with 1 being Sunday and 7 being Saturday
print(Date().dayNumberOfWeek()!) // 4
If you were looking for the written, localized version of the day of week:
extension Date {
func dayOfWeek() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self).capitalized
// or use capitalized(with: locale) if you want
}
}
print(Date().dayOfWeek()!) // Wednesday
A pointer to a class member function is not the same as a pointer to a function. A class member takes an implicit extra argument (the this pointer), and uses a different calling convention.
If your API expects a nonmember callback function, that's what you have to pass to it.
if you invoke .equals()
on null
you will get NullPointerException
So it is always advisble to check nullity before invoking method where ever it applies
if(str!=null && str.equals("hi")){
//str contains hi
}
Also See
$file = Get-Item -Path "c:/foo/foobar.txt"
$file.Name
Works with both relative an absolute paths
You can use exec
for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
using(var database=new DatabaseEntities()){}
Don't use using statement. Just write like that
DatabaseEntities database=new DatabaseEntities ();{}
It will work.
For documentation on the using
statement see here.
If the content type is recognized as form data, request.data
will parse that into request.form
and return an empty string.
To get the raw data regardless of content type, call request.get_data()
. request.data
calls get_data(parse_form_data=True)
, while the default is False
if you call it directly.
well, you can use SC.EXE to delete any windows Service forcefully if un-install doesnt removes by any chance.
sc delete <Service_Name>
Read more on "MS Techno Blogging" Deleting Services Forcefully from Services MMC
copy structure in c you just need to assign the values as follow:
struct RTCclk RTCclk1;
struct RTCclk RTCclkBuffert;
RTCclk1.second=3;
RTCclk1.minute=4;
RTCclk1.hour=5;
RTCclkBuffert=RTCclk1;
now RTCclkBuffert.hour will have value 5,
RTCclkBuffert.minute will have value 4
RTCclkBuffert.second will have value 3
The line reader.Read()
is missing in your code. You should add it. It is the function which actually reads data from the database:
string conString = "Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "select * from Pending_Tasks";
SqlCommand com = new SqlCommand(selectSql, con);
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while(reader.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
}
}
finally
{
con.Close();
}
EDIT : This code works supposing you want to write the last record to your textboxes. If you want to apply a different scenario, like for example to read all the records from database and to change data in the texboxes when you click the Next
button, you should create and use your own Model, or you can store data in the DataTable and refer to them later if you wish.
It's used in for loops to iterate over a list of objects.
for (Object o: list)
{
// o is an element of list here
}
Think of it as a for <item> in <list>
in Python.
Easier alternative to above answers
If Object(Model Class/POJO) contains the date in String datatype.
private void sortArray(ArrayList<myObject> arraylist) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //your own date format
if (reports != null) {
Collections.sort(arraylist, new Comparator<myObject>() {
@Override
public int compare(myObject o1, myObject o2) {
try {
return simpleDateFormat.parse(o2.getCreated_at()).compareTo(simpleDateFormat.parse(o1.getCreated_at()));
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
});
}
If Object(Model Class/POJO) contains date in Date datatype
private void sortArray(ArrayList<myObject> arrayList) {
if (arrayList != null) {
Collections.sort(arrayList, new Comparator<myObject>() {
@Override
public int compare(myObject o1, myObject o2) {
return o2.getCreated_at().compareTo(o1.getCreated_at()); }
});
} }
The above code is for sorting the array in descending order of date, swap o1 and o2 for ascending order.
There are several other version managers to consider, see for a few examples and one that's not listed there that I'll be giving a try soon is ch-ruby. I tried rbenv but had too many problems with it. RVM is my mainstay, though it sometimes has the odd problem (hence my wish to try ch-ruby when I get a chance). I wouldn't touch the system Ruby, as other things may rely on it.
I should add I've also compiled my own Ruby several times, and using the Hivelogic article (as Dave Everitt has suggested) is a good idea if you take that route.
textFieldView.keyboardType = UIKeyboardType.PhonePad
This is for swift. Also in order for this to function properly it must be set after the textFieldView.delegate = self
from django.db import models
class Foo(models.Model):
any_field = models.BooleanField(default=True)
After some serious searching it seems i've found the answer to my question:
from: http://www.brunildo.org/test/Overflowxy2.html
In Gecko, Safari, Opera, ‘visible’ becomes ‘auto’ also when combined with ‘hidden’ (in other words: ‘visible’ becomes ‘auto’ when combined with anything else different from ‘visible’). Gecko 1.8, Safari 3, Opera 9.5 are pretty consistent among them.
also the W3C spec says:
The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.
Short Version:
If you are using visible
for either overflow-x
or overflow-y
and something other than visible
for the other, the visible
value is interpreted as auto
.
I know this question goes a way back and there are some excellent answers here, nonetheless I wanted to share another bit for the mathematically-minded people that will stumble in this post. The Master theorem is another usefull thing to know when studying complexity. I didn't see it mentioned in the other answers.
I think the best way to do that is to first read the file into a byte array, then convert the array to an image with ImageIO.read()
You can use input.value = JSON.stringify(obj)
to transform the object to a string.
And when you need it back you can use obj = JSON.parse(input.value)
The JSON object is available on modern browsers or you can use the json2.js library from json.org
I had to use required="required"
along with the same name and type, and then validation worked fine.
<input type="radio" name="user-radio" id="" value="User" required="required" />
<input type="radio" name="user-radio" id="" value="Admin" />
<input type="radio" name="user-radio" id="" value="Guest" />
I think you should call the super.draw()
method first before you do anything in surfaceView's draw method.
Set the highlighted properties. Set MaximimSize and MinimizeSize properties the same size
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30