A png is a bitmap image style and an SVG is a vector-based graphics design which supports bitmaps so it's not as if it would convert the image to vectors, just an image embedded in a vector-based format. You could do this using http://www.inkscape.org/ which is free. It would embed it, however it also has a Live Trace like engine which will try to convert it to paths if you wish (using potrace). See live trace in adobe illustrator (commericial) is an example:
http://graphicssoft.about.com/od/illustrator/ss/sflivetrace.htm
It's go to newline then add spaces to start second line at end of first line
Output
Hello
Goodbye
CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.
So, just as you use InterfaceName i = new ItsImplementation()
, you can use CharSequence cs = new String("string")
or simply CharSequence cs = "string";
You can try this direct VBA
approach which doesn't require HEX editing. It will work for any files (*.xls, *.xlsm, *.xlam ...).
Tested and works on:
Excel 2007
Excel 2010
Excel 2013 - 32 bit version
Excel 2016 - 32 bit version
Looking for 64 bit version? See this answer
I will try my best to explain how it works - please excuse my English.
Please backup your files first!
Create a new xlsm file and store this code in Module1
code credited to Siwtom (nick name), a Vietnamese developer
Option Explicit
Private Const PAGE_EXECUTE_READWRITE = &H40
Private Declare Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As Long, Source As Long, ByVal Length As Long)
Private Declare Function VirtualProtect Lib "kernel32" (lpAddress As Long, _
ByVal dwSize As Long, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long
Private Declare Function GetModuleHandleA Lib "kernel32" (ByVal lpModuleName As String) As Long
Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, _
ByVal lpProcName As String) As Long
Private Declare Function DialogBoxParam Lib "user32" Alias "DialogBoxParamA" (ByVal hInstance As Long, _
ByVal pTemplateName As Long, ByVal hWndParent As Long, _
ByVal lpDialogFunc As Long, ByVal dwInitParam As Long) As Integer
Dim HookBytes(0 To 5) As Byte
Dim OriginBytes(0 To 5) As Byte
Dim pFunc As Long
Dim Flag As Boolean
Private Function GetPtr(ByVal Value As Long) As Long
GetPtr = Value
End Function
Public Sub RecoverBytes()
If Flag Then MoveMemory ByVal pFunc, ByVal VarPtr(OriginBytes(0)), 6
End Sub
Public Function Hook() As Boolean
Dim TmpBytes(0 To 5) As Byte
Dim p As Long
Dim OriginProtect As Long
Hook = False
pFunc = GetProcAddress(GetModuleHandleA("user32.dll"), "DialogBoxParamA")
If VirtualProtect(ByVal pFunc, 6, PAGE_EXECUTE_READWRITE, OriginProtect) <> 0 Then
MoveMemory ByVal VarPtr(TmpBytes(0)), ByVal pFunc, 6
If TmpBytes(0) <> &H68 Then
MoveMemory ByVal VarPtr(OriginBytes(0)), ByVal pFunc, 6
p = GetPtr(AddressOf MyDialogBoxParam)
HookBytes(0) = &H68
MoveMemory ByVal VarPtr(HookBytes(1)), ByVal VarPtr(p), 4
HookBytes(5) = &HC3
MoveMemory ByVal pFunc, ByVal VarPtr(HookBytes(0)), 6
Flag = True
Hook = True
End If
End If
End Function
Private Function MyDialogBoxParam(ByVal hInstance As Long, _
ByVal pTemplateName As Long, ByVal hWndParent As Long, _
ByVal lpDialogFunc As Long, ByVal dwInitParam As Long) As Integer
If pTemplateName = 4070 Then
MyDialogBoxParam = 1
Else
RecoverBytes
MyDialogBoxParam = DialogBoxParam(hInstance, pTemplateName, _
hWndParent, lpDialogFunc, dwInitParam)
Hook
End If
End Function
Paste this code under the above code in Module1 and run it
Sub unprotected()
If Hook Then
MsgBox "VBA Project is unprotected!", vbInformation, "*****"
End If
End Sub
Come back to your VBA Projects and enjoy.
Check out MSDN...
CREATE SCHEMA
: http://msdn.microsoft.com/en-us/library/ms189462.aspx
Then
ALTER SCHEMA
: http://msdn.microsoft.com/en-us/library/ms173423.aspx
Or you can check it on on SO...
Good question - I think the only way to achieve this is to filter the items in the select.
You can do this through a jquery plugin. Check the following link, it describes how to achieve something similar to what you need. Thanks
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
You need to make Tomcat listen to 192.168.1.100 address also.
If you want it to listen to all interfaces (IP-s) just remove "address=" from Connector string in your configuration file and restart Tomcat.
Or just use your IP to listen to that address address=192.168.1.100 in the Connector string
As others have said, use ArrayList
. Here's how:
public class t
{
private List<Integer> x = new ArrayList<Integer>();
public void add(int num)
{
this.x.add(num);
}
}
As you can see, your add
method just calls the ArrayList
's add method. This is only useful if your variable is private (which it is).
Deleting it will do nothing to the original project. Editing it will only edit your fork on your repo page.
In my case, I have several tasks I want to execute in parallel, but I need to do something different with the result of those tasks.
function wait(ms, data) {
console.log('Starting task:', data, ms);
return new Promise(resolve => setTimeout(resolve, ms, data));
}
var tasks = [
async () => {
var result = await wait(1000, 'moose');
// do something with result
console.log(result);
},
async () => {
var result = await wait(500, 'taco');
// do something with result
console.log(result);
},
async () => {
var result = await wait(5000, 'burp');
// do something with result
console.log(result);
}
]
await Promise.all(tasks.map(p => p()));
console.log('done');
And the output:
Starting task: moose 1000
Starting task: taco 500
Starting task: burp 5000
taco
moose
burp
done
It runs successfully the first time, but if I run it again, I keep getting a System.OutOfMemoryException. What are some reasons this could be happening?
Regardless of what the others have said, the error has nothing to do with forgetting to dispose your DBCommand or DBConnection, and you will not fix your error by disposing of either of them.
The error has everything to do with your dataset which contains nearly 600,000 rows of data. Apparently your dataset consumes more than 50% of the available memory on your machine. Clearly, you'll run out of memory when you return another dataset of the same size before the first one has been garbage collected. Simple as that.
You can remedy this problem in a few ways:
Consider returning fewer records. I personally can't imagine a time when returning 600K records has ever been useful to a user. To minimize the records returned, try:
Limiting your query to the first 1000 records. If there are more than 1000 results returned from the query, inform the user to narrow their search results.
If your users really insist on seeing that much data at once, try paging the data. Remember: Google never shows you all 22 bajillion results of a search at once, it shows you 20 or so records at a time. Google probably doesn't hold all 22 bajillion results in memory at once, it probably finds its more memory efficient to requery its database to generate a new page.
If you just need to iterate through the data and you don't need random access, try returning a datareader instead. A datareader only loads one record into memory at a time.
If none of those are an option, then you need to force .NET to free up the memory used by the dataset before calling your method using one of these methods:
Remove all references to your old dataset. Anything holding on to a refenence of your dataset will prevent it from being reclaimed by memory.
If you can't null all the references to your dataset, clear all of the rows from the dataset and any objects bound to those rows instead. This removes references to the datarows and allows them to be eaten by the garbage collector.
I don't believe you'll need to call GC.Collect()
to force a gen cycle. Not only is it generally a bad idea to call GC.Collect()
, because sufficient memory pressure will cause .NET invoke the garbage collector on its own.
Note: calling Dispose on your dataset does not free any memory, nor does it invoke the garbage collector, nor does it remove a reference to your dataset. Dispose is used to clean up unmanaged resources, but the DataSet does not have any unmanaged resources. It only implements IDispoable because it inherents from MarshalByValueComponent, so the Dispose method on the dataset is pretty much useless.
if you are working in the java world - intelliJ idea has also extensive xml support, including xsd generation and samle xml from xsd generation, and with plugins you can get xslt debuggers. - especially nice if you plan to use tools such as jaxb afterwards.
they are two different things..
[]
is declaring an Array:
given, a list of elements held by numeric index.
{}
is declaring a new object:
given, an object with fields with Names and type+value,
some like to think of it as "Associative Array".
but are not arrays, in their representation.
You can read more @ This Article
In the "root" __init__.py
you can also do a
import sys
sys.path.insert(1, '.')
which should make both modules importable.
On my Linux system, the +
and *
registers map to an X11 selection, which can be pasted with the middle mouse button. When :set clipboard=unnamed
and :set clipboard=unnamedplus
are used, then the registers map to the clipboard, and can be pasted with CTRL-V.
The specifics seem to be somewhat configuration and system dependent, so your mileage will definitely vary. It should definitely get you pointed in the right direction, though.
In my cases, I solved the problem when using the labs()
instead of abs()
.
For deleting untracked files:
git clean -f
For deleting untracked directories as well, use:
git clean -f -d
For preventing any cardiac arrest, use
git clean -n -f -d
To extend the given answer with few useful tricks:
var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
bounds.extend(markers[i].getPosition());
}
//center the map to a specific spot (city)
map.setCenter(center);
//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
map.setZoom(15);
}
//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
map.setMaxZoom(15);
map.fitBounds(bounds);
map.setMaxZoom(Null)
}
UPDATE:
Further research in the topic show that fitBounds() is a asynchronic
and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
this.setZoom(map.getZoom()-1);
if (this.getZoom() > 15) {
this.setZoom(15);
}
});
map.fitBounds(bounds);
You'll get it as part of a Visual Studio install (if you included the SDK), or in a standalone SDK install. It'll live somewhere like C:\program files\Microsoft Visual Studio 8\SDK\v2.0\Bin
If you don't already have it, you can download the .NET SDKs from
http://msdn.microsoft.com/en-us/netframework/aa569263.aspx
Complete walkthrough of writing setup.py
scripts here. (with some examples)
If you'd like a real-world example, I could point you towards the setup.py
scripts of a couple major projects. Django's is here, pyglet's is here. You can just browse the source of other projects for a file named setup.py for more examples.
These aren't simple examples; the tutorial link I gave has those. These are more complex, but also more practical.
You can do that without the terminal. You just need to create a branch with the new name, and remove the old after.
Create a branch
In your repository’s branch selector, just start typing a new branch name. It’ll give you the option to create a new branch:
It’ll branch off of your current context. For example, if you’re on the bugfix branch, it’ll create a new branch from bugfix instead of master. Looking at a commit or a tag instead? It’ll branch your code from that specific revision.
Delete a branch
You’ll also see a delete button in your repository’s Branches page:
As an added bonus, it’ll also give you a link to the branch’s Pull Request, if it has one.
I just copied this content from: Create and delete branches
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.*;
import java.io.BufferedReader;
import java.io.FileReader;
public class AESFile
{
private static String algorithm = "AES";
private static byte[] keyValue=new byte[] {'0','2','3','4','5','6','7','8','9','1','2','3','4','5','6','7'};// your key
// Performs Encryption
public static String encrypt(String plainText) throws Exception
{
Key key = generateKey();
Cipher chiper = Cipher.getInstance(algorithm);
chiper.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = chiper.doFinal(plainText.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
// Performs decryption
public static String decrypt(String encryptedText) throws Exception
{
// generate key
Key key = generateKey();
Cipher chiper = Cipher.getInstance(algorithm);
chiper.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedText);
byte[] decValue = chiper.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
//generateKey() is used to generate a secret key for AES algorithm
private static Key generateKey() throws Exception
{
Key key = new SecretKeySpec(keyValue, algorithm);
return key;
}
// performs encryption & decryption
public static void main(String[] args) throws Exception
{
FileReader file = new FileReader("C://myprograms//plaintext.txt");
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while(line!= null)
{
text += line;
line = reader.readLine();
}
reader.close();
System.out.println(text);
String plainText = text;
String encryptedText = AESFile.encrypt(plainText);
String decryptedText = AESFile.decrypt(encryptedText);
System.out.println("Plain Text : " + plainText);
System.out.println("Encrypted Text : " + encryptedText);
System.out.println("Decrypted Text : " + decryptedText);
}
}
If you want to always prune
when you fetch
, I can suggest to use Aliases.
Just type git config -e
to open your editor and change the configuration for a specific project and add a section like
[alias]
pfetch = fetch --prune
the when you fetch with git pfetch
the prune will be done automatically.
So I see many possibilities to achieve this.
string text = "Foobar-test";
Regex Match everything till the first "-"
Match result = Regex.Match(text, @"^.*?(?=-)");
^
match from the start of the string.*?
match any character (.
), zero or more times (*
) but as less as possible (?
)(?=-)
till the next character is a "-" (this is a positive look ahead)Regex Match anything that is not a "-" from the start of the string
Match result2 = Regex.Match(text, @"^[^-]*");
[^-]*
matches any character that is not a "-" zero or more timesRegex Match anything that is not a "-" from the start of the string till a "-"
Match result21 = Regex.Match(text, @"^([^-]*)-");
Will only match if there is a dash in the string, but the result is then found in capture group 1.
Split on "-"
string[] result3 = text.Split('-');
Result is an Array the part before the first "-" is the first item in the Array
Substring till the first "-"
string result4 = text.Substring(0, text.IndexOf("-"));
Get the substring from text from the start till the first occurrence of "-" (text.IndexOf("-")
)
You get then all the results (all the same) with this
Console.WriteLine(result);
Console.WriteLine(result2);
Console.WriteLine(result21.Groups[1]);
Console.WriteLine(result3[0]);
Console.WriteLine(result4);
I would prefer the first method.
You need to think also about the behavior, when there is no dash in the string. The fourth method will throw an exception in that case, because text.IndexOf("-")
will be -1
. Method 1 and 2.1 will return nothing and method 2 and 3 will return the complete string.
You should use Adaptive hashing like http://en.wikipedia.org/wiki/Bcrypt for securing passwords
Use *
var allElem = document.getElementsByTagName("*");
for (var i = 0; i < allElem.length; i++) {
// Do something with all element here
}
With Java 8 it can be cloned with a stream.
import static java.util.stream.Collectors.toList;
...
List<AnObject> clone = myList.stream().collect(toList());
Adding commons-logging.jar or commons-logging-1.1.jar will solve this...
Yet Another Option:
>>> [re.split(r'(\d+)', s) for s in ('foofo21', 'bar432', 'foobar12345')]
[['foofo', '21', ''], ['bar', '432', ''], ['foobar', '12345', '']]
SIMPLY, You must set initial state first
If you don't set initial state react will treat that as an uncontrolled component
I found this easier to understand:
List<string> names = new List<string> { "One", "Two", "Three", "Four", "Five" };
for (int i = 0; i < names.Count; i++)
{
Console.WriteLine(names[i]);
}
My initial guess without knowing the data would be that the UserNameToVerify is not a multiple of 4 in length. Check out the FromBase64String on msdn.
// Ok
byte[] b1 = Convert.FromBase64String("CoolDude");
// Exception
byte[] b2 = Convert.FromBase64String("MyMan");
I did it like this
echo "NEO4J_ULIMIT_NOFILE=50000" >> neo4j
mv neo4j /etc/default/
First, you should understand the pointer is not complex. A pointer is showing the address of the variable.
Example:
int a = 10;
int *p = &a; // This means giving a pointer of variable "a" to int pointer variable "p"
And, you should understand "Pointer is an address" and "address is numerical value". So, you can get the address of variable as Integer.
int a = 10;
unsigned long address = (unsigned long)&a;
// comparison
printf("%p\n", &a);
printf("%ld\n", address);
output is below
0x7fff1216619c
7fff1216619c
Note:
If you use a 64-bit computer, you can't get pointer by the way below.
int a = 10;
unsigned int address = (unsigned int)&a;
Because pointer is 8 bytes (64 bit) on a 64-bit machine, but int is 4 bytes. So, you can't give an 8-byte memory address to 4 bytes variable.
You have to use long long
or long
to get an address of the variable.
long long
is always 8 bytes.long
is 4 bytes when code was compiled for a 32-bit machine.long
is 8 bytes when code was compiled for a 64-bit machine.Therefore, you should use long
to receive a pointer.
If you just want to round the number for output purposes, then the "%.2f"
format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:
#include <math.h>
float val = 37.777779;
float rounded_down = floorf(val * 100) / 100; /* Result: 37.77 */
float nearest = roundf(val * 100) / 100; /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100; /* Result: 37.78 */
Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.
As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.
For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.
I had success with easy killing all active httpd processes in Monitor Activity tool:
1) close XAMPP control
2) open Monitor Activity
3) select filter for All processes (default is My processes)
4) in fulltext search type: httpd
5) kill all showen items
6) relaunch XAMPP control and launch apache again
If you are using gvim, you could just hit Ctrl + Home to go the first line. Similarly, Ctrl + End goes to the last line.
How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it?
I posted a gist that solves this question/problem with a decorator and a threading.Timer
. Here it is with a breakdown.
It was tested with Python 2 and 3. It should also work under Unix/Linux and Windows.
First the imports. These attempt to keep the code consistent regardless of the Python version:
from __future__ import print_function
import sys
import threading
from time import sleep
try:
import thread
except ImportError:
import _thread as thread
Use version independent code:
try:
range, _print = xrange, print
def print(*args, **kwargs):
flush = kwargs.pop('flush', False)
_print(*args, **kwargs)
if flush:
kwargs.get('file', sys.stdout).flush()
except NameError:
pass
Now we have imported our functionality from the standard library.
exit_after
decoratorNext we need a function to terminate the main()
from the child thread:
def quit_function(fn_name):
# print to stderr, unbuffered in Python 2.
print('{0} took too long'.format(fn_name), file=sys.stderr)
sys.stderr.flush() # Python 3 stderr is likely buffered.
thread.interrupt_main() # raises KeyboardInterrupt
And here is the decorator itself:
def exit_after(s):
'''
use as decorator to exit process if
function takes longer than s seconds
'''
def outer(fn):
def inner(*args, **kwargs):
timer = threading.Timer(s, quit_function, args=[fn.__name__])
timer.start()
try:
result = fn(*args, **kwargs)
finally:
timer.cancel()
return result
return inner
return outer
And here's the usage that directly answers your question about exiting after 5 seconds!:
@exit_after(5)
def countdown(n):
print('countdown started', flush=True)
for i in range(n, -1, -1):
print(i, end=', ', flush=True)
sleep(1)
print('countdown finished')
Demo:
>>> countdown(3)
countdown started
3, 2, 1, 0, countdown finished
>>> countdown(10)
countdown started
10, 9, 8, 7, 6, countdown took too long
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in inner
File "<stdin>", line 6, in countdown
KeyboardInterrupt
The second function call will not finish, instead the process should exit with a traceback!
KeyboardInterrupt
does not always stop a sleeping threadNote that sleep will not always be interrupted by a keyboard interrupt, on Python 2 on Windows, e.g.:
@exit_after(1)
def sleep10():
sleep(10)
print('slept 10 seconds')
>>> sleep10()
sleep10 took too long # Note that it hangs here about 9 more seconds
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in inner
File "<stdin>", line 3, in sleep10
KeyboardInterrupt
nor is it likely to interrupt code running in extensions unless it explicitly checks for PyErr_CheckSignals()
, see Cython, Python and KeyboardInterrupt ignored
I would avoid sleeping a thread more than a second, in any case - that's an eon in processor time.
How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
To catch it and do something else, you can catch the KeyboardInterrupt.
>>> try:
... countdown(10)
... except KeyboardInterrupt:
... print('do something else')
...
countdown started
10, 9, 8, 7, 6, countdown took too long
do something else
(this question is a duplicate of In chart.js, Is it possible to hide x-axis label/text of bar chart if accessing from mobile?) They added the option, 2.1.4 (and maybe a little earlier) has it
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
ticks: {
display: false
}
}]
}
}
}
public void showNotification (String from, String notification, Intent intent) {
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
Notification_ID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification mNotification = builder
.setContentTitle(from)
.setContentText(notification)
// .setTicker("Hearty365")
// .setContentInfo("Info")
// .setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
// .setDefaults(Notification.DEFAULT_ALL)
// .setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.build();
notificationManager.notify(/*notification id*/Notification_ID, mNotification);
}
var img = $('<img />', {
id: 'Myid',
src: 'MySrc.gif',
alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));
Use lapply
function after creating your function normally.
lapply(x="your input", fun="insert your function name")
lapply
gives a list so use unlist
function to take them out of the function
unlist(lapply(a,w))
That only deletes the object, but it still keeps the array length the same.
To remove the element from the array, you need to do something like:
array.splice(index, 1);
HTTP verbs are probably one of the most cryptic things about the HTTP protocol. They exist, and there are many of them, but why do they exist?
Rails seems to want to support many verbs and add some verbs that aren't supported by web browsers natively.
Here's an exhaustive list of http verbs: http://annevankesteren.nl/2007/10/http-methods
There the HTTP patch from the official RFC: https://datatracker.ietf.org/doc/rfc5789/?include_text=1
The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request- URI. The set of changes is represented in a format called a "patch document" identified by a media type. If the Request-URI does not point to an existing resource, the server MAY create a new resource, depending on the patch document type (whether it can logically modify a null resource) and permissions, etc.
The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it also MAY have side effects on other resources; i.e., new resources may be created, or existing ones modified, by the application of a PATCH.
As far as I know, the PATCH verb is not used as it is in rails applications... As I understand this, the RFC patch verb should be used to send patch instructions like when you do a diff between two files. Instead of sending the whole entity again, you send a patch that could be much smaller than resending the whole entity.
Imagine you want to edit a huge file. You edit 3 lines. Instead of sending the file back, you just have to send the diff. On the plus side, sending a patch request could be used to merge files asynchronously. A version control system could potentially use the PATCH verb to update code remotely.
One other possible use case is somewhat related to NoSQL databases, it is possible to store documents. Let say we use a JSON structure to send back and forth data from the server to the client. If we wanted to delete a field, we could use a syntax similar to the one in mongodb for $unset. Actually, the method used in mongodb to update documents could be probably used to handle json patches.
Taking this example:
db.products.update(
{ sku: "unknown" },
{ $unset: { quantity: "", instock: "" } }
)
We could have something like this:
PATCH /products?sku=unknown
{ "$unset": { "quantity": "", "instock": "" } }
Last, but not least, people can say whatever they want about HTTP verbs. There is only one truth, and the truth is in the RFCs.
This works for vertical and horizontal:
#myContent{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
And if you want make an element center of the parent, set the position of the parent relative:
#parentElement{
position: relative
}
For vertical center align, set the height to your element. Thanks to Raul.
If you want make an element center of the parent, set the position of the parent to relative
The reason this question still often arises is because, as you mentioned, somewhere somehow someone presumed as important wrote that the RFC states domain names without subdomain in front of them are not valid. If you read the RFC carefully, however, you'll find that this is not exactly what it says. In fact, RFC 1912 states:
Don't go overboard with CNAMEs. Use them when renaming hosts, but plan to get rid of them (and inform your users).
Some DNS hosts provide a way to get CNAME-like functionality at the zone apex (the root domain level, for the naked domain name) using a custom record type. Such records include, for example:
For each provider, the setup is similar: point the ALIAS or ANAME entry for your apex domain to example.domain.com, just as you would with a CNAME record. Depending on the DNS provider, an empty or @ Name value identifies the zone apex.
ALIAS or ANAME or @ example.domain.com.
If your DNS provider does not support such a record-type, and you are unable to switch to one that does, you will need to use subdomain redirection, which is not that hard, depending on the protocol or server software that needs to do it.
I strongly disagree with the statement that it's done only by "amateur admins" or such ideas. It's a simple "What does the name and its service need to do?" deal, and then to adapt your DNS config to serve those wishes; If your main services are web and e-mail, I don' t see any VALID reason why dropping the CNAMEs for-good would be problematic. After all, who would prefer @subdomain.domain.org over @domain.org ? Who needs "www" if you're already set with the protocol itself? It's illogical to assume that use of a root-domainname would be invalid.
I avoid using natural keys for one simple reason -- human error. Although natural unique identifiers are often available (SSN, VIN, Account Number, etc.), they require a human to enter them correctly. If you're using SSNs as a primary key, someone transposes a couple of numbers during data entry, and the error isn't discovered immediately, then you're faced with changing your primary key.
My primary keys are all handled by the database program in the background and the user is never aware of them.
You don't need to add the concat package, you can do this via cssmin like this:
cssmin : {
options: {
keepSpecialComments: 0
},
minify : {
expand : true,
cwd : '/library/css',
src : ['*.css', '!*.min.css'],
dest : '/library/css',
ext : '.min.css'
},
combine : {
files: {
'/library/css/app.combined.min.css': ['/library/css/main.min.css', '/library/css/font-awesome.min.css']
}
}
}
And for js, use uglify like this:
uglify: {
my_target: {
files: {
'/library/js/app.combined.min.js' : ['/app.js', '/controllers/*.js']
}
}
}
Wikipedia has the following information about USING
:
The USING construct is more than mere syntactic sugar, however, since the result set differs from the result set of the version with the explicit predicate. Specifically, any columns mentioned in the USING list will appear only once, with an unqualified name, rather than once for each table in the join. In the case above, there will be a single DepartmentID column and no employee.DepartmentID or department.DepartmentID.
Tables that it was talking about:
The Postgres documentation also defines them pretty well:
The ON clause is the most general kind of join condition: it takes a Boolean value expression of the same kind as is used in a WHERE clause. A pair of rows from T1 and T2 match if the ON expression evaluates to true.
The USING clause is a shorthand that allows you to take advantage of the specific situation where both sides of the join use the same name for the joining column(s). It takes a comma-separated list of the shared column names and forms a join condition that includes an equality comparison for each one. For example, joining T1 and T2 with USING (a, b) produces the join condition ON T1.a = T2.a AND T1.b = T2.b.
Furthermore, the output of JOIN USING suppresses redundant columns: there is no need to print both of the matched columns, since they must have equal values. While JOIN ON produces all columns from T1 followed by all columns from T2, JOIN USING produces one output column for each of the listed column pairs (in the listed order), followed by any remaining columns from T1, followed by any remaining columns from T2.
I offer one more solution in case it is worthful for someone else.
I have a history.js
file where I have the following:
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
history.pushLater = (...args) => setImmediate(() => history.push(...args))
export default history
Next, on my Root where I define my router I use the following:
import history from '../history'
import { Provider } from 'react-redux'
import { Router, Route, Switch } from 'react-router-dom'
export default class Root extends React.Component {
render() {
return (
<Provider store={store}>
<Router history={history}>
<Switch>
...
</Switch>
</Router>
</Provider>
)
}
}
Finally, on my actions.js
I import History and make use of pushLater
import history from './history'
export const login = createAction(
...
history.pushLater({ pathname: PATH_REDIRECT_LOGIN })
...)
This way, I can push to new actions after API calls.
Hope it helps!
You can try disabling the "VirtualBox NDIS6 Bridged Networking Driver" on all but your actual physical network adapter(s) before attempting to create the VirtualBox host-only adapter again.
See this answer.
The jQuery UI sortable
feature includes a serialize
method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.
$('#element').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
What this does is that it creates an array of the elements using the elements id
. So, I usually do something like this:
<ul id="sortable">
<li id="item-1"></li>
<li id="item-2"></li>
...
</ul>
When you use the serialize
option, it will create a POST query string like this: item[]=1&item[]=2
etc. So if you make use - for example - your database IDs in the id
attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
For example, in PHP:
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}
Have you tried adding a magic comment in the script where you use non-ASCII chars? It should go on top of the script.
#!/bin/env ruby
# encoding: utf-8
It worked for me like a charm.
For anyone wishing to do this in a single line (e.g in the Display/Immediate window, a watch expression or similar in a debug session), the following will do so and "pretty print" the SQL:
new org.hibernate.jdbc.util.BasicFormatterImpl().format((new org.hibernate.loader.criteria.CriteriaJoinWalker((org.hibernate.persister.entity.OuterJoinLoadable)((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),new org.hibernate.loader.criteria.CriteriaQueryTranslator(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),((org.hibernate.impl.CriteriaImpl)crit),((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),(org.hibernate.impl.CriteriaImpl)crit,((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters())).getSQLString());
...or here's an easier to read version:
new org.hibernate.jdbc.util.BasicFormatterImpl().format(
(new org.hibernate.loader.criteria.CriteriaJoinWalker(
(org.hibernate.persister.entity.OuterJoinLoadable)
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(
((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),
new org.hibernate.loader.criteria.CriteriaQueryTranslator(
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
((org.hibernate.impl.CriteriaImpl)crit),
((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),
((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
(org.hibernate.impl.CriteriaImpl)crit,
((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters()
)
).getSQLString()
);
Notes:
crit
. If named differently, do a search and replace.getEnabledFilters
rather than getLoadQueryInfluencers()
for backwards compatibility since the latter was introduced in a later version of Hibernate (3.5???)It is possible to save a "list" of labels in keras model directly. This way the user who uses the model for predictions and does not have any other sources of information can perform the lookup himself. Here is a dummy example of how one can perform an "injection" of labels
# assume we get labels as list
labels = ["cat","dog","horse","tomato"]
# here we start building our model with input image 299x299 and one output layer
xx = Input(shape=(299,299,3))
flat = Flatten()(xx)
output = Dense(shape=(4))(flat)
# here we perform injection of labels
tf_labels = tf.constant([labels],dtype="string")
tf_labels = tf.tile(labels,[tf.shape(xx)[0],1])
output_labels = Lambda(lambda x: tf_labels,name="label_injection")(xx)
#and finaly creating a model
model=tf.keras.Model(xx,[output,output_labels])
When used for prediction, this model returns tensor of scores and tensot of string labels. Model like this can be saved to h5. In this case the file contains the labels. This model can also be exported to saved_model and used for serving in the cloud.
This is for the icon in the browser (most of the sites omit the type):
<link rel="icon" type="image/vnd.microsoft.icon"
href="http://example.com/favicon.ico" />
or
<link rel="icon" type="image/png"
href="http://example.com/image.png" />
or
<link rel="apple-touch-icon"
href="http://example.com//apple-touch-icon.png">
for the shortcut icon:
<link rel="shortcut icon"
href="http://example.com/favicon.ico" />
Place them in the <head></head>
section.
Edit may 2019 some additional examples from MDN
I don't know any native cmdlet in powershell but you can use com object instead:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()
you can create a powershell script save as set-shortcut.ps1 in your $pwd
param ( [string]$SourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()
and call it like this
Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"
If you want to pass arguments to the target exe, it can be done by:
#Set the additional parameters for the shortcut
$Shortcut.Arguments = "/argument=value"
before $Shortcut.Save().
For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.
param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
I was also facing the same error. The reason for this is that there is no smtp server on your environment. For creating a fake smtp server I used this fake-smtp.jar file for creating a virtual server and listening to all the requests. If you are facing the same error, I recommend you to use this jar and run it after extracting and then try to run your application.
string valueStr = "title, genre, director, actor";
var vals = valueStr.Split(',')[0];
vals will give you the title
Ideally use a simple directive to keep controllers free from redundant $window
app.directive('back', ['$window', function($window) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
elem.bind('click', function () {
$window.history.back();
});
}
};
}]);
Use like this:
<button back>Back</button>
FYI, I needed to update the color of the calendar icon which didn't seem possible with properties like color
, fill
, etc.
I did eventually figure out that some filter
properties will adjust the icon so while i did not end up figuring out how to make it any color, luckily all I needed was to make it so the icon was visible on a dark background so I was able to do the following:
body { background: black; }_x000D_
_x000D_
input[type="date"] { _x000D_
background: transparent;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
filter: invert(100%);_x000D_
}
_x000D_
<body>_x000D_
<input type="date" />_x000D_
</body>
_x000D_
Hopefully this helps some people as for the most part chrome even directly says this is impossible.
It is cumbersome to interoperate socket.io and connect sessions support. The problem is not because socket.io "hijacks" request somehow, but because certain socket.io transports (I think flashsockets) don't support cookies. I could be wrong with cookies, but my approach is the following:
This error happens if you did not set the password on install, in this case the mysql using unix-socket plugin.
But if delete the plugin link from settings (table mysql.user) will other problem. This does not fix the problem and creates another problem. To fix the deleted link and set password ("PWD") do:
1) Run with --skip-grant-tables
as said above.
If it doesnt works then add the string skip-grant-tables
in section [mysqld]
of /etc/mysql/mysql.conf.d/mysqld.cnf
. Then do
sudo service mysql restart
.
2) Run mysql -u root -p
, then (change "PWD"):
update mysql.user
set authentication_string=PASSWORD("PWD"), plugin="mysql_native_password"
where User='root' and Host='localhost';
flush privileges;
quit
then sudo service mysql restart
. Check: mysql -u root -p
.
Before restart
remove that string from file mysqld.cnf, if you set it there.
in Swift 3.0 or Later
passwordTextField.isSecureTextEntry = true
Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.
e.g. if you do this:
SELECT 1 / 2
you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.
e.g.
SELECT CAST(1 AS DECIMAL) / 2
gives 0.500000
SqlConnection c = new SqlConnection(@"Data Source=localhost;
Initial Catalog=Northwind; Integrated Security=True");
std::string num = "0.6";
double temp = ::atof(num.c_str());
Does it for me, it is a valid C++ syntax to convert a string to a double.
You can do it with the stringstream or boost::lexical_cast but those come with a performance penalty.
Ahaha you have a Qt project ...
QString winOpacity("0.6");
double temp = winOpacity.toDouble();
Extra note:
If the input data is a const char*
, QByteArray::toDouble
will be faster.
You can use the Gmail service for the mail.
Steps to use Gmail as an email service (Free) in Django:
1: Create a dummy Google account for your contact. 2: Add the following code in settings.py at the bottom.
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "[email protected]"
EMAIL_HOST_PASSWORD = "dummypassword"
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
3: Now in views.py add:
from django.core.mail import EmailMessage
# now in your function add this code
messageContent = yourcontent
msg = EmailMessage(heading, messageContent, settings.EMAIL_HOST_USER,[list of senders email])
msg.send()
4: Enable these things first for the dummy Gmail account:
a: Go to https://myaccount.google.com/lesssecureapps and enable it. NOTE: First check that you enable this with sign in as your dummy account. b: Now go to https://accounts.google.com/DisplayUnlockCaptcha and click continue.
5: You are ready to use Gmail email services for your contact page.
Bonus:
If you want to send a mail with an HTML template in Django then use this code in views.py.
from django.template.loader import get_template
from django.core.mail import EmailMessage
# add this code in function:
ctx = {
'subject': subjectin,
'userMsg': messagein,
}
heading = Your heading
messageContent = get_template('yourTemplate.html').render(ctx) #sending value on HTML page through context
msg = EmailMessage(heading, messageContent, settings.EMAIL_HOST_USER,
[list of emails ])
msg.content_subtype = 'html'
msg.send()
You can do this in jquery by setting the attribute disabled to 'disabled'.
$(this).prop('disabled', true);
I have made a simple example http://jsfiddle.net/4gnXL/2/
In 2019, I would suggest putting all the item animations into the ItemAnimator.
Let's start with declaring the animator in the recycler-view:
with(view.recycler_view) {
adapter = Adapter()
itemAnimator = CustomAnimator()
}
Declare the custom animator then,
class CustomAnimator() : DefaultItemAnimator() {
override fun animateAppearance(
holder: RecyclerView.ViewHolder,
preInfo: ItemHolderInfo?,
postInfo: ItemHolderInfo): Boolean{} // declare what happens when a item appears on the recycler view
override fun animatePersistence(
holder: RecyclerView.ViewHolder,
preInfo: ItemHolderInfo,
postInfo: ItemHolderInfo): Boolean {} // declare animation for items that persist in a recycler view even when the items change
}
Similar to the ones above there is one for disappearance animateDisappearance
, for add animateAdd
, for change animateChange
and move animateMove
.
One important point would be to call the correct animation-dispatchers inside them.
The regex you pasted does not validate leap years correctly, but there is one that does in the same post.
I modified it to take dd/mm/yyyy
, dd-mm-yyyy
or dd.mm.yyyy
.
^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
I tested it a bit in the link Arun provided in his answer and also here and it seems to work.
Edit February 14th 2019: I've removed a comma that was in the regex which allowed dates like 29-0,-11
Lazy Loading? Well, it simply means that child records are not fetched immediately, but automatically as soon as you try to access them.
Additionally, if you have the NDK installed, you can also find the listing in ${ndk_path}platforms\android-${api}\${architecture}\usr\include\android\keycodes.h
.
I'm only mentioning it because I've found it simpler to navigate and read than the KeyEvent class or docs.
If the above solutions don't work on ubuntu/linux then you can try this
sudo fuser -k -n tcp port
Run it several times to kill processes on your port of choosing. port could be 3000 for example. You would have killed all the processes if you see no output after running the command
A very portable way is to parse the output of this command.
ifconfig | awk '$0 ~ /HWaddr/ { print $5 }'
Provided ifconfig can be run as the current user (usually can) and awk is installed (it often is). This will give you the mac address of the machine.
The solution for me was to configure the build path to include the project itself.
If necessary, click the project menu and choose the ‘clean…’ option to rebuild.
In newer versions of Notepad++ (currently 5.9), this option is under:
View->Show Symbol->Show All Characters
or
View->Show Symbol->Show White Space and Tab
As delnan pointed out, the match
keyword in Scala has nothing to do with regexes. To find out whether a string matches a regex, you can use the String.matches
method. To find out whether a string starts with an a, b or c in lower or upper case, the regex would look like this:
word.matches("[a-cA-C].*")
You can read this regex as "one of the characters a, b, c, A, B or C followed by anything" (.
means "any character" and *
means "zero or more times", so ".*" is any string).
This usually happens when debugging using the emulator, which is known to be slow anyway.
Another polyfill for element.classList
is here. I found it via MDN.
I include that script and use element.classList.add("first","second","third")
as it's intended.
% is a special character you put in format strings, for example in C language printf and scanf (and family), that basically says "this is a placeholder for something else, not to be printed/read literally."
For example, a
(%02d)
in a format string for printf is a placeholder for an integer variable that will be printed in decimal(%02d)
and padded to at least two digits, with zeros if necessary.The actual integer is supplied by you in an an argument to the function, e.g.
printf("%02d",5);
would print05
on screen,(%01d)
also works similarly
Same hold for Java and other languages too :)
Click on simulator , Navigate to Window and enable Device Bezels
Just run composer install
- it will make your vendor
directory reflect dependencies in composer.lock
file.
In other words - it will delete any vendor which is missing in composer.lock
.
Please update the composer itself before running this.
what about a pure css3 solution?
div {
resize: both;
overflow: auto;
}
$(this).click(function(e) {
// does something
});
In reference to the above code
$(this)
is the element which as some variable.
click
is the event that needs to be performed.
the parameter e
is automatically passed from js to your function which holds the value of $(this)
value and can be used further in your code to do some operation.
More oftenly most of the applications will have data,display and processing part and we just put all those in the letters M
,V
and C
.
Model(M
)-->Has the attributes that holds state of application and it dont know any thing about V
and C
.
View(V
)-->Has displaying format for the application and and only knows about how-to-digest model on it and does not bother about C
.
Controller(C
)---->Has processing part of application and acts as wiring between M and V and it depends on both M
,V
unlike M
and V
.
Altogether there is separation of concern between each. In future any change or enhancements can be added very easily.
If you know how to launch your program from the command line then you can run it from the platformio-ide-terminal
package's terminal. See platformio-ide-terminal
provides an embedded terminal within the Atom text editor. So you can issue commands, including commands to run your Java program, from within it. To install this package you can use APM with the command:
$ apm install platformio-ide-terminal --no-confirm
Alternatively, you can install it from the command palette with:
platformio-ide-terminal
. You can read directly the value defined into strings.xml:
<resources>
<string name="hello">Hello StackOverflow!</string>
</resources>
and set into a variable:
String mymessage = getString(R.string.hello);
but we can define the string into the view:
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"/>
A useful extension is to collect the results in a Dictionary
for fast lookup (e.g. in a loop):
var resultDict = _dbContext.Projects
.Where(p => p.Status == ProjectStatus.Active)
.GroupBy(f => f.Country)
.Select(g => new { country = g.Key, count = g.Count() })
.ToDictionary(k => k.country, i => i.count);
Originally found here: http://www.snippetsource.net/Snippet/140/groupby-and-count-with-ef-in-c
TRUNCATE TABLE table;
is the SQL command. In PHP, you'd use:
mysql_query('TRUNCATE TABLE table;');
It's perfectly valid to use break
- as others have pointed out, it's nowhere in the same league as goto
.
Although you might want to use the vFound
variable when you want to check outside the loop whether the value was found in the array. Also from a maintainability point of view, having a common flag signalling the exit criteria might be useful.
You can achieve this $(identifier).data('id')
using jquery,
<script type="text/javascript">
function goDoSomething(identifier){
alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
javascript : You can use getAttribute("attributename")
if want to use javascript tag,
<script type="text/javascript">
function goDoSomething(d){
alert(d.getAttribute("data-id"));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
Or:
<script type="text/javascript">
function goDoSomething(data_id, data_option){
alert("data-id:"+data_id+", data-option:"+data_option);
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
Click to do something
</a>
since others have answered how to do it, I'll answer how it happens line by line.
with FileOpenerCM('file.txt') as fp: # is equal to "with open('file.txt') as fp:"
fp.write('dummy text')
this is a so-called context manager
, anything that comes with a with
block is a context manager. so let's see how this happens under the hood.
class FileOpenerCM:
def __init__(self, file, mode='w'):
self.file = open(file, mode)
def __enter__(self):
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
self.file.close()
the first method __init__
is (as you all know) the initialization method of an object. whenever an object is created obj.__init__
is definitely called. and that's the place where you put your all the init kinda code.
the second method __enter__
is a bit interesting. some of you might not have seen it because it is a specific method for context managers. what it returns is the value to be assigned to the variable after the as
keyword. in our case, fp
.
the last method is the method to run after an error is captured or if the code exits the with block. exc_type
, exc_value
, exc_traceback
variables are the variables that hold the values of the errors that occurred inside with block. for example,
exc_type: TypeError
exc_value: unsupported operand type(s) for +: 'int' and 'str
exc_traceback: <traceback object at 0x6af8ee10bc4d>
from the first two variables, you can get info enough info about the error. honestly, I don't know the use of the third variable, but for me, the first two are enough. if you want to do more research on context managers surely you can do it and note that writing classes are not the only way to write context managers. with contextlib you can write context managers through functions(actually generators) as well. it's totally up to you to have a look at it. you can surely try generator functions with contextlib but as I see classes are much cleaner.
The first approach to take is to modify your web.config using the <location>
configuration tag, and <allow users="?"/>
to allow anonymous or <allow users="*"/>
for all:
<configuration>
<location path="Path/To/Public/Folder">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
If that approach doesn't work then you can take the following approach which requires making a small modification to the IIS applicationHost.config.
First, change the anonymousAuthentication section's overrideModeDefault from "Deny" to "Allow" in C:\Windows\System32\inetsrv\config\applicationHost.config:
<section name="anonymousAuthentication" overrideModeDefault="Allow" />
overrideMode
is a security feature of IIS. If override is disallowed at the system level in applicationHost.config then there is nothing you can do in web.config to enable it. If you don't have this level of access on your target system you have to take up that discussion with your hosting provider or system administrator.
Second, after setting overrideModeDefault="Allow"
then you can put the following in your web.config:
<location path="Path/To/Public/Folder">
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
</location>
The easiest way that I could find to pass a message from my app to facebook was programmatically copy to the clipboard and alert the user that they have the option to paste. It saves the user from manually doing it; my app is not pasting but the user might.
...
if (app.equals("facebook")) {
// overcome fb 'putExtra' constraint;
// copy message to clipboard for user to paste into fb.
ClipboardManager cb = (ClipboardManager)
getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("post", msg);
cb.setPrimaryClip(clip);
// tell the to PASTE POST with option to stop showing this dialogue
showDialog(this, getString(R.string.facebook_post));
}
startActivity(appIntent);
...
Few answers that may be useful, especially if you have dynamic content.
$('#dialogueForm').live("dialogclose", function(){
//your code to run on dialog close
});
Or, when opening the modal, have a callback.
$( "#dialogueForm" ).dialog({
autoOpen: false,
height: "auto",
width: "auto",
modal: true,
my: "center",
at: "center",
of: window,
close : function(){
// functionality goes here
}
});
Make a factory in your module and add a reference of the factory in controller and use its variables in the controller and now get the value of data in another controller by adding reference where ever you want
I have just started checking out Angular(so im quite sure there are other ways to get it done which are more optimum), and i came across this question while searching for examples of ng-repeat.
The requirement by the poser(with the update):
"...but my real requirement is display the items as shown below.."
looked real-world enough (and simple), so i thought ill give it a spin and attempt to get the exact desired structure.
angular.module('appTest', [])_x000D_
.controller("repeatCtrl", function($scope) {_x000D_
$scope.items = [{_x000D_
Name: "Soap",_x000D_
Price: "25",_x000D_
Quantity: "10"_x000D_
}, {_x000D_
Name: "Bag",_x000D_
Price: "100",_x000D_
Quantity: "15"_x000D_
}, {_x000D_
Name: "Pen",_x000D_
Price: "15",_x000D_
Quantity: "13"_x000D_
}];_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<body ng-app="appTest">_x000D_
<section ng-controller="repeatCtrl">_x000D_
<table>_x000D_
<thead>_x000D_
<tr ng-repeat="item in items | limitTo:1">_x000D_
<th ng-repeat="(key, val) in item">_x000D_
{{key}}_x000D_
</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr ng-repeat="item in items">_x000D_
<td ng-repeat="(key, val) in item">_x000D_
{{val}}_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</section>_x000D_
</body>
_x000D_
The limitTo:(n) filter is the key. Im still not sure if having multiple ng-repeat is an optimum way to go about it, but can't think of another alternative currently.
kennytm's links are dead and he doesn't provide an example so here's how you do substrings:
=MID(text, start_num, char_num)
Let's say cell A1
is Hello
.
=MID(A1, 2, 3)
Would return
ell
Because it says to start at character 2, e
, and to return 3 characters.
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
A simple way would be to use pandas. I adapted an example from the plotting documentation:
In [1]: import pandas as pd, numpy as np
In [2]: df = pd.DataFrame(np.random.rand(12,2), columns=['Apples', 'Oranges'] )
In [3]: df['Categories'] = pd.Series(list('AAAABBBBCCCC'))
In [4]: pd.options.display.mpl_style = 'default'
In [5]: df.boxplot(by='Categories')
Out[5]:
array([<matplotlib.axes.AxesSubplot object at 0x51a5190>,
<matplotlib.axes.AxesSubplot object at 0x53fddd0>], dtype=object)
Yes. But place your "test" after the comma if you want the column...
> A <- matrix(sample(1:12,12,T),ncol=4)
> rownames(A) <- letters[1:3]
> colnames(A) <- letters[11:14]
> A[,"l"]
a b c
6 10 1
see also help(Extract)
It is not at all obvious why one would want to concatenate the (decimal) "ascii values". What is certain is that concatenating them without leading zeroes (or some other padding or a delimiter) is useless -- nothing can be reliably recovered from such an output.
>>> tests = ["hi", "Hi", "HI", '\x0A\x29\x00\x05']
>>> ["".join("%d" % ord(c) for c in s) for s in tests]
['104105', '72105', '7273', '104105']
Note that the first 3 outputs are of different length. Note that the fourth result is the same as the first.
>>> ["".join("%03d" % ord(c) for c in s) for s in tests]
['104105', '072105', '072073', '010041000005']
>>> [" ".join("%d" % ord(c) for c in s) for s in tests]
['104 105', '72 105', '72 73', '10 41 0 5']
>>> ["".join("%02x" % ord(c) for c in s) for s in tests]
['6869', '4869', '4849', '0a290005']
>>>
Note no such problems.
There are 2 differences:
2 methods creating a user and granting some privileges to him
create user userName identified by password;
grant connect to userName;
and
grant connect to userName identified by password;
do exactly the same. It creates a user and grants him the connect role.
different outcome
resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.
To grant a user all privileges run you first snippet or
grant all privileges to userName identified by password;
In windows You may try this batch file to help you to shuffle your data.txt, The usage of the batch code is
C:\> type list.txt | shuffle.bat > maclist_temp.txt
After issuing this command, maclist_temp.txt will contain a randomized list of lines.
Hope this helps.
i have ran into the same problem and found a solution (not totally by myself, but there is the internet for)
Color blue = ColorTranslator.FromHtml("#CCFFFF");
Color red = ColorTranslator.FromHtml("#FFCCFF");
Color letters = Color.Black;
foreach (DataGridViewRow r in datagridIncome.Rows)
{
if (r.Cells[5].Value.ToString().Contains("1")) {
r.DefaultCellStyle.BackColor = blue;
r.DefaultCellStyle.SelectionBackColor = blue;
r.DefaultCellStyle.SelectionForeColor = letters;
}
else {
r.DefaultCellStyle.BackColor = red;
r.DefaultCellStyle.SelectionBackColor = red;
r.DefaultCellStyle.SelectionForeColor = letters;
}
}
This is a small trick, the only way you can see a row is selected, is by the very first column (not column[0], but the one therefore). When you click another row, you will not see the blue selection anymore, only the arrow indicates which row have selected. As you understand, I use rowSelection in my gridview.
These steps worked for me.
One of the versions you posted actually works for all modern browsers (where CSS selectors level 3 are supported):
div ul:not(:first-child) {
background-color: #900;
}
If you need to support legacy browsers, or if you are hindered by the :not
selector's limitation (it only accepts a simple selector as an argument) then you can use another technique:
Define a rule that has greater scope than what you intend and then "revoke" it conditionally, limiting its scope to what you do intend:
div ul {
background-color: #900; /* applies to every ul */
}
div ul:first-child {
background-color: transparent; /* limits the scope of the previous rule */
}
When limiting the scope use the default value for each CSS attribute that you are setting.
This isn't possible with ruby currently. You can't pass 'empty' attributes to methods. The closest you can get is to pass nil:
ldap_get(base_dn, filter, nil, X)
However, this will set the scope to nil, not LDAP::LDAP_SCOPE_SUBTREE.
What you can do is set the default value within your method:
def ldap_get(base_dn, filter, scope = nil, attrs = nil)
scope ||= LDAP::LDAP_SCOPE_SUBTREE
... do something ...
end
Now if you call the method as above, the behaviour will be as you expect.
In order to get the popup exactly centered, it's a simple matter of applying a negative top margin of half the div height, and a negative left margin of half the div width. For this example, like so:
.div {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 50%;
}
The function argument to setTimeout
is closing over the loop variable. The loop finishes before the first timeout and displays the current value of i
, which is 3
.
Because JavaScript variables only have function scope, the solution is to pass the loop variable to a function that sets the timeout. You can declare and call such a function like this:
for (var i = 1; i <= 2; i++) {
(function (x) {
setTimeout(function () { alert(x); }, 100);
})(i);
}
<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access plus 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
If you're using Laravel, my problem was in the name of my Route. Instead:
Route::put('/reason/update', 'REASONController@update');
I wrote:
Route::put('/reason/update', 'RESONController@update');
and when I fixed the controller name, the code worked!
Repository.addorupdate(entity, entity.id);
Repository.savechanges();
Var id = entity.id;
This will work.
__dirname
is only defined in scripts. It's not available in REPL.
try make a script a.js
console.log(__dirname);
and run it:
node a.js
you will see __dirname
printed.
Added background explanation: __dirname
means 'The directory of this script'. In REPL, you don't have a script. Hence, __dirname
would not have any real meaning.
This function check the special chars
on key press and eliminates the value if it is not a number
function mobilevalid(id) {
var feild = document.getElementById(id);
if (isNaN(feild.value) == false) {
if (feild.value.length == 1) {
if (feild.value < 7) {
feild.value = "";
}
} else if (feild.value.length > 10) {
feild.value = feild.value.substr(0, feild.value.length - 1);
}
if (feild.value.charAt(0) < 7) {
feild.value = "";
}
} else {
feild.value = "";
}
}
You can deploy your angular application on github
using
angular-cli-ghpages
check out the link to find how to deploy using this cli.
the deployed website will be stored in some branch in github
typically
gh-pages
use can clone the git branch and use it like static website in your server
My approach:
define a default constraint on the ModDate
column with a value of GETDATE()
- this handles the INSERT
case
have a AFTER UPDATE
trigger to update the ModDate
column
Something like:
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
for i in `ls *.zip`; do unzip $i; done
My 2 cent. Same but different...
<script>
dosomething("blaha", function(){
alert("Yay just like jQuery callbacks!");
});
function dosomething(damsg, callback){
alert(damsg);
if(typeof callback == "function")
callback();
}
</script>
I found this to be the simplest piece of code for getting the job done. As you can see it is super simple.
for original link text
I use:
$("#sec1").text(Sector1);
where
Sector1 = 'my new link text';
For the future time traveler from google, here is a new way (available from python 3.8 onward):
b = 1
if a := b:
# this section is only reached if b is not 0 or false.
# Also, a is set to b
print(a, b)
I was trying to make my module from magaplaza hello world tutorial, but something went wrong. I imported code of this module https://github.com/astorm/magento2-hello-world from github and it worked. from that module, i created it a categories subcategories ajax select drop downs Module. After installing it in aap/code directory of your magento2 installation follow this URL.. http://www.example.com/hello_mvvm/hello/world You can download its code from here https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns and place it in your aap/code folder. than run these commands...
php bin/magento setup:update
php bin/magento setup:static-content:deploy -f
php bin/magento c:c
Now you can check module functionality with following URL http://{{www.example.com}}/hello_mvvm/hello/world
Try using the wget library for python. You can find the documentation for it here.
import wget
link = 'ftp://example.com/foo.txt'
wget.download(link)
To stick with the Maven terms:
http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference
Here is the code you need:
start cmd.exe @cmd /k "Command"
Here is part of a line in my code that brought the warning up in NetBeans:
$page = (!empty($_GET['p']))
After much research and seeing how there are about a bazillion ways to filter this array, I found one that was simple. And my code works and NetBeans is happy:
$p = filter_input(INPUT_GET, 'p');
$page = (!empty($p))
Difference between a Spy and a Mock
When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.
In the following example – we create a mock of the ArrayList class:
@Test
public void whenCreateMock_thenCreated() {
List mockedList = Mockito.mock(ArrayList.class);
mockedList.add("one");
Mockito.verify(mockedList).add("one");
assertEquals(0, mockedList.size());
}
As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:
@Test
public void whenCreateSpy_thenCreate() {
List spyList = Mockito.spy(new ArrayList());
spyList.add("one");
Mockito.verify(spyList).add("one");
assertEquals(1, spyList.size());
}
Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn’t been mocked! So where does 1 come from? The internal real size() method is called as size() isn’t mocked (or stubbed) and hence we can say that the entry was added to the real object.
Source: http://www.baeldung.com/mockito-spy + self notes.
You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:
Dim MyVar as string = "some text ""hello"" "
This will give the MyVar
variable a value of some text "hello"
.
The following command gives you a list of all background processes in your session, along with the pid. You can then use it to kill the process.
jobs -l
Example usage:
$ sleep 300 &
$ jobs -l
[1]+ 31139 Running sleep 300 &
$ kill 31139
lets say you want to install scipy,
Here is the code to install it
!pip install scipy
You not only have to put the meta tag, telling that it is UTF-8 but really make the document UTF-8. You can do that with good editors (like notepad++) by converting them to "unicode" or "UTF-8 without BOM". Than you can simply use arabic characters
As this page is UTF-8, here are some examples (I hope I don't write anything rude here): ???
If you use a server side scripting language make sure that it does not output the page in a different encoding. In PHP e.g. you can set it like this:
header('Content-Type: text/html; charset=utf-8');
I think you can do this using 'git mv' and 'git pull'.
I'm a fair git noob - so be careful with your main repository - but I just tried this in a temp dir and it seems to work.
First - rename the structure of XXX to match how you want it to look when it's within YYY:
cd XXX
mkdir tmp
git mv ZZZ tmp/ZZZ
git mv tmp ZZZ
Now XXX looks like this:
XXX
|- ZZZ
|- ZZZ
Now use 'git pull' to fetch the changes across:
cd ../YYY
git pull ../XXX
Now YYY looks like this:
YYY
|- ZZZ
|- ZZZ
|- (other folders that already were in YYY)
Let's assume your model is a collection of objects (or maybe a single object). For each object in the model do the following.
1) Put the object you want to display in the ViewBag. For example:
ViewBag.YourObject = yourObject;
2) Add a using statement at the top of _Layout.cshtml that contains the class definition for your objects. For example:
@using YourApplication.YourClasses;
3) When you reference yourObject in _Layout cast it. You can apply the cast because of what you did in (2).
function uploadFile() {
var fileElement = document.getElementById("fileToUpload");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension == "odx-d"||fileExtension == "odx"||fileExtension == "pdx"||fileExtension == "cmo"||fileExtension == "xml") {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/post_uploadReq");
xhr.send(fd);
}
else {
alert("You must select a valid odx,pdx,xml or cmo file for upload");
return false;
}
}
tried this , works very well
Please find the below query also split the string with delimeter.
Select Substring(@String1,0,CharIndex(@delimeter,@String1))
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
Save your sorting order in a ViewState.
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression,string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
Why you don't want to use existing sorting functionality? You can always customize it.
Sorting Data in a GridView Web Server Control at MSDN
Here is an example with customization:
Thanks @Ole V.v for reviewing it: i have found some inbuilt library classes which does the same
int noOfMonths = 0;
org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat
.forPattern("yyyy-MM-dd");
DateTime dt = formatter.parseDateTime(startDate);
DateTime endDate11 = new DateTime();
Months m = Months.monthsBetween(dt, endDate11);
noOfMonths = m.getMonths();
System.out.println(noOfMonths);
I also prefer CSS over HTML; HTML is about content, CSS about presentation.
With CSS you have three options.
Example using internal stylesheet:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Image with border</title>
<style type="text/css">
img.hasBorder { border:15px solid #66CC33; }
</style>
</head>
<body>
<img class="hasBorder" src="peggy.jpg" alt="" />
</body>
</html>
If you want an external stylesheet, replace the <style>...</style> block with
<link rel="stylesheet" type="text/css" href="somestylesheet.css" />
This worked for me:
git remote set-url heroku <repo git>
This replacement old url heroku.
You can check with:
git remote -v
Perl versions 5.10 and later support subsidiary vertical and horizontal character classes, \v
and \h
, as well as the generic whitespace character class \s
The cleanest solution is to use the horizontal whitespace character class \h
. This will match tab and space from the ASCII set, non-breaking space from extended ASCII, or any of these Unicode characters
U+0009 CHARACTER TABULATION
U+0020 SPACE
U+00A0 NO-BREAK SPACE (not matched by \s)
U+1680 OGHAM SPACE MARK
U+2000 EN QUAD
U+2001 EM QUAD
U+2002 EN SPACE
U+2003 EM SPACE
U+2004 THREE-PER-EM SPACE
U+2005 FOUR-PER-EM SPACE
U+2006 SIX-PER-EM SPACE
U+2007 FIGURE SPACE
U+2008 PUNCTUATION SPACE
U+2009 THIN SPACE
U+200A HAIR SPACE
U+202F NARROW NO-BREAK SPACE
U+205F MEDIUM MATHEMATICAL SPACE
U+3000 IDEOGRAPHIC SPACE
The vertical space pattern \v
is less useful, but matches these characters
U+000A LINE FEED
U+000B LINE TABULATION
U+000C FORM FEED
U+000D CARRIAGE RETURN
U+0085 NEXT LINE (not matched by \s)
U+2028 LINE SEPARATOR
U+2029 PARAGRAPH SEPARATOR
There are seven vertical whitespace characters which match \v
and eighteen horizontal ones which match \h
. \s
matches twenty-three characters
All whitespace characters are either vertical or horizontal with no overlap, but they are not proper subsets because \h
also matches U+00A0 NO-BREAK SPACE, and \v
also matches U+0085 NEXT LINE, neither of which are matched by \s
I had the same problem caused by my script below. The problem was caused by url variable. When I added http://|web server name|/|application name| in front of /Reports/ReportPage.aspx ... it started to work.
<script>_x000D_
$(document).ready(function () {_x000D_
DisplayReport();_x000D_
});_x000D_
_x000D_
function DisplayReport() {_x000D_
var url = '/Reports/ReportPage.aspx?ReportName=AssignmentReport';_x000D_
_x000D_
if (url === '')_x000D_
return;_x000D_
var myFrame = document.getElementById('frmReportViewer');_x000D_
if (myFrame !== null) {_x000D_
if (myFrame.contentWindow !== null && myFrame.contentWindow.location !== null) {_x000D_
myFrame.contentWindow.location = url;_x000D_
}_x000D_
else {_x000D_
myFrame.setAttribute('src', url);_x000D_
}_x000D_
}_x000D_
}_x000D_
</script>
_x000D_
Below is the pseudo-code for using sub-query using Criteria API.
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<EMPLOYEE> from = criteriaQuery.from(EMPLOYEE.class);
Path<Object> path = from.get("compare_field"); // field to map with sub-query
from.fetch("name");
from.fetch("id");
CriteriaQuery<Object> select = criteriaQuery.select(from);
Subquery<PROJECT> subquery = criteriaQuery.subquery(PROJECT.class);
Root fromProject = subquery.from(PROJECT.class);
subquery.select(fromProject.get("requiredColumnName")); // field to map with main-query
subquery.where(criteriaBuilder.and(criteriaBuilder.equal("name",name_value),criteriaBuilder.equal("id",id_value)));
select.where(criteriaBuilder.in(path).value(subquery));
TypedQuery<Object> typedQuery = entityManager.createQuery(select);
List<Object> resultList = typedQuery.getResultList();
Also it definitely needs some modification as I have tried to map it according to your query. Here is a link http://www.ibm.com/developerworks/java/library/j-typesafejpa/ which explains concept nicely.
Use document.activeElement
Should work.
P.S getElementById("myID")
not getElementById("#myID")
Modified version of Kon's answer as it only partially works with similar named parameters. The down side of using String Replace function. Other than that, I give him full credit on the solution.
private string GetActualQuery(SqlCommand sqlcmd)
{
string query = sqlcmd.CommandText;
string parameters = "";
string[] strArray = System.Text.RegularExpressions.Regex.Split(query, " VALUES ");
//Reconstructs the second half of the SQL Command
parameters = "(";
int count = 0;
foreach (SqlParameter p in sqlcmd.Parameters)
{
if (count == (sqlcmd.Parameters.Count - 1))
{
parameters += p.Value.ToString();
}
else
{
parameters += p.Value.ToString() + ", ";
}
count++;
}
parameters += ")";
//Returns the string recombined.
return strArray[0] + " VALUES " + parameters;
}
CMD > netstat -ao
> look for any line like 0.0.0.0:80
and look at the PID value (e.g. 4796)
Open Task Manager > Processes tab > View > Select Column > Tick on PID (Process Identifier) > OK to create new column
Look at the processes list in Task Manager > Sort by PID (the new column) and find the 4796 to know which program is using Port 80. Mine is Bit-Torrent. After close (exit) Bit-Torrent, Wampserver should work as usual.
use JSON.stringify(userData)
to coverty json object to string.
var dataStore = $.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));
and for getting back from cookie use JSON.parse()
var data=JSON.parse($.cookie("basket-data"))
So there are lots of useful solutions to the question - but which is fastest / uses the fewest resources?
Repeated tests using this frame:
/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do TEST ; x=$(($x-1)); done'
Replacing TEST each time:
[[ $b =~ $a ]] 2.92 user 0.06 system 0:02.99 elapsed 99% CPU
[ "${b/$a//}" = "$b" ] 3.16 user 0.07 system 0:03.25 elapsed 99% CPU
[[ $b == *$a* ]] 1.85 user 0.04 system 0:01.90 elapsed 99% CPU
case $b in *$a):;;esac 1.80 user 0.02 system 0:01.83 elapsed 99% CPU
doContain $a $b 4.27 user 0.11 system 0:04.41 elapsed 99%CPU
(doContain was in F. Houri's answer)
And for giggles:
echo $b|grep -q $a 12.68 user 30.86 system 3:42.40 elapsed 19% CPU !ouch!
So the simple substitution option predictably wins whether in an extended test or a case. The case is portable.
Piping out to 100000 greps is predictably painful! The old rule about using external utilities without need holds true.
$("ul").empty() should work and clear the childrens. you can see it here:
' Create an HTTP object
myURL = "http://www.google.com"
Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )
' Download the specified URL
objHTTP.Open "GET", myURL, False
objHTTP.Send
intStatus = objHTTP.Status
If intStatus = 200 Then
WScript.Echo " " & intStatus & " A OK " +myURL
Else
WScript.Echo "OOPS" +myURL
End If
then
C:\>cscript geturl.vbs
Microsoft (R) Windows Script Host Version 5.7
Copyright (C) Microsoft Corporation. All rights reserved.
200 A OK http://www.google.com
or just double click it to test in windows
Click the database symbol with the plus sign (shown in the below picture). Enter a name and click Apply
.
This worked in MySQL Workbench 6.0
My personal choice is:
^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$
, Where:
^\p{L}+
- It should start with 1 or more letters.
[\p{Pd}\p{Zs}'\p{L}]*
- It can have letters, space character (including invisible), dash or hyphen characters and ' in any order 0 or more times.
\p{L}+$
- It should finish with 1 or more letters.
|^\p{L}+$
- Or it just should contain 1 or more letters (It is done to support single letter names).
Support for dots (full stops) was dropped, as in British English it can be dropped in Mr or Mrs, for example.
Have a look at File > Preferences > Keyboard Shortcuts (or Ctrl+K Ctrl+S)
Search for cursorColumnSelectDown
or cursorColumnSelectUp
which will give you the relevent keyboard shortcut. For me it is Shift+Alt+Down/Up Arrow
url=”http://shahkrunalm.wordpress.com“
content=”$(curl -sLI “$url” | grep HTTP/1.1 | tail -1 | awk {‘print $2'})”
if [ ! -z $content ] && [ $content -eq 200 ]
then
echo “valid url”
else
echo “invalid url”
fi
SELECT *
FROM people
WHERE names ='SMITH'
ORDER BY names asc
limit 10
If you need add group by clause. If you search Smith you would have to sort on something else.
check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.
You can add .a file in the linking command:
gcc yourfiles /path/to/library/libLIBRARY.a
But this is not talking with gcc driver, but with ld
linker as options like -Wl,anything
are.
When you tell gcc or ld -Ldir -lLIBRARY
, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose
). To change order of library types checked you can use -Wl,-Bstatic
and -Wl,-Bdynamic
. Here is a man page of gnu LD: http://linux.die.net/man/1/ld
To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:
gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3
Assuming that default setting of ld is to use dynamic libraries (it is on Linux).
This should be a good case for map and lambda
with open ('names.txt','r') as f :
Names = map (lambda x : x.strip(),f_in.readlines())
I stand corrected (or at least improved). List comprehensions is even more elegant
with open ('names.txt','r') as f :
Names = [name.rstrip() for name in f]
map
doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map
.
map
in Python 3 is equivalent to this:
def map(func, iterable):
for i in iterable:
yield func(i)
and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yield
ing.
Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map
, particularly if you're using a lambda expression as the first argument:
[func(i) for i in iterable]
As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -
>>> a = "hello, world"
>>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')
A use of map
here would be if you start with a list of strings instead of a single string - map
can listify all of them individually:
>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
Note that map(list, a)
is equivalent in Python 2, but in Python 3 you need the list
call if you want to do anything other than feed it into a for
loop (or a processing function such as sum
that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:
>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
They are identical. JPG is simply a holdover from the days of DOS when file extensions were required to be 3 characters long. You can find out more information about the JPEG standard here. A question very similar to this one was asked over at SuperUser, where the accepted answer should give you some more detailed information.
My solution doesn't require the addition of external tools or scripting languages --it's pretty much guaranteed to work on your build machine. I solve this problem in several parts. First, I have created a BUILD.BAT file that converts the Jenkins BUILD_NUMBER parameter into an environment variable. I use Jenkins's "Execute Windows batch command" function to run the build batch file by entering the following information for the Jenkins build:
./build.bat --build_id %BUILD_ID% -build_number %BUILD_NUMBER%
In the build environment, I have a build.bat file that starts as follows:
rem build.bat
set BUILD_ID=Unknown
set BUILD_NUMBER=0
:parse_command_line
IF NOT "%1"=="" (
IF "%1"=="-build_id" (
SET BUILD_ID=%2
SHIFT
)
IF "%1"=="-build_number" (
SET BUILD_NUMBER=%2
SHIFT
)
SHIFT
GOTO :parse_command_line
)
REM your build continues with the environmental variables set
MSBUILD.EXE YourProject.sln
Once I did that, I right-clicked on the project to be built in Visual Studio's Solution Explorer pane and selected Properties, select Build Events, and entered the following information as the Pre-Build Event Command Line, which automatically creates a .cs file containing build number information based on current environment variable settings:
set VERSION_FILE=$(ProjectDir)\Properties\VersionInfo.cs
if !%BUILD_NUMBER%==! goto no_buildnumber_set
goto buildnumber_set
:no_buildnumber_set
set BUILD_NUMBER=0
:buildnumber_set
if not exist %VERSION_FILE% goto no_version_file
del /q %VERSION_FILE%
:no_version_file
echo using System.Reflection; >> %VERSION_FILE%
echo using System.Runtime.CompilerServices; >> %VERSION_FILE%
echo using System.Runtime.InteropServices; >> %VERSION_FILE%
echo [assembly: AssemblyVersion("0.0.%BUILD_NUMBER%.1")] >> %VERSION_FILE%
echo [assembly: AssemblyFileVersion("0.0.%BUILD_NUMBER%.1")] >> %VERSION_FILE%
You may need to adjust to your build taste. I build the project manually once to generate an initial Version.cs file in the Properties directory of the main project. Lastly, I manually include the Version.cs file into the Visual Studio solution by dragging it into the Solution Explorer pane, underneath the Properties tab for that project. In future builds, Visual Studio then reads that .cs file at Jenkins build time and gets the correct build number information out of it.
dplyr now has a function case_when
that offers a vectorised if. The syntax is a little strange compared to mosaic:::derivedFactor
as you cannot access variables in the standard dplyr way, and need to declare the mode of NA, but it is considerably faster than mosaic:::derivedFactor
.
df %>%
mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L,
a %in% c(0,1,3,4) | c == 4 ~ 3L,
TRUE~as.integer(NA)))
EDIT: If you're using dplyr::case_when()
from before version 0.7.0 of the package, then you need to precede variable names with '.$
' (e.g. write .$a == 1
inside case_when
).
Benchmark: For the benchmark (reusing functions from Arun 's post) and reducing sample size:
require(data.table)
require(mosaic)
require(dplyr)
require(microbenchmark)
set.seed(42) # To recreate the dataframe
DT <- setDT(lapply(1:6, function(x) sample(7, 10000, TRUE)))
setnames(DT, letters[1:6])
DF <- as.data.frame(DT)
DPLYR_case_when <- function(DF) {
DF %>%
mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L,
a %in% c(0,1,3,4) | c==4 ~ 3L,
TRUE~as.integer(NA)))
}
DT_fun <- function(DT) {
DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}
DPLYR_fun <- function(DF) {
mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L,
ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}
mosa_fun <- function(DF) {
mutate(DF, g = derivedFactor(
"2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
"3" = (a == 0 | a == 1 | a == 4 | a == 3 | c == 4),
.method = "first",
.default = NA
))
}
perf_results <- microbenchmark(
dt_fun <- DT_fun(copy(DT)),
dplyr_ifelse <- DPLYR_fun(copy(DF)),
dplyr_case_when <- DPLYR_case_when(copy(DF)),
mosa <- mosa_fun(copy(DF)),
times = 100L
)
This gives:
print(perf_results)
Unit: milliseconds
expr min lq mean median uq max neval
dt_fun 1.391402 1.560751 1.658337 1.651201 1.716851 2.383801 100
dplyr_ifelse 1.172601 1.230351 1.331538 1.294851 1.390351 1.995701 100
dplyr_case_when 1.648201 1.768002 1.860968 1.844101 1.958801 2.207001 100
mosa 255.591301 281.158350 291.391586 286.549802 292.101601 545.880702 100
The problem with writing scripts at the head of a page is blocking. The browser must stop processing the page until the script is download, parsed and executed. The reason for this is pretty clear, these scripts might insert more into the page changing the result of the rendering, they also may remove things that dont need to be rendered, etc.
Some of the more modern browsers violate this rule by not blocking on the downloading the scripts (ie8 was the first) but overall the download isn't the majority of the time spent blocking.
Check out Even Faster Websites, I just finished reading it and it goes over all of the fast ways to get scripts onto a page, Including putting scripts at the bottom of the page to allow rendering to complete (better UX).
Although this question is old, it is still asked by many who use MSYS2.
I started to use it this year to replace CygWin, and I'm getting pretty satisfied.
To install make
, open the MSYS2 shell and type the following commands:
# Update the package database and core system packages
pacman -Syu
# Close shell and open again if needed
# Update again
pacman -Su
# Install make
pacman -S make
# Test it (show version)
make -v
I know it's been a year since this was asked, but just for people that are going to visit this page I am posting my solution.
By using what @Aldi Unanto suggested here is a more complete answer:
jQuery('.show_hide').click(function(e) {
e.preventDefault();
if (jQuery('.slidingDiv').is(":visible") ) {
jQuery('.slidingDiv').stop(true,true).hide("slide", { direction: "left" }, 200);
} else {
jQuery('.slidingDiv').stop(true,true).show("slide", { direction: "left" }, 200);
}
});
First I prevent the link from doing anything on click. Then I add a check if the element is visible or not. When visible I hide it. When hidden I show it. You can change direction to left or right and duration from 200 ms to anything you like.
Edit: I have also added
.stop(true,true)
in order to clearQueue and jumpToEnd. Read about jQuery stop here
The best thing you can do is leave out the action attribute altogether. If you leave it out, the form will be submitted to the document's address, i.e. the same page.
It is also possible to leave it empty, and any browser implementing HTML's form submission algorithm will treat it as equivalent to the document's address, which it does mainly because that's how browsers currently work:
8.
Let action be the submitter element's action.
9.
If action is the empty string, let action be the document's address.Note: This step is a willful violation of RFC 3986, which would require base URL processing here. This violation is motivated by a desire for compatibility with legacy content. [RFC3986]
This definitely works in all current browsers, but may not work as expected in some older browsers ("browsers do weird things with an empty action="" attribute"), which is why the spec strongly discourages authors from leaving it empty:
The
action
andformaction
content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.
use test1
insert into employee(deptid) select deptid from test2.dbo.employee
The postgresql port is defined in your postgresql.conf
file.
For me in Ubuntu 14.04 it is: /etc/postgresql/9.3/main/postgresql.conf
Inside there is a line:
port = 5432
Changing the number there requires restart of postgresql for it to take effect.
Question is asking for two different things:
Second question has been already answered. For the first one, I would do it this way:
if($("#someElement").is(".test")){
// Has class test assigned, eventually combined with other classes
}
else{
// Does not have it
}
To get an array as result from a json string you should set second param as boolean true.
$result = json_decode($json_string, true);
$context = $result['context'];
Otherwise $result will be an std object. but you can access values as object.
$result = json_decode($json_string);
$context = $result->context;
If you are planning to use JdbcTemplate in multiple locations, it would be a good idea to create a Spring Bean for it.
Using Java Config it would be:
@Configuration
public class DBConfig {
@Bean
public DataSource dataSource() {
//create a data source
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
@Bean
public TransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
Then a repository that uses that JdbcTemplate could be:
@Repository
public class JdbcSomeRepository implements SomeRepository {
private final JdbcTemplate jdbcTemplate ;
@Autowired
public JdbcSomeRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
@Transactional
public int someUpdate(SomeType someValue, SomeOtherType someOtherValue) {
return jdbcTemplate.update("INSERT INTO SomeTable(column1, column2) VALUES(?,?)", someValue, someOtherValue)
}
}
The update method from JdbcTemplate that I have used can be found here.
I realise this is many years later but I stumbled across this page from google with the same question.
There is one minor difference on the MSDN page as of now.
VS2005
Note:
If you require a Boolean variable that can also have a value of null, use bool. For more information, see Nullable Types (C# Programming Guide).
VS2010
Note:
If you require a Boolean variable that can also have a value of null, use bool?. For more information, see Nullable Types (C# Programming Guide).
This is what I tried for a right outer join [as per my requirement]:
m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink,
by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"),
by.y=c("company_permalink"), all.y=TRUE)
This worked.
you can simply do this..
<img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>
First thing to do is run this:
SHOW GRANTS;
You will quickly see you were assigned the anonymous user to authenticate into mysql.
Instead of logging into mysql with
mysql
login like this:
mysql -uroot
By default, root@localhost has all rights and no password.
If you cannot login as root without a password, do the following:
Step 01) Add the two options in the mysqld section of my.ini:
[mysqld]
skip-grant-tables
skip-networking
Step 02) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 03) Connect to mysql
mysql
Step 04) Create a password from root@localhost
UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit
Step 05) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 06) Login as root with password
mysql -u root -p
You should be good from there.
Splash screen is a little unusable object in Android: it can not be loaded as soon as possible for hiding the delay of main activity starting. There are two reasons to use it: advertising and network operations.
Implementation as dialog makes jump without delay from splash screen to main UI of activity.
public class SplashDialog extends Dialog {
ImageView splashscreen;
SplashLoader loader;
int splashTime = 4000;
public SplashDialog(Context context, int theme) {
super(context, theme);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
setCancelable(false);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
cancel();
}
}, splashTime);
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white">
<ImageView
android:id="@+id/splashscreen"
android:layout_width="190dp"
android:layout_height="190dp"
android:background="@drawable/whistle"
android:layout_centerInParent="true" />
</RelativeLayout>
And start:
public class MyActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().getCategories() != null && getIntent().getCategories().contains("android.intent.category.LAUNCHER")) {
showSplashScreen();
}
}
protected Dialog splashDialog;
protected void showSplashScreen() {
splashDialog = new SplashDialog(this, R.style.SplashScreen);
splashDialog.show();
}
...
}
if I got it right, you can try
for item in [x for x in checklist if x not in mylist]:
print (item)
You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:
var gent = /I like your Apartment. Could we schedule a viewing\?/g;
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
Use the rand
function:
http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Quote:
A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:
( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014
You need to handle it via ajax
submit.
Something like this:
$(function(){
$('#subscribe-email-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#subscribe-email-form').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
A better way would be to use a django form, and then render the following snippet:
<form>
<div class="modal-body">
<input type="email" placeholder="email"/>
<p>This service will notify you by email should any issue arise that affects your plivo service.</p>
</div>
<div class="modal-footer">
<input type="submit" value="SUBMIT" class="btn"/>
</div>
</form>
via the context - example : {{form}}
.
Here is a flexible approach, it can be used in all cases, in particular:
dataframe
has been obtained from applying previous operations (e.g. not immediately opening a file, or creating a new data frame).First, un-factorize a string using the as.character
function, and, then, re-factorize with the as.factor
(or simply factor
) function:
fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
# Un-factorize (as.numeric can be use for numeric values)
# (as.vector can be use for objects - not tested)
fixed$Type <- as.character(fixed$Type)
fixed[1, ] <- c("lunch", 100)
# Re-factorize with the as.factor function or simple factor(fixed$Type)
fixed$Type <- as.factor(fixed$Type)
You can create a unique index that accept multiple NULLs with a WHERE
clause. See the answer below.
You cannot create a UNIQUE constraint and allow NULLs. You need set a default value of NEWID().
Update the existing values to NEWID() where NULL before creating the UNIQUE constraint.
Unfortunately the solution provided by FaileN doesn't work as stated by Walter Tross.. days may not be 24 hours!
I like to use the PHP Objects where possible and for a bit more flexibility I have come up with the following function:
/**
* @param DateTimeInterface $a
* @param DateTimeInterface $b
* @param bool $absolute Should the interval be forced to be positive?
* @param string $cap The greatest time unit to allow
*
* @return DateInterval The difference as a time only interval
*/
function time_diff(DateTimeInterface $a, DateTimeInterface $b, $absolute=false, $cap='H'){
// Get unix timestamps, note getTimeStamp() is limited
$b_raw = intval($b->format("U"));
$a_raw = intval($a->format("U"));
// Initial Interval properties
$h = 0;
$m = 0;
$invert = 0;
// Is interval negative?
if(!$absolute && $b_raw<$a_raw){
$invert = 1;
}
// Working diff, reduced as larger time units are calculated
$working = abs($b_raw-$a_raw);
// If capped at hours, calc and remove hours, cap at minutes
if($cap == 'H') {
$h = intval($working/3600);
$working -= $h * 3600;
$cap = 'M';
}
// If capped at minutes, calc and remove minutes
if($cap == 'M') {
$m = intval($working/60);
$working -= $m * 60;
}
// Seconds remain
$s = $working;
// Build interval and invert if necessary
$interval = new DateInterval('PT'.$h.'H'.$m.'M'.$s.'S');
$interval->invert=$invert;
return $interval;
}
This like date_diff()
creates a DateTimeInterval
, but with the highest unit as hours rather than years.. it can be formatted as usual.
$interval = time_diff($date_a, $date_b);
echo $interval->format('%r%H'); // For hours (with sign)
N.B. I have used format('U')
instead of getTimestamp()
because of the comment in the manual. Also note that 64-bit is required for post-epoch and pre-negative-epoch dates!
There could be a simpler solution, and more correct: The perimeter of earth is 40,000Km at the equator, about 37,000 on Greenwich (or any longitude) cycle. Thus:
pythagoras = function (lat1, lon1, lat2, lon2) {
function sqr(x) {return x * x;}
function cosDeg(x) {return Math.cos(x * Math.PI / 180.0);}
var earthCyclePerimeter = 40000000.0 * cosDeg((lat1 + lat2) / 2.0);
var dx = (lon1 - lon2) * earthCyclePerimeter / 360.0;
var dy = 37000000.0 * (lat1 - lat2) / 360.0;
return Math.sqrt(sqr(dx) + sqr(dy));
};
I agree that it should be fine-tuned as, I myself said that it's an ellipsoid, so the radius to be multiplied by the cosine varies. But it's a bit more accurate. Compared with Google Maps and it did reduce the error significantly.
You just need to iterate the anchors in the two links.
<a href="#hide2" class="hide" id="hide2">+</a>
<a href="#show2" class="show" id="show2">-</a>
See this jsfiddle http://jsfiddle.net/eJX8z/
I also added some margin to the FAQ call to improve the format.
Here is one way...
(Get-Process powershell | select -First 1).Path
Here is possibly a better way, as it returns the first hit on the path, just like if you had ran Powershell from a command prompt...
(Get-Command powershell.exe).Definition
I'd suggest to use .nth(0)
rather than .first()
if you need to get the first row.
The difference between them is how they handle NaNs, so .nth(0)
will return the first row of group no matter what are the values in this row, while .first()
will eventually return the first not NaN
value in each column.
E.g. if your dataset is :
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4],
'value' : ["first","second","third", np.NaN,
"second","first","second","third",
"fourth","first","second"]})
>>> df.groupby('id').nth(0)
value
id
1 first
2 NaN
3 first
4 first
And
>>> df.groupby('id').first()
value
id
1 first
2 second
3 first
4 first
Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.
Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.
You can do it like... Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id= "data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
This works best for me: Add this at the top of the script:
#!c:/Python27/python.exe
(C:\Python27\python.exe is the path to the python.exe on my machine) Then run the script via:
chmod +x script-name.py && script-name.py
Please follow the below step to remove this warning message.
Step 1: Go to setting in your IDE then find or search the experimentalDecorators.
Step 2: then click on checkbox and warning has been remove in your page.
Thank you Happy Coding ..........
So far the best solution to accept seems to be <img class="center-block" ... />
. But no one has mentioned how center-block
works.
Take Bootstrap v3.3.6 for example:
.center-block {
display: block;
margin-right: auto;
margin-left: auto;
}
The default value of dispaly
for <img>
is inline
. Value block
will display an element as a block element (like <p>
). It starts on a new line, and takes up the whole width. In this way, the two margin settings let the image stay in the middle horizontally.
I've just been trying to use the above in my code and I believe that there is a problem with the Bitmap2BitmapImage function (and possibly the other one as well).
using (MemoryStream ms = new MemoryStream())
Does the above line result in the stream being disposed of? Which means that the returned BitmapImage loses its content.
As I'm a WPF newbie I'm not sure that this is the correct technical explanation, but the code didn't work in my application until I removed the using directive.
If you want to create multiple select dropdowns in the same page:
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
Html:
<form>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>Select an option</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one">
<input type="checkbox" id="one" />First checkbox</label>
<label for="two">
<input type="checkbox" id="two" />Second checkbox</label>
<label for="three">
<input type="checkbox" id="three" />Third checkbox</label>
</div>
</div>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>Select an option</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one">
<input type="checkbox" id="one" />First checkbox</label>
<label for="two">
<input type="checkbox" id="two" />Second checkbox</label>
<label for="three">
<input type="checkbox" id="three" />Third checkbox</label>
</div>
</div>
</form>
Using Jquery:
function showCheckboxes(elethis) {
if($(elethis).next('#checkboxes').is(':hidden')){
$(elethis).next('#checkboxes').show();
$('.selectBox').not(elethis).next('#checkboxes').hide();
}else{
$(elethis).next('#checkboxes').hide();
$('.selectBox').not(elethis).next('#checkboxes').hide();
}
}
Fastest way I know:
bool is_pal(int n) {
if (n % 10 == 0) return 0;
int r = 0;
while (r < n) {
r = 10 * r + n % 10;
n /= 10;
}
return n == r || n == r / 10;
}