Look here:
http://tratt.net/laurie/tech_articles/articles/tail_call_optimization
As you probably know, recursive function calls can wreak havoc on a stack; it is easy to quickly run out of stack space. Tail call optimization is way by which you can create a recursive style algorithm that uses constant stack space, therefore it does not grow and grow and you get stack errors.
TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).
As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.
BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.
for me this works
unicode(data).encode('utf-8')
For Xcode 4.1 you can simply add /Developer/usr/bin to the PATH environment variable. This is easily done:
$ export PATH=$PATH:/Developer/usr/bin
Also be certain to update your ~/.bashrc (or ~/.profile or ~/.bash_login) file.
.btn
is the best way, in modern website, it's not good while using anchor element
without href
so make the anchor tag
to button
is better.
Here is the simplest solution
select m_id,v_id,max(timestamp) from table group by m_id;
Group by m_id but get max of timestamp for each m_id.
String pooling
String pooling (sometimes also called as string canonicalisation) is a process of replacing several String objects with equal value but different identity with a single shared String object. You can achieve this goal by keeping your own Map (with possibly soft or weak references depending on your requirements) and using map values as canonicalised values. Or you can use String.intern() method which is provided to you by JDK.
At times of Java 6 using String.intern() was forbidden by many standards due to a high possibility to get an OutOfMemoryException if pooling went out of control. Oracle Java 7 implementation of string pooling was changed considerably. You can look for details in http://bugs.sun.com/view_bug.do?bug_id=6962931 and http://bugs.sun.com/view_bug.do?bug_id=6962930.
String.intern() in Java 6
In those good old days all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool. Besides explicitly interned strings, PermGen string pool also contained all literal strings earlier used in your program (the important word here is used – if a class or method was never loaded/called, any constants defined in it will not be loaded).
The biggest issue with such string pool in Java 6 was its location – the PermGen. PermGen has a fixed size and can not be expanded at runtime. You can set it using -XX:MaxPermSize=96m option. As far as I know, the default PermGen size varies between 32M and 96M depending on the platform. You can increase its size, but its size will still be fixed. Such limitation required very careful usage of String.intern – you’d better not intern any uncontrolled user input using this method. That’s why string pooling at times of Java 6 was mostly implemented in the manually managed maps.
String.intern() in Java 7
Oracle engineers made an extremely important change to the string pooling logic in Java 7 – the string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application. Technically, this alone could be a sufficient reason to reconsider using String.intern() in your Java 7 programs. But there are other reasons.
String pool values are garbage collected
Yes, all strings in the JVM string pool are eligible for garbage collection if there are no references to them from your program roots. It applies to all discussed versions of Java. It means that if your interned string went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.
Being eligible for garbage collection and residing in the heap, a JVM string pool seems to be a right place for all your strings, isn’t it? In theory it is true – non-used strings will be garbage collected from the pool, used strings will allow you to save memory in case then you get an equal string from the input. Seems to be a perfect memory saving strategy? Nearly so. You must know how the string pool is implemented before making any decisions.
Yes, you can use Visual Studio for Android (native) using "vs-android".
Here are the steps to set it up:
Download the Android SDK here.
Download the Android NDK here.
Download Cygwin here.
Download the JDK here.
Download Visual Studio 2010, 2012 or 2013 here.
Download vs-android here.
Download Apache Ant here.
Set environment variables:
(Control Panel > System > Advanced > Environment Variables)
ANDROID_HOME = <install_path>\android-sdk
ANDROID_NDK_ROOT = <install_path>\android-ndk
ANT_HOME = <install_path>\apache-ant
JAVA_HOME = <install_path>\jdk
_JAVA_OPTIONS = -Xms256m -Xmx512m
It works like a charm... and best so far to use.
Translated accepted answer to YAML works for me
logging:
level:
org:
hibernate:
SQL:
TRACE
type:
descriptor:
sql:
BasicBinder:
TRACE
You can use rows
and cols
:
cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;
or size()
:
cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;
While I agree with Ari's answer (and upvoted it :), I needed to do an extra step to get it to work with Java on Windows (where it needed to be deployed):
openssl s_client -showcerts -connect www.example.com:443 < /dev/null | openssl x509 -outform DER > derp.der
Before adding the openssl x509 -outform DER
conversion, I was getting an error from keytool on Windows complaining about the certificate's format. Importing the .der file worked fine.
Remove the date()
part
SELECT name, datum
FROM tasks
WHERE datum >= NOW()
and if you use a specific date, don't forget the quotes around it and use the proper format with :
SELECT name, datum
FROM tasks
WHERE datum >= '2014-05-18 15:00:00'
I found I could add
::-webkit-scrollbar {
display: none;
}
directly to my css and it would make the scrollbar invisible, but still allow me to scroll (on Chrome at least). Good for when you don't want a distracting scrollbar on your page!
Do your trouble shooting in controlled steps:
(1) Does the script looks ok?
DOS E:\trials\SoTrials\SoDbTrials\MySQLScripts
type ansi.sql
show databases
(2) Can you connect to your database (even without specified the host)?
DOS E:\trials\SoTrials\SoDbTrials\MySQLScripts
mysql -u root -p mysql
Enter password: ********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.0.51b-community-nt MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
(3) Can you source the script? (Hoping for more/better error info)
mysql> source ansi.sql
+--------------------+
| Database |
+--------------------+
| information_schema |
| ... |
| test |
+--------------------+
7 rows in set (0.01 sec)
mysql> quit
Bye
(4) Why does it (still not) work?
DOS E:\trials\SoTrials\SoDbTrials\MySQLScripts
mysql -u root -p mysql < ansi.sql
Enter password: ********
Database
information_schema
...
test
I suspected that the encoding of the script could be the culprit, but I got syntax errors for UTF8 or UTF16 encoded files:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '´++
show databases' at line 1
This could be a version thing; so I think you should make sure of the encoding of your script.
Use the following code fragment to hide the form on button click.
document.getElementById("your form id").style.display="none";
And the following code to display it:
document.getElementById("your form id").style.display="block";
Or you can use the same function for both purposes:
function asd(a)
{
if(a==1)
document.getElementById("asd").style.display="none";
else
document.getElementById("asd").style.display="block";
}
And the HTML:
<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>
The basic difference between interface and abstract class is, interface supports multiple inheritance but abstract class not.
In abstract class also you can provide all abstract methods like interface.
why abstract class is required?
In some scenarios, while processing user request, the abstract class doesn't know what user intention. In that scenario, we will define one abstract method in the class and ask the user who extending this class, please provide your intention in the abstract method. In this case abstract classes are very useful
Why interface is required?
Let's say, I have a work which I don't have experience in that area. Example, if you want to construct a building or dam, then what you will do in that scenario?
Here I don't bother about the logic how they constructed. The final object satisfied my requirements or not, that only my key point.
Here your requirements called interface and constructors are called implementor.
Attention: this is an extremely rough and oversimplified sketch, assuming the simplest possible HTTP request (no HTTPS, no HTTP2, no extras), simplest possible DNS, no proxies, single-stack IPv4, one HTTP request only, a simple HTTP server on the other end, and no problems in any step. This is, for most contemporary intents and purposes, an unrealistic scenario; all of these are far more complex in actual use, and the tech stack has become an order of magnitude more complicated since this was written. With this in mind, the following timeline is still somewhat valid:
Again, discussion of each of these points have filled countless pages; take this only as a summary, abridged for the sake of clarity. Also, there are many other things happening in parallel to this (processing typed-in address, speculative prefetching, adding page to browser history, displaying progress to user, notifying plugins and extensions, rendering the page while it's downloading, pipelining, connection tracking for keep-alive, cookie management, checking for malicious content etc.) - and the whole operation gets an order of magnitude more complex with HTTPS (certificates and ciphers and pinning, oh my!).
If you want to use enhanced loop, you can convert the string to charArray
for (char ch : exampleString.toCharArray()) {
System.out.println(ch);
}
Here you go:
SELECT Field1, COUNT(Field1)
FROM Table1
GROUP BY Field1
HAVING COUNT(Field1) > 1
ORDER BY Field1 desc
You can also use vscode to compare branches using extension CodeLense, this is already answered in this SO: How to compare different branches on Visual studio code
As a commenter mentioned you can get Values
from net/url
which has an Encode
method. You could do something like this (req.URL.Query()
returns the existing url.Values
)
package main
import (
"fmt"
"log"
"net/http"
"os"
)
func main() {
req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// Output:
// http://api.themoviedb.org/3/tv/popular?another_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}
Use following property same as table and its fully dynamic:
ul {_x000D_
width: 100%;_x000D_
display: table;_x000D_
table-layout: fixed; /* optional, for equal spacing */_x000D_
border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
display: table-cell;_x000D_
text-align: center;_x000D_
border: 1px solid pink;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo<br>foo</li>_x000D_
<li>barbarbarbarbar</li>_x000D_
<li>baz klxjgkldjklg </li>_x000D_
<li>baz</li>_x000D_
<li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
May be its solve your issue.
XAMPP by default uses http://localhost/phpmyadmin
It also requires you start both Apache and MySQL from the control panel (or as a service).
In the XAMPP Control Panel, clicking [ Admin ] on the MySQL line will open your default browser at the configured URL for the phpMyAdmin application.
If you get a phpMyAdmin error stating "Cannot connect: invalid settings." You will need to make sure your MySQL config file has a matching port for server and client. If it is not the standard 3306 port, you will also need to change your phpMyAdmin config file under apache (config.inc.php) to meet the new port settings. (127.0.0.1 becomes 127.0.0.1:<port>)
I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.
Wrap up content like below,
var params = {
"IDs": IDs,
"ID2s": IDs2,
"id": 1
};
In my case I had already json'd the arrays and passed the result to the function
var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());
Then call the XMLHttpRequest POST and stringify the object
var ajax = new XMLHttpRequest();
ajax.open("POST", '@Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
ajax.onreadystatechange = function () {
if (this.readyState == 4) {
var blob = new Blob([this.response], { type: "application/octet-stream" });
saveAs(blob, "filename.zip");
}
};
ajax.send(JSON.stringify(params));
Then have a model like this
public class MyModel
{
public int[] IDs { get; set; }
public int[] ID2s { get; set; }
public int id { get; set; }
}
Then pass in Action like
public async Task<IActionResult> MyAction([FromBody] MyModel model)
Use this add-on if your returning a file
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
Simply query the INFORMATION_SCHEMA:
USE INFORMATION_SCHEMA;
SELECT TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "<your_database_name>"
AND TABLE_NAME = "<your_table_name>"
AND REFERENCED_COLUMN_NAME IS NOT NULL;
$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice
$newInvoice.ToString("yyyy-MM-dd")
There you go, use a type accelerator, but also into a new var, if you want to use it elsewhere, use it like so: $newInvoice.ToString("yyyy-MM-dd")
as $newInvoice
will always be in the datetime format, unless you cast it as a string afterwards, but will lose the ability to perform datetime functions - adding days etc...
This will return all documents with a key called "IMAGE URL", but they may still have a null value.
db.mycollection.find({"IMAGE URL":{$exists:true}});
This will return all documents with both a key called "IMAGE URL" and a non-null value.
db.mycollection.find({"IMAGE URL":{$ne:null}});
Also, according to the docs, $exists currently can't use an index, but $ne can.
Edit: Adding some examples due to interest in this answer
Given these inserts:
db.test.insert({"num":1, "check":"check value"});
db.test.insert({"num":2, "check":null});
db.test.insert({"num":3});
This will return all three documents:
db.test.find();
This will return the first and second documents only:
db.test.find({"check":{$exists:true}});
This will return the first document only:
db.test.find({"check":{$ne:null}});
This will return the second and third documents only:
db.test.find({"check":null})
This means that your ArrayList has integers in some elements. The casting should work unless there's an integer in one of your elements.
One way to make sure that your arraylist has no integers is by declaring it as a Doubles array.
ArrayList<Double> marks = new ArrayList<Double>();
Here's what I ended up using.
I'm very new to AngularJS, so would love to see better / alternative solutions.
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
scope: {},
link: function(scope, element, attrs)
{
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
element.html(htmlText);
}
}
})
Example usage:
<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>
Its work fine to me,You can try it.
protected void displayNotification() {
Log.i("Start", "notification");
// Invoking the default notification service //
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this);
mBuilder.setAutoCancel(true);
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You have "+unMber_unRead_sms +" new message.");
mBuilder.setTicker("New message from PayMe..");
mBuilder.setSmallIcon(R.drawable.icon2);
// Increase notification number every time a new notification arrives //
mBuilder.setNumber(unMber_unRead_sms);
// Creates an explicit intent for an Activity in your app //
Intent resultIntent = new Intent(this, FreesmsLog.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(FreesmsLog.class);
// Adds the Intent that starts the Activity to the top of the stack //
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// mBuilder.setOngoing(true);
Notification note = mBuilder.build();
note.defaults |= Notification.DEFAULT_VIBRATE;
note.defaults |= Notification.DEFAULT_SOUND;
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on. //
mNotificationManager.notify(notificationID, mBuilder.build());
}
Simply define a function and set the value of your Combobox to empty/null or whatever you want. Try the following.
def Reset():
cmb.set("")
here, cmb
is a variable in which you have assigned the Combobox. Now call that function in a button such as,
btn2 = ttk.Button(root, text="Reset",command=Reset)
The <style>
tag belongs in the <head>
section, separate from all the content.
unicode_escape
doesn't work in generalIt turns out that the string_escape
or unicode_escape
solution does not work in general -- particularly, it doesn't work in the presence of actual Unicode.
If you can be sure that every non-ASCII character will be escaped (and remember, anything beyond the first 128 characters is non-ASCII), unicode_escape
will do the right thing for you. But if there are any literal non-ASCII characters already in your string, things will go wrong.
unicode_escape
is fundamentally designed to convert bytes into Unicode text. But in many places -- for example, Python source code -- the source data is already Unicode text.
The only way this can work correctly is if you encode the text into bytes first. UTF-8 is the sensible encoding for all text, so that should work, right?
The following examples are in Python 3, so that the string literals are cleaner, but the same problem exists with slightly different manifestations on both Python 2 and 3.
>>> s = 'naïve \\t test'
>>> print(s.encode('utf-8').decode('unicode_escape'))
naïve test
Well, that's wrong.
The new recommended way to use codecs that decode text into text is to call codecs.decode
directly. Does that help?
>>> import codecs
>>> print(codecs.decode(s, 'unicode_escape'))
naïve test
Not at all. (Also, the above is a UnicodeError on Python 2.)
The unicode_escape
codec, despite its name, turns out to assume that all non-ASCII bytes are in the Latin-1 (ISO-8859-1) encoding. So you would have to do it like this:
>>> print(s.encode('latin-1').decode('unicode_escape'))
naïve test
But that's terrible. This limits you to the 256 Latin-1 characters, as if Unicode had never been invented at all!
>>> print('Erno \\t Rubik'.encode('latin-1').decode('unicode_escape'))
UnicodeEncodeError: 'latin-1' codec can't encode character '\u0151'
in position 3: ordinal not in range(256)
(Surprisingly, we do not now have two problems.)
What we need to do is only apply the unicode_escape
decoder to things that we are certain to be ASCII text. In particular, we can make sure only to apply it to valid Python escape sequences, which are guaranteed to be ASCII text.
The plan is, we'll find escape sequences using a regular expression, and use a function as the argument to re.sub
to replace them with their unescaped value.
import re
import codecs
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\U........ # 8-digit hex escapes
| \\u.... # 4-digit hex escapes
| \\x.. # 2-digit hex escapes
| \\[0-7]{1,3} # Octal escapes
| \\N\{[^}]+\} # Unicode characters by name
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
def decode_escapes(s):
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
And with that:
>>> print(decode_escapes('Erno \\t Rubik'))
Erno Rubik
You can use list open file command and then kill the process like below.
sudo lsof -t -i tcp:8181 | xargs kill -9
or
sudo lsof -i tcp:8181
kill -9 PID
If you are using Express > 4.0, you could go for serve-favicon
You want to join on condition 1 AND condition 2, so simply use the AND keyword as below
ON a.userid = b.sourceid AND a.listid = b.destinationid;
That should be simple. Try this:
var idList = new int[1, 2, 3, 4, 5];
var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e));
Having something like the following would work.
<iframe id = "testframe" onload = populateIframe(this.id);></iframe>
// The following function should be inside a script tag
function populateIframe(id) {
var text = "This is a Test"
var iframe = document.getElementById(id);
var doc;
if(iframe.contentDocument) {
doc = iframe.contentDocument;
} else {
doc = iframe.contentWindow.document;
}
doc.body.innerHTML = text;
}
You're already prepending the hash sign in your showDialog()
function, and you're missing single quotes in your second code snippet. You should also return false
from the handler to prevent a postback from occurring. Try:
<asp:Button ID="ButtonAdd" runat="server" Text="Add"
OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />
How I placed a border around my UI view (main - SubscriptionAd) in Storyboard is to place it inside another UI view (background - BackgroundAd). The Background UIView has a background colour that matches the border colour i want, and the Main UIView has constraints value 2 from each side.
I will link the background view to my ViewController and then turn the border on and off by changing the background colour.
you can use String format to include variables within strings
i use this code to include 2 variable in string:
String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);
<table>
<tbody>
<tr><td>{{data[0].foo}}</td></tr>
<tr ng-repeat="d in data[1]"><td>{{d.bar}}</td></tr>
<tr ng-repeat="d in data[2]"><td>{{d.lol}}</td></tr>
</tbody>
</table>
I think that this is valid :)
<table style="border: 1px solid red">
<thead>
<tr>
<td>Header stays put, no scrolling</td>
</tr>
</thead>
<tbody id="tbodyMain" style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
<tr>
<td>cell 1/1</td>
<td>cell 1/2</td>
</tr>
<tr>
<td>cell 2/1</td>
<td>cell 2/2</td>
</tr>
<tr>
<td>cell 3/1</td>
<td>cell 3/2</td>
</tr>
</tbody>
</table>
Javascript Section
<script>
$(document).ready(function(){
var maxHeight = Math.max.apply(null, $("body").map(function () { return $(this).height(); }).get());
// alert(maxHeight);
var borderheight =3 ;
// Added some pixed into maxheight
// If you set border then need to add this "borderheight" to maxheight varialbe
$("#tbodyMain").css("min-height", parseInt(maxHeight + borderheight) + "px");
});
</script>
please, refer How to set maximum possible height to your Table Body
Fiddle Here
If I had to do this with a regex, I'd do it like this:
s = re.sub(r'\.jpg$', '', s)
Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
Firebase is a suite of features .
I believe you are trying to compare Firebase Realtime Database with Mongo DB . Firebase Realtime Database stores data as JSON format and syncs to all updates of the data to all clients listening to the data . It abstracts you from all complexity that is needed to setup and scale any database . I will not recommend firebase where you have lot of complex scenarios where aggregation of data is needed .(Queries that need SUM/AVERAGE kind of stuff ) . Though this is recently achievable using Firebase functions . Modeling data in Firebase is tricky . But it is the best way to get you started instantaneously . MongoDB is a database. This give you lot of powerful features. But MongoDB when installed in any platform you need to manage it by yourself .
When i try to choose between Firebase or MongoDB(or any DB ) . I try to answer the following .
.NET and Mono are great environments, with many tools and and excellent skills base of people who know how to use them.
I think Mono has the opportunity to be the mobile cross-platform development environment of choice, seeing as they are the only alternative to Objective-C on the iPhone and should be portable to Android, and .NET is already on Windows Mobile.
I'm really hoping to see a solid implementation of Mono on Android, with wrappers for the Android API as with Monotouch, and would be prepared to pay for it since I'm not in a position to do it myself.
This arstechnica article describes the basic steps:
Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?
Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.
Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.
You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.
The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.
If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.
If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.
Neither of them worked for me for some reason.
I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.
And finally this worked for me.
cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
connect.commit()
EDIT: (As per the comments in question:)
I've been looking into this since then. I was lucky enough that I had repo laying around. Still it's not clear to me whether you need to enclose your commands between single quotes by force. I looked into the repo syntax and I don't think you need to. You could used double quotes around your command, and then use whatever single and double quotes you need inside provided you escape double ones.
If the file includes a line break in the middle of the text neither strip()
nor rstrip()
will not solve the problem,
strip family are used to trim from the began and the end of the string
replace()
is the way to solve your problem
>>> my_name = "Landon\nWO"
>>> print my_name
Landon
WO
>>> my_name = my_name.replace('\n','')
>>> print my_name
LandonWO
import * as utils from './utils.js';
If you do the above, you will be able to use functions in utils.js as
utils.someFunction()
Combining the answers of kiamlaluno and Mark, along with formatOnSave to autointent code for Python:
{
"editor.formatOnSave": true,
"editor.autoIndent": "advanced",
"editor.detectIndentation": true,
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,
"editor.formatOnPaste": true,
"editor.multiCursorModifier": "ctrlCmd",
"editor.snippetSuggestions": "top",
"editor.rulers": [
{
"column": 79,
"color": "#424142"
},
100, // <- a ruler in the default color or as customized at column 0
{
"column": 120,
"color": "#ff0000"
},
],
}
While the other answers are correct, there is an easy way to get rid of the underline on all those pesky links:
a {
text-decoration:none;
}
This will remove the underline from EVERY SINGLE LINK on your page!
Using numpy, you can do:
y = x.astype(int)
If you were using a non-numpy array, you could use a list comprehension:
y = [int(val) for val in x]
I have found it helpful to add a custom exec script to my utilities that do this.
utilities.js
const { exec } = require('child_process')
module.exports.exec = (command) => {
const process = exec(command)
process.stdout.on('data', (data) => {
console.log('stdout: ' + data.toString())
})
process.stderr.on('data', (data) => {
console.log('stderr: ' + data.toString())
})
process.on('exit', (code) => {
console.log('child process exited with code ' + code.toString())
})
}
app.js
const { exec } = require('./utilities.js')
exec('coffee -cw my_file.coffee')
I used to use (Timer
, TimerTask
) as well as Handler
to kick off (time-consuming) tasks periodically. Now I've switched the whole to RxJava. RxJava provides Observable.timer
which is simpler, less error-prone, hassle-free to use.
public class BetterTimerFragment extends Fragment {
public static final String TAG = "BetterTimer";
private TextView timeView;
private Subscription timerSubscription;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_timer, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
timeView = (TextView) view.findViewById(R.id.timeView);
}
@Override
public void onResume() {
super.onResume();
// Right after the app is visible to users, delay 2 seconds
// then kick off a (heavy) task every 10 seconds.
timerSubscription = Observable.timer(2, 10, TimeUnit.SECONDS)
.map(new Func1<Long, String>() {
@Override
public String call(Long unused) {
// TODO: Probably do time-consuming work here.
// This runs on a different thread than the main thread.
return "Time: " + System.currentTimeMillis();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
@Override
public void call(String timeText) {
// The result will then be propagated back to the main thread.
timeView.setText(timeText);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, throwable.getMessage(), throwable);
}
});
}
@Override
public void onPause() {
super.onPause();
// Don't kick off tasks when the app gets invisible.
timerSubscription.unsubscribe();
}
}
Yes, you should configure $locationProvider
and set html5Mode
to true
:
angular.module('phonecat', []).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.
when('/phones', {templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl}).
when('/phones/:phoneId', {templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl}).
otherwise({redirectTo: '/phones'});
$locationProvider.html5Mode(true);
}]);
Modified (now it accepts any non null string
and any positive chunkSize
) Konstantin Spirin's solution:
public static IEnumerable<String> Split(String value, int chunkSize) {
if (null == value)
throw new ArgumentNullException("value");
else if (chunkSize <= 0)
throw new ArgumentOutOfRangeException("chunkSize", "Chunk size should be positive");
return Enumerable
.Range(0, value.Length / chunkSize + ((value.Length % chunkSize) == 0 ? 0 : 1))
.Select(index => (index + 1) * chunkSize < value.Length
? value.Substring(index * chunkSize, chunkSize)
: value.Substring(index * chunkSize));
}
Tests:
String source = @"ABCDEF";
// "ABCD,EF"
String test1 = String.Join(",", Split(source, 4));
// "AB,CD,EF"
String test2 = String.Join(",", Split(source, 2));
// "ABCDEF"
String test3 = String.Join(",", Split(source, 123));
In Java I used encoding "IBM850" to write the file. That solved the problem.
You need to use document.write()
<div>foo</div>
<script>
document.write('<div>Print this after the script tag</div>');
</script>
<div>bar</div>
Note that this will only work if you are in the process of writing the document. Once the document has been rendered, calling document.write()
will clear the document and start writing a new one. Please refer to other answers provided to this question if this is your use case.
It is also possible to review changes between two commits for a specific file.
git diff <commit_Id_1> <commit_Id_2> some_dir/file.txt
Well if you are using Netbeans in Linux, then you should look for the tomcat-user.xml in
/home/Username/.netbeans/8.0/apache-tomcat-8.0.3.0_base/conf
(its called Catalina Base and is often hidden) instead of the Apache installation directory.
open tomcat-user.xml inside that folder, uncomment the user and roles and add/replace the following line.
<user username="tomcat" password="tomcat" roles="tomcat,admin,admin-gui,manager,manager-gui"/>
restart the server . That's all
Try a query like
INSERT INTO NEW_TABLENAME SELECT * FROM OLD_TABLENAME;
You have to use count() returns the number of rows that matches a specified criteria
select count(*) from table_name;
ssh-key with passphrase, with keychain
keychain is a small utility which manages ssh-agent on your behalf and allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.
To enable keychain, install it and add something like the following to ~/.bash_profile:
eval keychain --agents ssh --eval id_rsa
From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.
Got this info from;
Hope this helps
I have personally been able to automatically enter my passphrase upon terminal launch by doing this: (you can, of course, modify the script and fit it to your needs)
edit the bashrc file to add this script;
if [ -z "$SSH_AUTH_SOCK" ] ; then exec ssh-agent bash -c "ssh-add ; $0" echo "The SSH agent was awakened" exit fi
./ssh.exp
here's the content of this expect script
#!/usr/bin/expect
set timeout 20
set passphrase "test"
spawn "./keyadding.sh"
expect "Enter passphrase for /the/path/of/yourkey_id_rsa:"
send "$passphrase\r";
interact
Here's the content of my keyadding.sh script (you must put both scripts in your home folder, usually /home/user)
#!/bin/bash
ssh-add /the/path/of/yourkey_id_rsa
exit 0
I would HIGHLY suggest encrypting the password on the .exp script as well as renaming this .exp file to something like term_boot.exp or whatever else for security purposes. Don't forget to create the files directly from the terminal using nano or vim (ex: nano ~/.bashrc | nano term_boot.exp
) and also a chmod +x script.sh
to make it executable. A chmod +r term_boot.exp
would be also useful but you'll have to add sudo before ./ssh.exp in your bashrc file. So you'll have to enter your sudo password each time you launch your terminal. For me, it's more convenient than the passphrase cause I remember my admin (sudo) password by the hearth.
Also, here's another way to do it I think; https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/
Will certainly change my method for this one when I'll have the time.
Using useState with useEffect as described above is absolutely correct way. But if getSearchResults function returns subscription then useEffect should return a function which will be responsible for unsubscribing the subscription . Returned function from useEffect will run before each change to dependency(name in above case) and on component destroy
My way of Insert
in SQL Server. Also I usually check if a temporary table exists.
IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP Table #MyTable
SELECT b.Val as 'bVals'
INTO #MyTable
FROM OtherTable as b
The difference is not just for Chrome but for most of the web browsers.
F5
refreshes the web page and often reloads the same page from the cached contents of the web browser. However, reloading from cache every time is not guaranteed and it also depends upon the cache expiry.
Shift + F5
forces the web browser to ignore its cached contents and retrieve a fresh copy of the web page into the browser.
Shift + F5
guarantees loading of latest contents of the web page.
However, depending upon the size of page, it is usually slower than F5
.
You may want to refer to: What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?
Some of Methods mentioned above ignores if there are any integers and float with values 0 & 0.0
If someone wants to avoid the above can use below code(removes empty strings and None values from nested dictionary and nested list):
def remove_empty_from_dict(d):
if type(d) is dict:
_temp = {}
for k,v in d.items():
if v == None or v == "":
pass
elif type(v) is int or type(v) is float:
_temp[k] = remove_empty_from_dict(v)
elif (v or remove_empty_from_dict(v)):
_temp[k] = remove_empty_from_dict(v)
return _temp
elif type(d) is list:
return [remove_empty_from_dict(v) for v in d if( (str(v).strip() or str(remove_empty_from_dict(v)).strip()) and (v != None or remove_empty_from_dict(v) != None))]
else:
return d
TextView view = (TextView) findViewById(R.id.textView);
view.setText("Add your text here");
view.setVisibility(View.VISIBLE);
I'd recommend you to use Bytescout Spreadsheet.
https://bytescout.com/products/developer/spreadsheetsdk/bytescoutspreadsheetsdk.html
I tried it with Monodevelop in Unity3D and it is pretty straight forward. Check this sample code to see how the library works:
https://bytescout.com/products/developer/spreadsheetsdk/read-write-excel.html
Add your multiple columns with comma separations:
UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'
However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?
Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.
You declare the entity like this:
<!ENTITY otherFile SYSTEM "otherFile.xml">
Then you reference it like this:
&otherFile;
A complete example:
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE doc [
<!ENTITY otherFile SYSTEM "otherFile.xml">
]>
<doc>
<foo>
<bar>&otherFile;</bar>
</foo>
</doc>
When the XML parser reads the file, it will expand the entity reference and include the referenced XML file as part of the content.
If the "otherFile.xml" contained: <baz>this is my content</baz>
Then the XML would be evaluated and "seen" by an XML parser as:
<?xml version="1.0" standalone="no" ?>
<doc>
<foo>
<bar><baz>this is my content</baz></bar>
</foo>
</doc>
A few references that might be helpful:
Use join()
and the separator.
Working example
var arr = ['a', 'b', 'c', 1, 2, '3'];_x000D_
_x000D_
// using toString method_x000D_
var rslt = arr.toString(); _x000D_
console.log(rslt);_x000D_
_x000D_
// using join method. With a separator '-'_x000D_
rslt = arr.join('-');_x000D_
console.log(rslt);_x000D_
_x000D_
// using join method. without a separator _x000D_
rslt = arr.join('');_x000D_
console.log(rslt);
_x000D_
If you are only calling APIs that do not require user data, such as the Google Custom Search API, then API keys might be simpler to use than OAuth 2.0 access tokens. However, if your application already uses an OAuth 2.0 access token, then there is no need to generate an API key as well. Google ignores passed API keys if a passed OAuth 2.0 access token is already associated with the corresponding project.
Note: You must use either an OAuth 2.0 access token or an API key for all requests to Google APIs represented in the Google Developers Console. Not all APIs require authorized calls. To learn whether authorization is required for a specific call, see your API documentation.
Reference: https://developers.google.com/console/help/new/?hl=en_US#credentials-access-security-and-identity
Another alternative is;
sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP
I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.
Edit**
According to Fernando comment and this link exclamation mark (
!
) will be placed before than-s
parameter:
sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP
It's in the app.config file.
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceDebug includeExceptionDetailInFaults="true"/>
The shorter ES6 version of the answer:
const delay = t => new Promise(resolve => setTimeout(resolve, t));
And then you can do:
delay(3000).then(() => console.log('Hello'));
Here is one I haven't seen that's even shorter
arr.slice(1).slice(-5)
Run the code snippet below for proof of it doing what you want
var arr1 = [0, 1, 2, 3, 4, 5, 6, 7],_x000D_
arr2 = [0, 1, 2, 3];_x000D_
_x000D_
document.body.innerHTML = 'ARRAY 1: ' + arr1.slice(1).slice(-5) + '<br/>ARRAY 2: ' + arr2.slice(1).slice(-5);
_x000D_
Another way to do it would be using lodash https://lodash.com/docs#rest - that is of course if you don't mind having to load a huge javascript minified file if your trying to do it from your browser.
_.slice(_.rest(arr), -5)
strstr(request, "favicon") != NULL
Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}
then you create a menu strip item to exit the application.
cheers
File->Project Structure->Project pane->"Android plugin version".
Make sure you don't confuse the Gradle version with the Android plugin version. The former is the build system itself, the latter is the plugin to the build system that knows how to build Android projects
There are three ways. For the speed seekers I recommend 'Method 2'
Method 1
Given by this answer
text = 'abcdefg'
new = list(text)
new[6] = 'W'
''.join(new)
Which is pretty slow compared to 'Method 2'
timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000)
1.0411581993103027
Method 2 (FAST METHOD)
Given by this answer
text = 'abcdefg'
text = text[:1] + 'Z' + text[2:]
Which is much faster:
timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
0.34651994705200195
Method 3:
Byte array:
timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000)
1.0387420654296875
To hide the prompt set xls.DisplayAlerts = False
ConflictResolution
is not a true
or false
property, it should be xlLocalSessionChanges
Note that this has nothing to do with displaying the Overwrite prompt though!
Set xls = CreateObject("Excel.Application")
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"
wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
wb.Close (True)
Thankyou Frank.i got the idea. Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
The following also works:
cd "${0%/*}"
The syntax is thoroughly described in this StackOverflow answer.
Don't forget to implement Serializable in every class your object will use like a list of objects. Else your app will crash.
Example:
public class City implements Serializable {
private List<House> house;
public List<House> getHouse() {
return house;
}
public void setHouse(List<House> house) {
this.house = house;
}}
Then House needs to implements Serializable as so :
public class House implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}}
Then you can use:
Bundle bundle = new Bundle();
bundle.putSerializable("city", city);
intent.putExtras(bundle);
And retreive it with:
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
City city = (City)bundle.getSerializable("city");
There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e.
The number of sessions the database was configured to allow
SELECT name, value
FROM v$parameter
WHERE name = 'sessions'
The number of sessions currently active
SELECT COUNT(*)
FROM v$session
As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM.
this will help all of you to find your own correct details use
npm ls dist-tag
this will then show the correct info so you don't guess the version file location etc
enjoy :)
Convert the List
in to String
and check whether the Strings are same or not
import java.util.ArrayList;
import java.util.List;
/**
* @author Rakesh KR
*
*/
public class ListCompare {
public static boolean compareList(List ls1,List ls2){
return ls1.toString().contentEquals(ls2.toString())?true:false;
}
public static void main(String[] args) {
ArrayList<String> one = new ArrayList<String>();
ArrayList<String> two = new ArrayList<String>();
one.add("one");
one.add("two");
one.add("six");
two.add("one");
two.add("two");
two.add("six");
System.out.println("Output1 :: "+compareList(one,two));
two.add("ten");
System.out.println("Output2 :: "+compareList(one,two));
}
}
Perhaps an analogy will help understanding the difference:
<student id="JonathanSampson" class="Biology Calculus" />
<student id="MarySmith" class="Biology Networking" />
Student ID cards are distinct. No two students on campus will have the same student ID card. However, many students can and will share at least one Class with each other.
It's okay to put multiple students under one Class title, such as Biology. But it's never acceptable to put multiple students under one student ID.
When giving Rules over the school intercom system, you can give Rules to a Class:
"Tomorrow, all students are to wear a red shirt to Biology class."
.Biology {
color: red;
}
Or you can give rules to a Specific Student, by calling his unique ID:
"Jonathan Sampson is to wear a green shirt tomorrow."
#JonathanSampson {
color: green;
}
In this case, Jonathan Sampson is receiving two commands: one as a student in the Biology class, and another as a direct requirement. Because Jonathan was told directly, via the id attribute, to wear a green shirt, he will disregard the earlier request to wear a red shirt.
The more specific selectors win.
Right Click on Project -> Build Path -> Configure Build Path. Check if Maven Dependencies is there in list, if not then update maven project by Right Click on Project -> Maven -> Update Project
Add your MAVEN_HOME
environment variable, edit your Path to include %MAVEN_HOME%/bin
then try creating the project manually with Maven:
mvn archetype:generate -DgroupId=com.program -DartifactId=Program -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
Then import the existing Maven project to Eclipse.
I ran into this problem today, and finding no good solutions for it, I created a module to address it. I was inspired by @fbartho's snippet, but wanted to avoid overwriting the fs module.
The module I wrote is Filequeue, and you use it just like fs:
var Filequeue = require('filequeue');
var fq = new Filequeue(200); // max number of files to open at once
fq.readdir('/Users/xaver/Downloads/xaver/xxx/xxx/', function(err, files) {
if(err) {
throw err;
}
files.forEach(function(file) {
fq.readFile('/Users/xaver/Downloads/xaver/xxx/xxx/' + file, function(err, data) {
// do something here
}
});
});
Similar to the selected answer, a table source can be used, in this case a derived query:
delete from dd
from (
select top 1 *
from my_table
) dd
Feel free to add orderbys and conditions.
For the next example, I'll assume that the restriction on 'where' is due to not wanting to select a row based on its values. So assuming that we want to delete a row based on position (in this case the first position):
delete from dd
from (
select
*,
row = row_number() over (order by (select 1))
from my_table
) dd
where row = 1
Note that the (select 1) makes it the sort order that the tables or indexes are in. You can replace that with a newid to get fairly random rows.
You can also add a partition by to delete the top row of each color, for example.
<?php
function generate_thumb_now($field_name = '',$target_folder ='',$file_name = '', $thumb = FALSE, $thumb_folder = '', $thumb_width = '',$thumb_height = ''){
//folder path setup
$target_path = $target_folder;
$thumb_path = $thumb_folder;
//file name setup
$filename_err = explode(".",$_FILES[$field_name]['name']);
$filename_err_count = count($filename_err);
$file_ext = $filename_err[$filename_err_count-1];
if($file_name != '')
{
$fileName = $file_name.'.'.$file_ext;
}
else
{
$fileName = $_FILES[$field_name]['name'];
}
//upload image path
$upload_image = $target_path.basename($fileName);
//upload image
if(move_uploaded_file($_FILES[$field_name]['tmp_name'],$upload_image))
{
//thumbnail creation
if($thumb == TRUE)
{
$thumbnail = $thumb_path.$fileName;
list($width,$height) = getimagesize($upload_image);
$thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
switch($file_ext){
case 'jpg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'jpeg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'png':
$source = imagecreatefrompng($upload_image);
break;
case 'gif':
$source = imagecreatefromgif($upload_image);
break;
default:
$source = imagecreatefromjpeg($upload_image);
}
imagecopyresized($thumb_create, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width,$height);
switch($file_ext){
case 'jpg' || 'jpeg':
imagejpeg($thumb_create,$thumbnail,100);
break;
case 'png':
imagepng($thumb_create,$thumbnail,100);
break;
case 'gif':
imagegif($thumb_create,$thumbnail,100);
break;
default:
imagejpeg($thumb_create,$thumbnail,100);
}
}
return $fileName;
}
else
{
return false;
}
}
if(!empty($_FILES['image']['name'])){
$upload_img = generate_thumb_now('image','uploads/','',TRUE,'uploads /thumbs/','400','320');
//full path of the thumbnail image
$thumb_src = 'uploads/thumbs/'.$upload_img;
//set success and error messages
$message = $upload_img?"<span style='color:#008000;'>Image thumbnail created successfully.</span>":"<span style='color:#F00000;'>Some error occurred, please try again.</span>";
}else{
//if form is not submitted, below variable should be blank
$thumb_src = '';
$message = '';
}
?>
<html>
<head>Image upload and generate thumbnail</head>
<body>
<div class="messages"><?php echo $message; ?></div>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php if($thumb_src != ''){ ?>
<div class="gallery">
<ul>
<li><img src="<?php echo $thumb_src; ?>" alt=""></li>
</ul>
</div>
<?php } ?>
</body>
</html>
This works for me:
import SwiftyJSON
extension JSON {
mutating func appendIfKeyValuePair(key: String, value: Any){
if var dict = self.dictionaryObject {
dict[key] = value
self = JSON(dict)
}
}
}
Usage:
var data: JSON = []
data.appendIfKeyValuePair(key: "myKey", value: "myValue")
Install the extension "Code Runner". Check if you can compile your program with csc
(ex.: csc hello.cs
). The command csc
is shipped with Mono. Then add this to your VS Code user settings:
"code-runner.executorMap": {
"csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
// "csharp": "echo '# calling dotnet run\n' && dotnet run"
}
Open your C# file and use the execution key of Code Runner.
Edit: also added dotnet run
, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console
, dotnet restore
).
An idea could be to use the optgroup. In my case found it better than the disabled approach. It's less confusing for the user than seeing the disabled option I think.
<select id="q1" v-model="selected" v-on:change="setCPost1(selected)">
<option value="0"></option>
<template
v-for="(child, idx) in getLevel1"
v-bind:value="child.id"
>
<optgroup v-bind:value="child.id" :key="idx"
:label="child.label"
v-if="child.label_line_two"
>
</optgroup>
<option v-bind:value="child.id" :key="idx" v-if="!child.label_line_two"
>
{{ child.label }}
</option>
<option v-bind:value="child.id" :key="idx" v-if="child.label_line_two"
style="font-style:italic">
{{ child.label_line_two }}
</option>
</template>
</select>
An external component sounds cool like Vue Select, but I wanted to stick with the native html select at the moment.
Javascript in a browser only really has a couple of effective scopes: function scope and global scope.
If a variable isn't in function scope, it's in global scope. And global variables are generally bad, so this is a construct to keep a library's variables to itself.
Even though it's convenient to use, it seems like the convert-to-hash solution costs quite a lot of performance, which was an issue for me.
#!/usr/bin/perl
use Benchmark;
my @list;
for (1..10_000) {
push @list, $_;
}
timethese(10000, {
'grep' => sub {
if ( grep(/^5000$/o, @list) ) {
# code
}
},
'hash' => sub {
my %params = map { $_ => 1 } @list;
if ( exists($params{5000}) ) {
# code
}
},
});
Output of benchmark test:
Benchmark: timing 10000 iterations of grep, hash...
grep: 8 wallclock secs ( 7.95 usr + 0.00 sys = 7.95 CPU) @ 1257.86/s (n=10000)
hash: 50 wallclock secs (49.68 usr + 0.01 sys = 49.69 CPU) @ 201.25/s (n=10000)
I tried proposed solution and forward slash in the file name did not work for me, example: ...().getResourceAsStream("/my.properties"); null was returned
Removing the slash worked: ....getResourceAsStream("my.properties");
Here is from doc API: Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
HTML:
<div id="container" class="blog-pager">
<div id="left">Left</div>
<div id="right">Right</div>
<div id="center">Center</div>
</div>
CSS:
#container{width:98%; }
#left{float:left;}
#center{text-align:center;}
#right{float:right;}
text-align:center;
gives perfect centre align.
You would use the Take(N) method.
if(!arrayName[index]){
// do stuff
}
Usign fs with node.
var fs = require('fs');
try {
var data = fs.readFileSync('file.txt', 'utf8');
console.log(data.toString());
} catch(e) {
console.log('Error:', e.stack);
}
I use this statement in Django to convert an unaware time to an aware:
from django.utils import timezone
dt_aware = timezone.make_aware(dt_unaware, timezone.get_current_timezone())
Include in the GROUP BY
clause all SELECT
expressions that are not group function arguments.
I like the "querystring" syntax for argument passing, especially when there are a lot of arguments to be passed.
Example:
rake "mytask[width=10&height=20]"
The "querystring" being:
width=10&height=20
Warning: note that the syntax is rake "mytask[foo=bar]"
and NOT rake mytask["foo=bar"]
When parsed inside the rake task using Rack::Utils.parse_nested_query
, we get a Hash
:
=> {"width"=>"10", "height"=>"20"}
(The cool thing is that you can pass hashes and arrays, more below)
This is how to achieve this:
require 'rack/utils'
task :mytask, :args_expr do |t,args|
args.with_defaults(:args_expr => "width=10&height=10")
options = Rack::Utils.parse_nested_query(args[:args_expr])
end
Here's a more extended example that I'm using with Rails in my delayed_job_active_record_threaded gem:
bundle exec rake "dj:start[ebooks[workers_number]=16&ebooks[worker_timeout]=60&albums[workers_number]=32&albums[worker_timeout]=120]"
Parsed the same way as above, with an environment dependency (in order load the Rails environment)
namespace :dj do
task :start, [ :args_expr ] => :environment do |t, args|
# defaults here...
options = Rack::Utils.parse_nested_query(args[:args_expr])
end
end
Gives the following in options
=> {"ebooks"=>{"workers_number"=>"16", "worker_timeout"=>"60"}, "albums"=>{"workers_number"=>"32", "worker_timeout"=>"120"}}
You forgot the #
on the id selector:
if ($("#EventStartTimeMin").val() === "") {
// ...
}
Try JadClipse.It will open all your .class file. Add library to your project and when you try to open any object declared in the lib file it will open just like your .java file.
In eclipse->help-> marketplace -> go to popular tab. There you can find plugins for the same.
Update: For those who are unable to find above plug-in, try downloading this: https://github.com/java-decompiler/jd-eclipse/releases/download/v1.0.0/jd-eclipse-site-1.0.0-RC2.zip
Then import it into Eclipse.
If you have issues importing above plug-in, refer: How to install plugin for Eclipse from .zip
Furthermore, as said in file_put_contents man page
in php.net
, beware of naming issues.
file_put_contents($dir."/file.txt", "hello");
may not work (even though it is correct on syntax), but
file_put_contents("$dir/file.txt", "hello");
works. I experienced this on different php installed servers.
Steve's reply is definitely the correct technique but it should be refactored so that your installpath variable is in a separate environment script where all such declarations are made.
Then all scripts source that script and should installpath change, you only need to change it in one location. Makes things more, er, futureproof. God I hate that word! (-:
BTW You should really refer to the variable using ${installpath} when using it in the way shown in your example:
. ${installpath}/incl.sh
If the braces are left out, some shells will try and expand the variable "installpath/incl.sh"!
The simplest way is:
selectElement.add(new Option('Text', 'value'));
Yes, that simple. And it works even in IE8. And has other optional parameters.
See docs:
A short and sweet solution, using ES6:
document.querySelectorAll('.input')
.forEach(input => input.addEventListener('focus', this.onInputFocus));
My problem was in the called activity when it tries to return to the previous activity by "finishing." I was incorrectly setting the intent. The following code is Kotlin.
I was doing this:
intent.putExtra("foo", "bar")
finish()
When I should have been doing this:
val result = Intent()
result.putExtra("foo", "bar")
setResult(Activity.RESULT_OK, result)
finish()
I just had this issue, and was able to work around it.
First, connect to the MySQL database with an older client that doesn't mind old_passwords. Connect using the user that your script will be using.
Run these queries:
SET SESSION old_passwords=FALSE;
SET PASSWORD = PASSWORD('[your password]');
In your PHP script, change your mysql_connect function to include the client flag 1:
define('CLIENT_LONG_PASSWORD', 1);
mysql_connect('[your server]', '[your username]', '[your password]', false, CLIENT_LONG_PASSWORD);
This allowed me to connect successfully.
Edit: as per Garland Pope's comment, it may not be necessary to set CLIENT_LONG_PASSWORD manually any more in your PHP code as of PHP 5.4!
Edit: courtesy of Antonio Bonifati, a PHP script to run the queries for you:
<?php const DB = [ 'host' => '...', # localhost may not work on some hosting
'user' => '...',
'pwd' => '...', ];
if (!mysql_connect(DB['host'], DB['user'], DB['pwd'])) {
die(mysql_error());
} if (!mysql_query($query = 'SET SESSION old_passwords=FALSE')) {
die($query);
} if (!mysql_query($query = "SET PASSWORD = PASSWORD('" . DB['pwd'] . "')")) {
die($query);
}
echo "Excellent, mysqli will now work";
?>
I was also facing this problem for some time but I realized it's not because of dialog
in my case it's because of ActionMode
. So if you are trying to finish activity when an ActionMode
is open it will cause this problem. In your activity's onPause
finish the action mode.
private ActionMode actionMode;
@Override
public void onActionModeStarted(ActionMode mode) {
super.onActionModeStarted(mode);
actionMode = mode;
}
@Override
protected void onPause() {
super.onPause();
if (actionMode != null) actionMode.finish();
}
Try declaring the unit of width:
e1.style.width = "400px"; // width in PIXELS
I see how this would work, what would be the process to create a dialog box that allows the user name the folder and place it where you want to.
Cheers
I think you're confused from looking at C++ enumerators. Java enumerators are different.
This would be the code if you are used to C/C++ enums:
public class TestEnum {
enum ids {
OPEN,
CLOSE,
OTHER;
public final int value = 100 + ordinal();
};
public static void main(String arg[]) {
System.out.println("OPEN: " + ids.OPEN.value);
System.out.println("CLOSE: " + ids.CLOSE.value);
System.out.println("OTHER: " + ids.OTHER.value);
}
};
// Prepared By Muhammad Mubashir.
// 26, August, 2011.
// Chnage Back Ground Image of Activity.
package com.ChangeBg_01;
import com.ChangeBg_01.R;
import android.R.color;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ChangeBg_01Activity extends Activity
{
TextView tv;
int[] arr = new int[2];
int i=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
arr[0] = R.drawable.icon1;
arr[1] = R.drawable.icon;
// Load a background for the current screen from a drawable resource
//getWindow().setBackgroundDrawableResource(R.drawable.icon1) ;
final Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
//tv.append("Hello World");
if(i== 2){
i=0;
}
getWindow().setBackgroundDrawableResource(arr[i]);
handler.postDelayed(this, 1000);
i++;
}
};
handler.postDelayed(r, 1000);
Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true)
{
if(i== 2){
//finish();
i=0;
}
sleep(1000);
handler.post(r);
//i++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
}
/*android:background="#FFFFFF"*/
/*
ImageView imageView = (ImageView) findViewById(R.layout.main);
imageView.setImageResource(R.drawable.icon);*/
// Now get a handle to any View contained
// within the main layout you are using
/* View someView = (View)findViewById(R.layout.main);
// Find the root view
View root = someView.getRootView();*/
// Set the color
/*root.setBackgroundColor(color.darker_gray);*/
I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.
Role attribute mainly improve accessibility for people using screen readers. For several cases we use it such as accessibility, device adaptation,server-side processing, and complex data description. Know more click: https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute.
You can also do it like this
public Map<Boolean, List<Student>> getpartitionMap(List<Student> studentsList) {
List<Predicate<Student>> allPredicates = getAllPredicates();
Predicate<Student> compositePredicate = allPredicates.stream()
.reduce(w -> true, Predicate::and)
Map<Boolean, List<Student>> studentsMap= studentsList
.stream()
.collect(Collectors.partitioningBy(compositePredicate));
return studentsMap;
}
public List<Student> getValidStudentsList(Map<Boolean, List<Student>> studentsMap) throws Exception {
List<Student> validStudentsList = studentsMap.entrySet()
.stream()
.filter(p -> p.getKey() == Boolean.TRUE)
.flatMap(p -> p.getValue().stream())
.collect(Collectors.toList());
return validStudentsList;
}
public List<Student> getInValidStudentsList(Map<Boolean, List<Student>> studentsMap) throws Exception {
List<Student> invalidStudentsList =
partionedByPredicate.entrySet()
.stream()
.filter(p -> p.getKey() == Boolean.FALSE)
.flatMap(p -> p.getValue().stream())
.collect(Collectors.toList());
return invalidStudentsList;
}
With flatMap
you will get just List<Student>
instead of List<List<Student>>
.
Thanks
You can do either…
$qb->where('e.fecha BETWEEN :monday AND :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));
or…
$qb->where('e.fecha > :monday')
->andWhere('e.fecha < :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));
If you have an IBOutlet to a UIImageView already, then all you have to do is grab an image and call setImage on the receiver (UIImageView). Two examples of grabbing an image are below. One from the Web, and one you add to your Resources folder in Xcode.
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
or
UIImage *image = [UIImage imageNamed: @"cell.png"];
Once you have an Image you can then set UIImageView:
[imageView setImage:image];
The line above assumes imageView is your IBOutlet.
That's it! If you want to get fancy you can add the image to an UIView and then add transitions.
P.S. Memory management not included.
Maybe placing the jquery.ui.widget.js
as second after jquery.ui.core.js
.
You can always use strtotime to minus the number of days from the current date:
$users = Users::where('status_id', 'active')
->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
->get();
foreach ( int number in numbers )
{
if ( number < 0 )
{
continue;
}
//otherwise process number
}
Here is a shorter implementation comparing to @Jav_Rock's
/**
* Round to certain number of decimals
*
* @param d
* @param decimalPlace the numbers of decimals
* @return
*/
public static float round(float d, int decimalPlace) {
return BigDecimal.valueOf(d).setScale(decimalPlace,BigDecimal.ROUND_HALF_UP).floatValue();
}
System.out.println(round(2.345f,2));//two decimal digits, //2.35
Is this what you're looking for?
if (request instanceof HttpServletRequest) {
String url = ((HttpServletRequest)request).getRequestURL().toString();
String queryString = ((HttpServletRequest)request).getQueryString();
}
To Reconstruct:
System.out.println(url + "?" + queryString);
Info on HttpServletRequest.getRequestURL()
and HttpServletRequest.getQueryString()
.
As inspiredlife explained, you can figure out whats happening using mail
command.
If you don't want to delete bunch of unrelated / auto-generated messages one by one (like me), simply run the command below to get rid of all messages:
echo -n > /var/mail/yourusername
Looks like your form is submitting which is the default behaviour, you can stop it with this:
<form action="" method="post" onsubmit="completeAndRedirect();return false;">
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float percent = 0.7f;
int seventyVolume = (int) (maxVolume*percent);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);
From PowerShell you can use the .NET [System.Environment]::SetEnvironmentVariable()
method:
To remove a user environment variable named FOO
:
[Environment]::SetEnvironmentVariable('FOO', $null, 'User')
Note that $null
is used to better signal the intent to remove the variable, though technically it is effectively the same as passing ''
in this case.
To remove a system (machine-level) environment variable named FOO
- requires elevation (must be run as administrator):
[Environment]::SetEnvironmentVariable('FOO', $null, 'Machine')
Aside from faster execution, the advantage over the reg.exe
-based method is that other applications are notified of the change, via a WM_SETTINGCHANGE
message (though not all applications listen to that message).
The simplest way is:
make foo=bar target
Then in your makefile you can refer to $(foo)
. Note that this won't propagate to sub-makes automatically.
If you are using sub-makes, see this article: Communicating Variables to a Sub-make
you can check if your session has a row in V$TRANSACTION
(obviously that requires read privilege on this view):
SQL> SELECT COUNT(*)
FROM v$transaction t, v$session s, v$mystat m
WHERE t.ses_addr = s.saddr
AND s.sid = m.sid
AND ROWNUM = 1;
COUNT(*)
----------
0
SQL> insert into a values (1);
1 row inserted
SQL> SELECT COUNT(*)
FROM v$transaction t, v$session s, v$mystat m
WHERE t.ses_addr = s.saddr
AND s.sid = m.sid
AND ROWNUM = 1;
COUNT(*)
----------
1
SQL> commit;
Commit complete
SQL> SELECT COUNT(*)
FROM v$transaction t, v$session s, v$mystat m
WHERE t.ses_addr = s.saddr
AND s.sid = m.sid
AND ROWNUM = 1;
COUNT(*)
----------
0
After Saving $data->save()
. all data is pushed inside $data
. As this is an object and the current row is just saved recently inside $data
. so last insertId
will be found inside $data->id
.
Response code will be:
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
Before reading this answer, bear in mind that there is another answer below, from Roman Kh, which uses
numpy.cumsum
and is MUCH MUCH FASTER than this one.
Best One common way to apply a moving/sliding average (or any other sliding window function) to a signal is by using numpy.convolve()
.
def movingaverage(interval, window_size):
window = numpy.ones(int(window_size))/float(window_size)
return numpy.convolve(interval, window, 'same')
Here, interval is your x
array, and window_size
is the number of samples to consider. The window will be centered on each sample, so it takes samples before and after the current sample in order to calculate the average. Your code would become:
plot(x,y)
xlim(0,1000)
x_av = movingaverage(interval, r)
plot(x_av, y)
xlabel("Months since Jan 1749.")
ylabel("No. of Sun spots")
show()
Hope this helps!
I'd be cautious as dismissing something as a bad idea because it is slow. If it is a part of the code that does not take much time to execute then the slowness is irrelevant. I just used the following code:
for (ic in 1:(dim(centroid)[2]))
{
cluster[[ic]]=matrix(,nrow=2,ncol=0)
}
# code to identify cluster=pindex[ip] to which to add the point
if(pdist[ip]>-1)
{
cluster[[pindex[ip]]]=cbind(cluster[[pindex[ip]]],points[,ip])
}
for a problem that ran in less than 1 second.
let session = URLSession.shared
let url = "http://...."
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
var params :[String: Any]?
params = ["Some_ID" : "111", "REQUEST" : "SOME_API_NAME"]
do{
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
if let response = response {
let nsHTTPResponse = response as! HTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
print ("status code = \(statusCode)")
}
if let error = error {
print ("\(error)")
}
if let data = data {
do{
let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
print ("data = \(jsonResponse)")
}catch _ {
print ("OOps not good JSON formatted response")
}
}
})
task.resume()
}catch _ {
print ("Oops something happened buddy")
}
raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
works, however it results in a Python warning of
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value
instead
I would guess this is due to some chaining indexing.
Here is another version using String Prototype. Enjoy!
String.prototype.replaceAll = function(obj) {
let finalString = '';
let word = this;
for (let each of word){
for (const o in obj){
const value = obj[o];
if (each == o){
each = value;
}
}
finalString += each;
}
return finalString;
};
'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"
I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding
style="position: relative; bottom: 0px"
to your Widget2 tag. Also try:
style="position: absolute; bottom: 0px"
if you want to snap your widget to the bottom of the screen.
I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.
Regarding [Console]::WriteLine() - you should use it if you are going to use pipelines in CMD (not in powershell). Say you want your ps1 to stream a lot of data to stdout, and some other utility to consume/transform it. If you use Write-Host in the script it will be much slower.
For WINDOWS users: FILE-->SETTingS-->EDITOR-->FONT.
If your are in Visual Studio 2012 or later this has an additional setting 'SDL checks' Under Property Pages -> C/C++ -> General
Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.
It defaults to YES - For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.
One thing that I found quite helpful to use to print all images :
_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
ax.imshow(img)
plt.show()
You should go to Control Panel -> Programs and Features, find Microsoft Visual Studio 2015 and select "Change". Visual Studio 2015 setup will start. Select "Modify".
In Visual Studio components list, open the list of sub-items and select "ClickOnce Publication Tools" and "Windows 10 SDK" too.
var trLength = jQuery('#tablebodyID >tr').length;
--
Integers (without decimal):
"{:,d}".format(1234567)
--
Floats (with decimal):
"{:,.2f}".format(1234567)
where the number before f
specifies the number of decimal places.
--
Bonus
Quick-and-dirty starter function for the Indian lakhs/crores numbering system (12,34,567):
Bit late to the party but this simple solution worked for me:
function chainError(err) {
return Promise.reject(err)
};
stepOne()
.then(stepTwo, chainError)
.then(stepThreee, chainError);
This allows you to break out of the chain.
A utility table in Oracle with only 1 row and 1 column. It is used to perform a number of arithmetic operations and can be used generally where one needs to generate a known output.
SELECT * FROM dual;
will give a single row, with a single column named "DUMMY" and a value of "X" as shown here:
DUMMY ----- X
A very simple way is to use Formatter
(see date time conversions) or more directly String.format
as in
String.format("%tR", new Date())
If you are using Sass in a Rails project, the sass-rails gem, https://github.com/rails/sass-rails, features glob importing.
@import "foo/*" // import all the files in the foo folder
@import "bar/**/*" // import all the files in the bar tree
To answer the concern in another answer "If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity."
Some would argue that organizing your files into directories can REDUCE complexity.
My organization's project is a rather complex app. There are 119 Sass files in 17 directories. These correspond roughly to our views and are mainly used for adjustments, with the heavy lifting being handled by our custom framework. To me, a few lines of imported directories is a tad less complex than 119 lines of imported filenames.
To address load order, we place files that need to load first – mixins, variables, etc. — in an early-loading directory. Otherwise, load order is and should be irrelevant... if we are doing things properly.
For some who wants to reset the form can also use type="reset"
inside any form.
<form action="/action_page.php">
Email: <input type="text" name="email"><br>
Pin: <input type="text" name="pin" maxlength="4"><br>
<input type="reset" value="Reset">
<input type="submit" value="Submit">
</form>
describe formatted <table_name>;
inside hive shell.
Notice the "Location" value that shows the location of the table.
What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:
p = [q.index(v) if v in q else 99999 for v in vm]
When using a list comprehension, you do not call list.append
because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for
keyword, which in this case is q.index(v) if v in q else 99999
. Incidentially, if you do use list.append
inside a comprehension, then you will get a list of None
values because that is what the append
method always returns.
If you still need to use the HTTP Module you need to configure it (.NET 4.0 framework) as follows:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="MyModule" type="[Namespace].[Class], [assembly]"/>
</modules>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
You can also use following code to return date diff by round fractions up $date1 = $duedate; // assign due date echo $date2 = date("Y-m-d"); // current date $ts1 = strtotime($date1); $ts2 = strtotime($date2); $seconds_diff = $ts1 - $ts2; echo $datediff = ceil(($seconds_diff/3600)/24); // return in days
If you use floor method of php instead of ceil it will return you the round fraction down. Please check the difference here, some times if your staging servers timezone is different then the live site time zone in that case you may get different results so change the conditions accordingly.
<script>
function dowiki(place) {
var URL = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=';
URL += "&titles=" + place;
URL += "&rvprop=content";
URL += "&callback=?";
$.getJSON(URL, function (data) {
var obj = data.query.pages;
var ob = Object.keys(obj)[0];
console.log(obj[ob]["extract"]);
try{
document.getElementById('Label11').textContent = obj[ob]["extract"];
}
catch (err) {
document.getElementById('Label11').textContent = err.message;
}
});
}
</script>
Generally speaking, people refer to an application's presentation layer as its front end, its persistence layer (database, usually) as the back end, and anything between as middle tier. This set of ideas is often referred to as 3-tier architecture. They let you separate your application into more easily comprehensible (and testable!) chunks; you can also reuse lower-tier code more easily in higher tiers.
Which code is part of which tier is somewhat subjective; graphic designers tend to think of everything that isn't presentation as the back end, database people think of everything in front of the database as the front end, and so on.
Not all applications need to be separated out this way, though. It's certainly more work to have 3 separate sub-projects than it is to just open index.php and get cracking; depending on (1) how long you expect to have to maintain the app (2) how complex you expect the app to get, you may want to forgo the complexity.
You can use the USER root command in your Dockerfile.
This should be the right answer. Cleanest and simplest:
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}
If I have understood your question correctly you want to display one particular cell of your populated datatable? This what I used to display the given cell in my DataGrid.
var s = dataGridView2.Rows[i].Cells[j].Value;
txt_Country.Text = s.ToString();
Hope this helps
Javascript:
document.getElementsByTagName("html")[0].setAttribute("oncontextmenu", "return false");
In My case, I am running a local Django backend in IP 127.0.0.1:8000
with Expo start.
Just make sure you have the server in public domain
not hosted lcoally on your machine
Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event()
and data pointers to a framework function watch_events()
(for example). When an event happens, your function is called with your data and some event-specific data.
Callbacks are also used in GUI programming. The GTK+ tutorial has a nice section on the theory of signals and callbacks.
Management studio creates scripts like:
insert table1 (foodate) values(CAST(N'2012-06-18 10:34:09.000' AS DateTime))
try this
lblMsg.Text = @"Your search result for <b style=""color:green;"">" + txtCode.Text.Trim() + "</b> ";
Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:
Using ImageLocation property of the PictureBox like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "../SamuderaJayaMotor.png";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
Using an image from the web like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.
Using the accepted answer you have to access each record by using Customers[i].customer
, and you need an extra CustomerJson
class, which is a little annoying. If you don't want to do that, you can use the following:
public class CustomerList
{
[JsonConverter(typeof(MyListConverter))]
public List<Customer> customer { get; set; }
}
Note that I'm using a List<>
, not an Array. Now create the following class:
class MyListConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var list = Activator.CreateInstance(objectType) as System.Collections.IList;
var itemType = objectType.GenericTypeArguments[0];
foreach (var child in token.Values())
{
var childToken = child.Children().First();
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(childToken.CreateReader(), newObject);
list.Add(newObject);
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
You can also use the RestSharp library for example
var userName = "myuser";
var password = "mypassword";
var host = "170.170.170.170:333";
var client = new RestClient("https://" + host + "/method1");
client.Authenticator = new HttpBasicAuthenticator(userName, password);
var request = new RestRequest(Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json","{}",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
You can turn off foreign key checks:
SET FOREIGN_KEY_CHECKS = 0;
/* DO WHAT YOU NEED HERE */
SET FOREIGN_KEY_CHECKS = 1;
Please make sure to NOT use this on production and have a backup.
The official solution (and others) were incomplete when I first visited, so I came back, years later, to post this alternate approach in case any others wound up here intending to use a public/private key-pair:
Execute this from the target backup machine, which pulls from source to target backup
rsync -av --delete -e 'ssh -p 59333 -i /home/user/.ssh/id_rsa' [email protected]:/home/user/Server/ /home/keith/Server/
Execute this from the source machine, which sends from source to target backup
rsync -av --delete -e 'ssh -p 59333 -i /home/user/.ssh/id_rsa' /home/user/Server/ [email protected]:/home/user/Server/
And, if you are not using an alternate port for ssh, then consider the more elegant examples below:
Execute this from the target backup machine, which pulls from source to target backup:
sudo rsync -avi --delete [email protected]:/var/www/ /media/sdb1/backups/www/
Execute this from the source machine, which sends from source to target backup:
sudo rsync -avi --delete /media/sdb1/backups/www/ [email protected]:/var/www/
If you are still getting prompted for a password, then you need to check your ssh configuration in /etc/ssh/sshd_config
and verify that the users in source and target each have the others' respective public ssh key by sending each over with ssh-copy-id [email protected]
.
(Again, this is for using ssh key-pairs without a password, as an alternate approach, and not for passing the password over via a file.)
I compiled python3.7 from the source code, with the following command
./configure --prefix=/opt/python3.7.4 --with-ssl
make
make install
after pip3.7 install jupyter
I found the executable is under /opt/python3.7.4/bin
check my answer here Missing sqlite3 after Python3 compile to get more detail comping python3.7 and pip under ubuntu14.04
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
There's one more difference. class
can be used to define type properties of computed type only. If you need a stored type property use static
instead.
I wrote a bash script that should automate the process written by Yakov Fain below. It can be called like ./removeComponent myComponentName This has only been tested with Angular 6
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Input a component to delete"
exit 1
fi
# finds folder with component name and deletes
find . -type d -name $1 | xargs rm -rf
# removes lines referencing the component from app.module.ts
grep -v $1 app.module.ts > temp
mv temp app.module.ts
componentName=$1
componentName+="Component"
grep -v -i $componentName app.module.ts > temp
mv temp app.module.ts
Convert by Number Class
:-
Eg:
var n = Number("103");
console.log(n+1)
Output: 104
Note:- Number
is class. When we pass string, then constructor of Number class
will convert it.
If you want list of database
SELECT datname FROM pg_database WHERE datistemplate = false;
If you want list of tables from current pg installation of all databases
SELECT table_schema,table_name FROM information_schema.tables
ORDER BY table_schema,table_name;
I struggled with a similar problem for hours. It then turned out that jQuery was included twice, once by the program that I was adding a jQuery function to and once by our in-house debugger.
Through this you can get absolute path of any file located in any directory.
File.join(Dir.pwd,'some-dir','some-file-name')
This will return
=> "/User/abc/xyz/some-dir/some-file-name"
Try this :
int smallest = Integer.MAX_VALUE;
for(int i=0;i<n;i++)
{
num=input.nextInt();
if(num>large)
{
large=num;
}
if(num<smallest){
smallest=num;
}
<object>.__class__.__name__
In the spirit of a DVCS (as in "Distributed"), you don't cancel something you have published:
Pull requests are essentially patches you have send (normally by email, here by GitHub webapp), and you wouldn't cancel an email either ;)
But since the GitHub Pull Request system also includes a discussion section, that would be there that you could voice your concern to the recipient of those changes, asking him/her to disregards 29 of your 30 commits.
Finally, remember:
That being said, since January 2011 ("Refreshed Pull Request Discussions"), and mentioned in the answer above, you can close a pull request in the comments.
Look for that "Comment and Close" button at the bottom of the discussion page:
Example for Spring Boot. My WSDL-file is in Resources in "wsdl" folder. The path to the WSDL-file is:
resources/wsdl/WebServiceFile.wsdl
To get the path from some method to this file you can do the following:
String pathToWsdl = this.getClass().getClassLoader().
getResource("wsdl\\WebServiceFile.wsdl").toString();
#
is an id selector, used to target a single specific element with a unique id, but . is a class selector used to target multiple elements with a particular class. To put it another way:
#foo {}
will style the single element declared with an attribute id="foo"
.foo {}
will style all elements with an attribute class="foo"
(you can have multiple classes assigned to an element too, just separate them with spaces, e.g. class="foo bar"
)Generally speaking, you use # for styling something you know is only going to appear once, for example, things like high level layout divs such sidebars, banner areas etc.
Classes are used where the style is repeated, e.g. say you head a special form of header for error messages, you could create a style h1.error {}
which would only apply to <h1 class="error">
Another aspect where selectors differ is in their specificity - an id selector is deemed to be more specific than class selector. This means that where styles conflict on an element, the ones defined with the more specific selector will override less specific selectors. For example, given <div id="sidebar" class="box">
any rules for #sidebar
with override conflicting rules for .box
See Selectutorial for more great primers on CSS selectors - they are incredibly powerful, and if your conception is simply that "# is used for DIVs" you'd do well to read up on exactly how to use CSS more effectively.
EDIT: Looks like Selectutorial might have gone to the big website in the sky, so try this archive link instead.
You need to install Team Explorer, it's best to install the version of Team Explorer that matches the version of TFS you are using e.g. if you're using TFS 2010 then install Team Explorer 2010.
2012 version http://www.microsoft.com/en-gb/download/details.aspx?id=30656
2013 version http://www.microsoft.com/en-us/download/details.aspx?id=40776
2019 version https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=TeamExplorer&rel=16
You also might be interested in the TFS power tools. They add some extra command line features (using tfpt.exe
) and also add some extra IDE features.
Try:
git config core.fileMode false
From git-config(1):
core.fileMode Tells Git if the executable bit of files in the working tree is to be honored. Some filesystems lose the executable bit when a file that is marked as executable is checked out, or checks out a non-executable file with executable bit on. git-clone(1) or git-init(1) probe the filesystem to see if it handles the executable bit correctly and this variable is automatically set as necessary. A repository, however, may be on a filesystem that handles the filemode correctly, and this variable is set to true when created, but later may be made accessible from another environment that loses the filemode (e.g. exporting ext4 via CIFS mount, visiting a Cygwin created repository with Git for Windows or Eclipse). In such a case it may be necessary to set this variable to false. See git-update-index(1). The default is true (when core.filemode is not specified in the config file).
The -c
flag can be used to set this option for one-off commands:
git -c core.fileMode=false diff
And the --global
flag will make it be the default behavior for the logged in user.
git config --global core.fileMode false
Changes of the global setting won't be applied to existing repositories.
Additionally, git clone
and git init
explicitly set core.fileMode
to true
in the repo config as discussed in Git global core.fileMode false overridden locally on clone
core.fileMode
is not the best practice and should be used carefully. This setting only covers the executable bit of mode and never the read/write bits. In many cases you think you need this setting because you did something like chmod -R 777
, making all your files executable. But in most projects most files don't need and should not be executable for security reasons.
The proper way to solve this kind of situation is to handle folder and file permission separately, with something like:
find . -type d -exec chmod a+rwx {} \; # Make folders traversable and read/write
find . -type f -exec chmod a+rw {} \; # Make files read/write
If you do that, you'll never need to use core.fileMode
, except in very rare environment.
Hat tip to Adam Bien if you don't want to use createQuery
with a String
and want type safety:
@PersistenceContext EntityManager em; public List<ConfigurationEntry> allEntries() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class); Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class); CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry); TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all); return allQuery.getResultList(); }
http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as
In case you're reading text from the clipboard in a Chrome extension, with 'clipboardRead' permission allowed, you can use the below code:
function readTextFromClipboardInChromeExtension() {
var ta = $('<textarea/>');
$('body').append(ta);
ta.focus();
document.execCommand('paste');
var text = ta.val();
ta.blur();
ta.remove();
return text;
}
Since R version 3.4.0 you can use strcapture()
from the utils package (included with base R installs), binding the output onto the other column(s).
out <- strcapture(
"(.*)_and_(.*)",
as.character(before$type),
data.frame(type_1 = character(), type_2 = character())
)
cbind(before["attr"], out)
# attr type_1 type_2
# 1 1 foo bar
# 2 30 foo bar_2
# 3 4 foo bar
# 4 6 foo bar_2
Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html
It's just a matter of using curl
to trigger a Jenkins job using the git hooks provided by git.
The command
curl http://localhost:8080/job/someJob/build?delay=0sec
can run a Jenkins job, where someJob
is the name of the Jenkins job.
Search for the hooks
folder in your hidden .git folder. Rename the post-commit.sample
file to post-commit
. Open it with Notepad, remove the : Nothing
line and paste the above command into it.
That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.
You need not specify the classes folder. Intellij should be able to load it. You will get this error if "Project Compiler output" is blank.
Just make sure that below value is set: Project Settings -> Project -> Project Compiler output to your projectDir/out folder
The iframe always keeps the parent page, you should use this to detect in which page you are in the iframe:
Html code:
<iframe id="iframe" frameborder="0" scrolling="no" onload="resizeIframe(this)" width="100%" src="www.google.com"></iframe>
Js:
function resizeIframe(obj) {
alert(obj.contentWindow.location.pathname);
}
As Mingyu pointed out, there is a problem in formatting. Other than that, I would strongly recommend not using the Derived class's name while calling super()
since it makes your code inflexible (code maintenance and inheritance issues). In Python 3, Use super().__init__
instead. Here is the code after incorporating these changes :
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type=battery_type
super().__init__(model, color, mpg)
Thanks to Erwin Mayer for pointing out the issue in using __class__
with super()