Sub GiveAddress()
Dim Chara As String
Chara = ""
Dim Num As Integer
Dim ColNum As Long
ColNum = InputBox("Input the column number")
Do
If ColNum < 27 Then
Chara = Chr(ColNum + 64) & Chara
Exit Do
Else
Num = ColNum / 26
If (Num * 26) > ColNum Then Num = Num - 1
If (Num * 26) = ColNum Then Num = ((ColNum - 1) / 26) - 1
Chara = Chr((ColNum - (26 * Num)) + 64) & Chara
ColNum = Num
End If
Loop
MsgBox "Address is '" & Chara & "'."
End Sub
You can use :
$url=getimagesize(“http://www.flickr.com/photos/27505599@N07/2564389539/”);
if(!is_array($url))
{
$default_image =”…/directoryFolder/junal.jpg”;
}
You can use an extension method like this:
internal static class ArrayExt
{
public static IEnumerable<int> Indices(this Array array, int dimension)
{
for (var i = array.GetLowerBound(dimension); i <= array.GetUpperBound(dimension); i++)
{
yield return i;
}
}
}
And then:
int[,] array = { { 1, 2, 3 }, { 4, 5, 6 } };
foreach (var i in array.Indices(0))
{
foreach (var j in array.Indices(1))
{
Console.Write(array[i, j]);
}
Console.WriteLine();
}
It will be a bit slower than using for loops but probably not an issue in most cases. Not sure if it makes things more readable.
Note that c# arrays can be other than zero-based so you can use a for loop like this:
int[,] array = { { 1, 2, 3 }, { 4, 5, 6 } };
for (var i = array.GetLowerBound(0); i <= array.GetUpperBound(0); i++)
{
for (var j= array.GetLowerBound(1); j <= array.GetUpperBound(1); j++)
{
Console.Write(array[i, j]);
}
Console.WriteLine();
}
With apologies and thanks to yukondude.
I've tried to summarise the timing settings for easy reading, though it's not a perfect job, and I don't touch 'every Friday' or 'only on Mondays' stuff.
This is version 10 - it now:
I am now publishing the script in full here.
https://gist.github.com/myshkin-uk/d667116d3e2d689f23f18f6cd3c71107
If you are using windows8:
command prompt
command prompt
and click Run as administrator
. Then execute the keytool command.SELECT *
FROM TableName
WHERE julianday(substr(date,7)||'-'||substr(date,4,2)||'-'||substr(date,1,2)) BETWEEN julianday('2011-01-11') AND julianday('2011-08-11')
Note that I use the format : dd/mm/yyyy
If you use d/m/yyyy, Change in substr()
Hope this will help you.
I could not get this to work based off the best answer, probably because I'm such a PC noob and missing something obvious. But just FYI in case it helps someone as challenged as me, what has FINALLY worked was through one of the links here (referenced in the answers). This involved simply pasting the following to my .bash_profile
:
env=~/.ssh/agent.env
agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
agent_start () {
(umask 077; ssh-agent >| "$env")
. "$env" >| /dev/null ; }
agent_load_env
# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)
if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
agent_start
ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
ssh-add
fi
unset env
I probably have something configured weird, but was not successful when I added it to my .profile
or .bashrc
. The other real challenge I've run into is I'm not an admin on this computer and can't change the environment variables without getting it approved by IT, so this is a solution for those that can't access that.
You know it's working if you're prompted for your ssh password when you open git bash. Hallelujah something finally worked.
Window -> Preferences -> Java -> Editor -> content assist > enter
".abcdefghijklmnopqrstuvwxyz"
in the Auto activation triggers.
It will allow you to complete your code.
Just because I didn't see AngularJS mentioned and thought that people might want to know...
angular.copy
also provides a method of deep copying objects and arrays.
Profiting from the MS Excel 365 function UNIQUE()
In order to enrich the valid solutions above:
Sub ExampleCall()
Dim rng As Range: Set rng = Sheet1.Range("A2:A11") ' << change to your sheet's Code(Name)
Dim a: a = rng
a = getUniques(a)
arrInfo a
End Sub
Function getUniques(a, Optional ZeroBased As Boolean = True)
Dim tmp: tmp = Application.Transpose(WorksheetFunction.Unique(a))
If ZeroBased Then ReDim Preserve tmp(0 To UBound(tmp) - 1)
getUniques = tmp
End Function
Instead of using http GET, use http POST. And JSON. Or XML
This is how your request stream to the server would look like.
POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)
{users: [user:{id:id1}, user:{id:id2}]}
Or in XML,
POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)
<users><user id='id1'/><user id='id2'/></users>
You could certainly continue using GET as you have proposed, as it is certainly simpler.
/appointments?users=1d1,1d2
Which means you would have to keep your data structures very simple.
However, if/when your data structure gets more complex, http GET and without JSON, your programming and ability to recognise the data gets very difficult.
Therefore,unless you could keep your data structure simple, I urge you adopt a data transfer framework. If your requests are browser based, the industry usual practice is JSON. If your requests are server-server, than XML is the most convenient framework.
JQuery
If your client is a browser and you are not using GWT, you should consider using jquery REST. Google on RESTful services with jQuery.
The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr)
instead of 1fr
as your track size.
The reason why the sublime documented shortcuts for Mac does not work are they are linked to the shortcuts of other Mac functionalities such as Mission Control, Application Windows, etc. Solution: Go to System Preferences -> Keyboard -> Shortcuts and then un-check the options for Mission Control and Application Windows. Now try "Control + Shift [+ Arrow keys]" for selecting the required text and then move the cursor to the required location without any mouse click, so that the selection can be pasted with the correct indentation at the required location.
If you are using Bootstrap 3, this worked for me:
See http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/
.btn-file {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
}_x000D_
.btn-file input[type=file] {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
min-width: 100%;_x000D_
min-height: 100%;_x000D_
font-size: 100px;_x000D_
text-align: right;_x000D_
filter: alpha(opacity=0);_x000D_
opacity: 0;_x000D_
outline: none;_x000D_
background: white;_x000D_
cursor: inherit;_x000D_
display: block;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<span class="btn btn-primary btn-file">_x000D_
Browse...<input type="file">_x000D_
</span>
_x000D_
Which produces the following file input button:
Seriously, check out http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/
I had this due to a simple ordering mistake on my end. I called
[WRONG] docker run <image> <arguments> <command>
When I should have used
docker run <arguments> <image> <command>
Same resolution on similar question: https://stackoverflow.com/a/50762266/6278
pip install -r requirements.txt
for python 2.x
pip3 install -r requirements.txt
for python 3.x
(in case multiple versions are installed)
Yes, there is a way. Its called custom fonts in CSS.Your CSS needs to be modified, and you need to upload those fonts to your website.
The CSS required for this is:
@font-face {
font-family: Thonburi-Bold;
src: url('pathway/Thonburi-Bold.otf');
}
i think it's just the debugger making it simple. Note that a case and "if list" are not ultimately the same. There is is a reason why case blocks normally end with "break". The case stmt actually looks something like this when broken down in assembly.
if myObject.GetType() == type of Car
GOTO START_CAR
else if myObject.GetType() == type of Bike
GOTO START_BIKE
LABEL START_CAR
//do something car
GOTO END
LABEL START_BIKE
//do something bike
GOTO END
LABEL END
If you don't have the break, then the case blocks would be missing the "GOTO END" stmts, and in fact if you landed in the "car" case you'd actually run both sections
//do something car
//do something bike
GOTO END
You can provide a file-like object to the stdin
argument of subprocess.call()
.
The documentation for the Popen
object applies here.
To capture the output, you should instead use subprocess.check_output()
, which takes similar arguments. From the documentation:
>>> subprocess.check_output(
... "ls non_existent_file; exit 0",
... stderr=subprocess.STDOUT,
... shell=True)
'ls: non_existent_file: No such file or directory\n'
Check this out: http://www.codeproject.com/KB/dotnet/MethodName.aspx
If you want to revert the element to the source position if it's not dropped inside a #droppable
element, just save the original parent element of the draggable at the start of the script (instead of the position), and if you verify that it's not dropped into #droppable
, then just restore the parent of #draggable
to this original element.
So, replace this:
}).each(function() {
var top = $(this).position().top;
var left = $(this).position().left;
$(this).data('orgTop', top);
$(this).data('orgLeft', left);
});
with this:
}).each(function() {
$(this).data('originalParent', $(this).parent())
});
Here, you'll have the original parent element of the draggable. Now, you have to restore it's parent in a precise moment.
drop
is called every time the element is dragged out from the droppable, not at the stop. So, you're adding a lot of event callbacks. This is wrong, because you never clean the mouseup
event. A good place where you can hook a callback and check if the element was dropped inside or outside the #droppable
element, is revert
, and you're doing it right now, so, just delete the drop
callback.
When the element is dropped, and needs to know if it should be reverted or not, you know for sure that you'll not have any other interaction from the user until the new drag start. So, using the same condition you're using to know if it should revert or know, let's replace this alert
with a fragment of code that: restores the parent element to the original div, and resets the originalPosition
from the draggable
internals. The originalPosition
proeprty is setted at the time of _mouseStart
, so, if you change the owner of the element, you should reset it, in order to make the animation of revert go to the proper place. So, let's set this to {top: 0, left: 0}
, making the animation go to the origin point of the element:
revert: function(dropped) {
var dropped = dropped && dropped[0].id == "droppable";
if(!dropped) {
$(this).data("draggable").originalPosition = {top:0, left:0}
$(this).appendTo($(this).data('originalParent'))
}
return !dropped;
}
And that's it! You can check this working here: http://jsfiddle.net/eUs3e/1/
Take into consideration that, if in any jQuery's UI update, the behavior of revert
or originalPosition
changes, you'll need to update your code in order to make it work. Keep in mind that.
If you need a solution which doesn't make use of calls to the internals of ui.draggable, you can make your body
an droppable element with greedy
option defined as false
. You'll have to make sure that your body
elements take the full screen.
Good luck!
Serialization is taking a "live" object in memory and converting it to a format that can be stored somewhere (eg. in memory, on disk) and later "deserialized" back into a live object.
Int
32 bits (4byte)
-2,147,483,648 to 2,147,483,647
Long
64 bits (8byte)
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
If your usage of a variable falls in the 32 bit range, use Int
, else use long
. Usually long is used for scientific computations and stuff like that need much accuracy. (eg. value of pi).
An example of choosing one over the other is YouTube's case. They first defined video view counter as an
int
which was overflowed when more than 2,147,483,647 views where received to a popular video. Since anInt
counter cannot store any value more than than its range, YouTube changed the counter to a 64 bit variable and now can count up to 9,223,372,036,854,775,807 views. Understand your data and choose the type which fits as 64 bit variable will take double the memory than a 32 bit variable.
For OGG on Windows: Theoraconverter
In Ubuntu, Try
sudo ufw allow <port_number>
to allow firewall access to both of your server and db.
To remove all files from staging area use -
git reset
To remove specific file use -
git reset "File path"
With ObsoleteAttribute
you can to show the deprecated method.
Obsolete attribute has three constructor:
[Obsolete]:
is a no parameter constructor and is a default using this attribute.[Obsolete(string message)]:
in this format you can getmessage
of why this method is deprecated.[Obsolete(string message, bool error)]:
in this format message is very explicit buterror
means, in compilation time, compiler must be showing error and cause to fail compiling or not.
Numpy has a convenience function, np.fft.fftfreq
to compute the frequencies associated with FFT components:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(301) - 0.5
ps = np.abs(np.fft.fft(data))**2
time_step = 1 / 30
freqs = np.fft.fftfreq(data.size, time_step)
idx = np.argsort(freqs)
plt.plot(freqs[idx], ps[idx])
Note that the largest frequency you see in your case is not 30 Hz, but
In [7]: max(freqs)
Out[7]: 14.950166112956811
You never see the sampling frequency in a power spectrum. If you had had an even number of samples, then you would have reached the Nyquist frequency, 15 Hz in your case (although numpy would have calculated it as -15).
**podria ser algo asi en react y electron**
xslToJson = workbook => {
//var data = [];
var sheet_name_list = workbook.SheetNames[0];
return XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list], {
raw: false,
dateNF: "DD-MMM-YYYY",
header:1,
defval: ""
});
};
handleFile = (file /*:File*/) => {
/* Boilerplate to set up FileReader */
const reader = new FileReader();
const rABS = !!reader.readAsBinaryString;
reader.onload = e => {
/* Parse data */
const bstr = e.target.result;
const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
/* Get first worksheet */
let arr = this.xslToJson(wb);
console.log("arr ", arr)
var dataNueva = []
arr.forEach(data => {
console.log("data renaes ", data)
})
// this.setState({ DataEESSsend: dataNueva })
console.log("dataNueva ", dataNueva)
};
if (rABS) reader.readAsBinaryString(file);
else reader.readAsArrayBuffer(file);
};
handleChange = e => {
const files = e.target.files;
if (files && files[0]) {
this.handleFile(files[0]);
}
};
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('dan red',
(SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')
it is advisable to store your values in lowercase to make retrieval easier and less error prone
INSERT INTO tab_teacher (name_teacher)
VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('rich man', LAST_INSERT_ID())
You don't mention the API version, but since API 11 there's the method WebViewClient.shouldInterceptRequest
Maybe this could help?
Using CSS only is tough, but you could use CSS's background-image
instead of <img>
tags...
Something like this:
HTML
<div id="image"></div>
CSS
#image {
background-image: url(Error.src);
width: //width of image;
height: //height of image;
}
Here is a working fiddle.
Note: I added the border in the CSS on the fiddle just to demonstrate where the image would be.
Here is my variation of Datepicker calendar aligning.
I think that it's pretty nice, because you can control positioning via jQuery UI Position util.
One restriction: jquery.ui.position.js required.
Code:
$('input[name=date]').datepicker({
beforeShow: function(input, inst) {
// Handle calendar position before showing it.
// It's not supported by Datepicker itself (for now) so we need to use its internal variables.
var calendar = inst.dpDiv;
// Dirty hack, but we can't do anything without it (for now, in jQuery UI 1.8.20)
setTimeout(function() {
calendar.position({
my: 'right top',
at: 'right bottom',
collision: 'none',
of: input
});
}, 1);
}
})
If you need just file names like:
dir/subdir/file1.txt
dir/subdir2/file2.sql
dir2/subdir3/file6.php
(which I use as a source for tar command) you will also need to filter out commit messages.
In order to do this I use following command:
git log --name-only --oneline | grep -v '.{7} '
Grep command excludes (-v
param) every line which starts with seven symbols (which is the length of my git hash for git log
command) followed by space. So it filters out every git hash message
line and leave only lines with file names.
One useful improvement is to append uniq
to remove duplicate lines so it will looks as follow:
git log --name-only --oneline | grep -v '.{7} ' | uniq
Create a mysqldump file in the system which has the datas and use pipe to give this mysqldump file as an input to the new system. The new system can be connected using ssh command.
mysqldump -u user -p'password' db-name | ssh user@some_far_place.com mysql -u user -p'password' db-name
no space between -p[password]
Use Measure-Command
Example
Measure-Command { <your command here> | Out-Host }
The pipe to Out-Host
allows you to see the output of the command, which is
otherwise consumed by Measure-Command
.
Other answers are correct, especially the one by Jon Skeet, but outdated.
These old date-time classes have been supplanted by the java.time framework built into Java 8 and later.
If you simply want the current time in UTC, use the Instant
class.
Instant now = Instant.now();
EST
is not a time zone, as explained in the correct Answer by Jon Skeet. Such 3-4 letter codes are neither standardized nor unique, and further the confusion over Daylight Saving Time (DST). Use a proper time zone name in the "continent/region" format.
Perhaps you meant Eastern Standard Time in east coast of north America? Or Egypt Standard Time? Or European Standard Time?
ZoneId zoneId = ZoneId.of( "America/New_York" );
ZoneId zoneId = ZoneId.of( "Africa/Cairo" );
ZoneId zoneId = ZoneId.of( "Europe/Lisbon" );
Use any such ZoneId
object to get the current moment adjusted to a particular time zone to produce a ZonedDateTime
object.
ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;
Adjust that ZonedDateTime into a different time zone by producing another ZonedDateTime object from the first. The java.time framework uses immutable objects rather than changing (mutating) existing objects.
ZonedDateTime zdtGuam = zdt.withZoneSameInstant( ZoneId.of( "Pacific/Guam" ) ) ;
Try
var e = document.getElementById("mySelect");
var selectedOp = e.options[e.selectedIndex].text;
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
Most voted solution is wrong, as cannot work with few buttons in one row.
Best solution will be the following code:
private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (e.ColumnIndex == senderGrid.Columns["Opn"].Index && e.RowIndex >= 0)
{
MessageBox.Show("Opn Click");
}
if (e.ColumnIndex == senderGrid.Columns["VT"].Index && e.RowIndex >= 0)
{
MessageBox.Show("VT Click");
}
}
Write a single function and call it for both of them.
function yourHandler(e){
alert( 'something happened!' );
}
jQuery(':input').change(yourHandler).keyup(yourHandler);
The change() and keyup() event registration functions return the original set, so they can be chained.
** Explicitly request services from other modules using angular.injector **
Just to elaborate on kim3er's answer, you can provide services, factories, etc without changing them to providers, as long as they are included in other modules...
However, I'm not sure if the *Provider
(which is made internally by angular after it processes a service, or factory) will always be available (it may depend on what else loaded first), as angular lazily loads modules.
Note that if you want to re-inject the values that they should be treated as constants.
Here's a more explicit, and probably more reliable way to do it + a working plunker
var base = angular.module('myAppBaseModule', [])
base.factory('Foo', function() {
console.log("Foo");
var Foo = function(name) { this.name = name; };
Foo.prototype.hello = function() {
return "Hello from factory instance " + this.name;
}
return Foo;
})
base.service('serviceFoo', function() {
this.hello = function() {
return "Service says hello";
}
return this;
});
var app = angular.module('appModule', []);
app.config(function($provide) {
var base = angular.injector(['myAppBaseModule']);
$provide.constant('Foo', base.get('Foo'));
$provide.constant('serviceFoo', base.get('serviceFoo'));
});
app.controller('appCtrl', function($scope, Foo, serviceFoo) {
$scope.appHello = (new Foo("app")).hello();
$scope.serviceHello = serviceFoo.hello();
});
push
does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:
import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
arr:[]
}
export default function userState(state = initialUserState, action){
console.log(arr);
switch (action.type){
case ADD_ITEM :
return {
...state,
arr:[...state.arr, action.newItem]
}
default:return state
}
}
So, little late, but MagicTextView will do text outlines, amongst other things.
<com.qwerjk.better_text.MagicTextView
xmlns:qwerjk="http://schemas.android.com/apk/res/com.qwerjk.better_text"
android:textSize="78dp"
android:textColor="#ff333333"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
qwerjk:strokeColor="#FFff0000"
qwerjk:strokeJoinStyle="miter"
qwerjk:strokeWidth="5"
android:text="Magic" />
Note: I made this, and am posting more for the sake of future travelers than the OP. It's borderline spam, but being on-topic, perhaps acceptable?
Here is the fiddle I've made:jsfiddle.net. It shows that props are assigned not in the constructor by default. As I understand they are assinged in the method React.createElement
. Hence super(props)
should be called only when the superclass's constructor manually assings props
to this.props
. If you just extend the React.Component
calling super(props)
will do nothing with props. Maybe It will be changed in the next versions of React.
I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
color: #000; /*Sets the text hover color on navbar*/
}
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
a:hover, .navbar-default .navbar-nav > .active > a:focus {
color: white; /*BACKGROUND color for active*/
background-color: #030033;
}
.navbar-default {
background-color: #0f006f;
border-color: #030033;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #66CCFF; /*change color of links in drop down here*/
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: silver; /*Change rollover cell color here*/
}
.navbar-default .navbar-nav > li > a {
color: white; /*Change active text color here*/
}
This might be caused by the onChange function is not updating the proper value which is mentioned in the input.
Example:
<input type="text" value={this.state.textValue} onChange = {this.changeText}></input>
changeText(event){
this.setState(
{textValue : event.target.value}
);
}
in the onChange function update the mentioned value field.
Install Aptana plugin to your Eclipse installation.
It has built-in FTP support, and it works excellently.
You can:
As a matter of fact the FTP support is so good I'm using Aptana (or Eclipse + Aptana) now for all my FTP needs. Plus I get syntax highlighting/whatever coding support there is. Granted, Eclipse is not the speediest app to launch, but it doesn't bug me so much.
Maybe can help to check that the path to the xsd file has not 'strange' characters like 'é', or similar: I was having the same issue but when I changed to a path without the 'é' the error dissapeared.
I had to add a '.value' to the end of Evert's code to get it working.
Also I combined it with a browser check so that input type="number" field is changed to type="text" in Chrome since 'formnovalidate' doesn't seem to work right now.
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
document.getElementById("input_id").attributes["type"].value = "text";
Apple mail has also been known to make an encoding error on text and csv attachments outbound. In essence it replaces line terminators with soft line breaks on each line, which look like =0D in the encoding. If the attachment is emailed to Outlook, Outlook sees the soft line breaks, removes the = then appends real line breaks i.e. 0D0A so you get 0D0D0A (cr cr lf) at the end of each line. The encoding should be =0D= if it is a mac format file (or any other flavour of unix) or =0D0A= if it is a windows format file.
If you are emailing out from apple mail (in at least mavericks or yosemite), making the attachment not a text or csv file is an acceptable workaround e.g. compress it.
The bug also exists if you are running a windows VM under parallels and email a txt file from there using apple mail. It is the email encoding. Form previous comments here, it looks like netscape had the same issue.
Just in case anyone runs into this in an environment where they cannot set node properties directly (in my case a build tool):
NODE_OPTIONS="--max-old-space-size=4096" node ...
You can set the node options using an environment variable if you cannot pass them on the command line.
A modified python version of @danack's PHP generate script. It generates all files & folders that live inside of build/
to the parent directory, replacing all {{placeholder}}
matches. You need to cd
into build/
before running the script.
File structure
build/
-- (files/folders you want to generate)
-- build.py
sites-available/...
sites-enabled/...
nginx.conf
...
build.py
import os, re
# Configurations
target = os.path.join('.', '..')
variables = {
'placeholder': 'your replacement here'
}
# Loop files
def loop(cb, subdir=''):
dir = os.path.join('.', subdir);
for name in os.listdir(dir):
file = os.path.join(dir, name)
newsubdir = os.path.join(subdir, name)
if name == 'build.py': continue
if os.path.isdir(file): loop(cb, newsubdir)
else: cb(subdir, name)
# Update file
def replacer(subdir, name):
dir = os.path.join(target, subdir)
file = os.path.join(dir, name)
oldfile = os.path.join('.', subdir, name)
with open(oldfile, "r") as fin:
data = fin.read()
for key, replacement in variables.iteritems():
data = re.sub(r"{{\s*" + key + "\s*}}", replacement, data)
if not os.path.exists(dir):
os.makedirs(dir)
with open(file, "w") as fout:
fout.write(data)
# Start variable replacements.
loop(replacer)
Just summarising @libing's answer with a sample that worked for me.
val gson = Gson()
val todoItem: TodoItem = gson.fromJson(this.assets.readAssetsFile("versus.json"), TodoItem::class.java)
private fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}
Without this extension function the same can be achieved by using BufferedReader
and InputStreamReader
this way:
val i: InputStream = this.assets.open("versus.json")
val br = BufferedReader(InputStreamReader(i))
val todoItem: TodoItem = gson.fromJson(br, TodoItem::class.java)
That's how I achieved it, which is not visible (HORRIBLE SOUND....)
<!-- horrible is your mp3 file name any other supported format.-->
<audio controls autoplay hidden="" src="horrible.mp3" type ="audio/mp3"">your browser does not support Html5</audio>
One solution is extend jQuery with a function, e.g.: resized
$.fn.resized = function (callback, timeout) {
$(this).resize(function () {
var $this = $(this);
if ($this.data('resizeTimeout')) {
clearTimeout($this.data('resizeTimeout'));
}
$this.data('resizeTimeout', setTimeout(callback, timeout));
});
};
Sample usage:
$(window).resized(myHandler, 300);
If you want to use optional arguments, but not named arguments, then this approach worked for me. I think this is much easier code to follow.
REM Get argument values. If not specified, use default values.
IF "%1"=="" ( SET "DatabaseServer=localhost" ) ELSE ( SET "DatabaseServer=%1" )
IF "%2"=="" ( SET "DatabaseName=MyDatabase" ) ELSE ( SET "DatabaseName=%2" )
REM Do work
ECHO Database Server = %DatabaseServer%
ECHO Database Name = %DatabaseName%
raw.github.com
is not truely raw access to file asset,
but a view rendered by Rails.
So accessing raw.github.com
is much heavier than needed.
I don't know why raw.github.com
is implemented as a Rails view.
Instead of fix this route issue, GitHub added a X-Content-Type-Options: nosniff
header.
Workaround:
user.github.io/repo
With find and cp only:
mkdir /tmp/targetdir
cd sourcedir
find . -type f -name '*.zip' -exec cp -p --parents {} /tmp/targetdir ";"
find . -type f -name '*.txt' -exec cp -p --parents {} /tmp/targetdir ";"
By adding a few more headers I was able to get the data:
import urllib2,cookielib
site= "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol=JPASSOCIAT&fromDate=1-JAN-2012&toDate=1-AUG-2012&datePeriod=unselected&hiddDwnld=true"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
req = urllib2.Request(site, headers=hdr)
try:
page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e.fp.read()
content = page.read()
print content
Actually, it works with just this one additional header:
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
I always create an IConfig interface with typesafe properties declared for all configuration values. A Config implementation class then wraps the calls to System.Configuration. All your System.Configuration calls are now in one place, and it is so much easier and cleaner to maintain and track which fields are being used and declare their default values. I write a set of private helper methods to read and parse common data types.
Using an IoC framework you can access the IConfig fields anywhere your in application by simply passing the interface to a class constructor. You're also then able to create mock implementations of the IConfig interface in your unit tests so you can now test various configuration values and value combinations without needing to touch your App.config or Web.config file.
Joe's approach is actually the most effective means that I have found for doing this conversation. To elaborate a little bit more on it, you should right click on the project in the package explorer in eclipse and then select to delete it without removing directory or its contents. Next, you select to create a Java project (File -> New -> Java Project) and in the Contents part of the New Java Project dialog box, select 'Create project from existing source'.
The advantage this approach is that source folders will be properly identified. I found that mucking around with the .project file can lead to the entire directory being considered a source folder which is not what you want.
There's a simple command built-in that will pull it:
rvm implode
This will remove the rvm/
directory and all the rubies built within it. In order to remove the final trace of rvm, you need to remove the rvm gem, too:
gem uninstall rvm
If you've made modifications to your PATH
you might want to pull those, too. Check your .bashrc
, .profile
and .bash_profile
files, among other things.
You may also have an /etc/rvmrc
file, or one in your home directory ~/.rvmrc
that may need to be removed as well.
The solution for the error is to add this line at the top of the code:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
I'm curious as to why you would want to do such a thing. Chances are, you should just let garbage collection do its job. In python, garbage collection is pretty deterministic. So you don't really have to worry as much about just leaving objects laying around in memory like you would in other languages (not to say that refcounting doesn't have disadvantages).
Although one thing that you should consider is a wrapper around any objects or resources you may get rid of later.
class foo(object):
def __init__(self):
self.some_big_object = some_resource
def killBigObject(self):
del some_big_object
In response to Null's addendum:
Unfortunately, I don't believe there's a way to do what you want to do the way you want to do it. Here's one way that you may wish to consider:
>>> class manager(object):
... def __init__(self):
... self.lookup = {}
... def addItem(self, name, item):
... self.lookup[name] = item
... item.setLookup(self.lookup)
>>> class Item(object):
... def __init__(self, name):
... self.name = name
... def setLookup(self, lookup):
... self.lookup = lookup
... def deleteSelf(self):
... del self.lookup[self.name]
>>> man = manager()
>>> item = Item("foo")
>>> man.addItem("foo", item)
>>> man.lookup
{'foo': <__main__.Item object at 0x81b50>}
>>> item.deleteSelf()
>>> man.lookup
{}
It's a little bit messy, but that should give you the idea. Essentially, I don't think that tying an item's existence in the game to whether or not it's allocated in memory is a good idea. This is because the conditions for the item to be garbage collected are probably going to be different than what the conditions are for the item in the game. This way, you don't have to worry so much about that.
Lets say that you have a Text
widget called my_text_widget
.
To get input from the my_text_widget
you can use the get
function.
Let's assume that you have imported tkinter
.
Lets define my_text_widget
first, lets make it just a simple text widget.
my_text_widget = Text(self)
To get input from a text
widget you need to use the get
function, both, text
and entry
widgets have this.
input = my_text_widget.get()
The reason we save it to a variable is to use it in the further process, for example, testing for what's the input.
It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.
In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1
for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x
is equivalent to (-x) - 1
.
The reified form of the ~
operator is provided as operator.invert
. To support this operator in your own class, give it an __invert__(self)
method.
>>> import operator
>>> class Foo:
... def __invert__(self):
... print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert
Any class in which it is meaningful to have a "complement" or "inverse" of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__
method to your class. (Note that byte-strings [ex: '\xff'
] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)
For posterity, here's Microsoft's article KB308364 on the subject. This no longer exists on their website, it is from an archive.
How to debug Windows Script Host, VBScript, and JScript files
SUMMARY
The purpose of this article is to explain how to debug Windows Script Host (WSH) scripts, which can be written in any ActiveX script language (as long as the proper language engine is installed), but which, by default, are written in VBScript and JScript. There are certain flags in the registry and, depending on the debugger used, certain required procedures to enable debugging.
MORE INFORMATION
To debug WSH scripts in Microsoft Visual InterDev, the Microsoft Script Debugger, or any other debugger, use the following command-line syntax to start the script:
wscript.exe //d <path to WSH file> This code informs the user when a runtime error has occurred and gives the user a choice to debug the application. Also, the //x flag
can be used, as follows, to throw an immediate exception, which starts the debugger immediately after the script starts running:
wscript.exe //d //x <path to WSH file> After a debug condition exists, the following registry key determines which debugger will be used: HKEY_CLASSES_ROOT\CLSID\{834128A2-51F4-11D0-8F20-00805F2CD064}\LocalServer32
The script debugger should be Msscrdbg.exe, and the Visual InterDev debugger should be
Mdm.exe
.If Visual InterDev is the default debugger, make sure that just-in-time (JIT) functionality is enabled. To do this, follow these steps:
Start Visual InterDev.
On the Tools menu, click Options.
Click Debugger, and then ensure that the Just-In-Time options are selected for both the General and Script categories.
Additionally, if you are trying to debug a .wsf file, make sure that the following registry key is set to 1:
HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug
PROPERTIES
Article ID:
308364
- Last Review: June 19, 2014 - Revision: 3.0Keywords:
kbdswmanage2003swept kbinfo KB308364
I've tried bson = require('../browser_build/bson');
but end up running into another error
Cannot set property 'BSON_BINARY_SUBTYPE_DEFAULT' of undefined
Finally I fixed this issue simply by npm update
, this will fix the bson module in mongoose.
The following configuration taken from MSDN can be applied to enable tracing on your WCF service.
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true" >
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="myUserTraceSource"
switchValue="Information, ActivityTracing">
<listeners>
<add name="xml"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="xml"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="Error.svclog" />
</sharedListeners>
</system.diagnostics>
</configuration>
To view the log file, you can use "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe".
If "SvcTraceViewer.exe" is not on your system, you can download it from the "Microsoft Windows SDK for Windows 7 and .NET Framework 4" package here:
You don't have to install the entire thing, just the ".NET Development / Tools" part.
When/if it bombs out during installation with a non-sensical error, Petopas' answer to Windows 7 SDK Installation Failure solved my issue.
A handy post explaining several mis-understandings about this:
Don't Call The Destructor explicitly
This covers several misconceptions about how the destructor works. Calling it explicitly will not actually destroy your variable, according to the PHP5 doc:
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
The post above does state that setting the variable to null can work in some cases, as long as nothing else is pointing to the allocated memory.
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
A solution using Promises, includes both progress bar & text countdown.
ProgressCountdown(10, 'pageBeginCountdown', 'pageBeginCountdownText').then(value => alert(`Page has started: ${value}.`));_x000D_
_x000D_
function ProgressCountdown(timeleft, bar, text) {_x000D_
return new Promise((resolve, reject) => {_x000D_
var countdownTimer = setInterval(() => {_x000D_
timeleft--;_x000D_
_x000D_
document.getElementById(bar).value = timeleft;_x000D_
document.getElementById(text).textContent = timeleft;_x000D_
_x000D_
if (timeleft <= 0) {_x000D_
clearInterval(countdownTimer);_x000D_
resolve(true);_x000D_
}_x000D_
}, 1000);_x000D_
});_x000D_
}
_x000D_
<div class="row begin-countdown">_x000D_
<div class="col-md-12 text-center">_x000D_
<progress value="10" max="10" id="pageBeginCountdown"></progress>_x000D_
<p> Begining in <span id="pageBeginCountdownText">10 </span> seconds</p>_x000D_
</div>_x000D_
</div>
_x000D_
Value is a string
List = List.OrderBy(c => c.Value.Length).ThenBy(c => c.Value).ToList();
Works
I work with gcc 7.2. I specifically needed a function to be non-inlined, because it had to be instantiated in a library. I tried the __attribute__((noinline))
answer, as well as the asm("")
answer. Neither one solved the problem.
Finally, I figured that defining a static variable inside the function will force the compiler to allocate space for it in the static variable block, and to issue an initialization for it when the function is first called.
This is sort of a dirty trick, but it works.
If you can't edit this part of code where your dict was defined you can still order it at any point in any way you want, like this:
from collections import OrderedDict
order_of_keys = ["key1", "key2", "key3", "key4", "key5"]
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)
$ DOCS="/cygdrive/c/Users/my\ dir/Documents"
Here's your first problem. This puts an actual backslash character into $DOCS
, as you can see by running this command:
$ echo "$DOCS"
/cygdrive/c/Users/my\ `
When defining DOCS
, you do need to escape the space character. You can quote the string (using either single or double quotes) or you can escape just the space character with a backslash. You can't do both. (On most Unix-like systems, you can have a backslash in a file or directory name, though it's not a good idea. On Cygwin or Windows, \
is a directory delimiter. But I'm going to assume the actual name of the directory is my dir
, not my\ dir
.)
$ cd $DOCS
This passes two arguments to cd
. The first is cygdrive/c/Users/my\
, and the second is dir/Documents
. It happens that cd
quietly ignores all but its first argument, which explains the error message:
-bash: cd: /cygdrive/c/Users/my\: No such file or directory
To set $DOCS
to the name of your Documents
directory, do any one of these:
$ DOCS="/cygdrive/c/Users/my dir/Documents"
$ DOCS='/cygdrive/c/Users/my dir/Documents'
$ DOCS=/cygdrive/c/Users/my\ dir/Documents
Once you've done that, to change to your Documents
directory, enclose the variable reference in double quotes (that's a good idea for any variable reference in bash, unless you're sure the value doesn't have any funny characters):
$ cd "$DOCS"
You might also consider giving that directory a name without any spaces in it -- though that can be hard to do in general on Windows.
if you add an #include <algorithm>
then you can use the for_each
function and a lambda function like so:
for_each(data.begin(), data.end(), [](Student *it)
{
std::cout<<it->name;
});
you can read more about the algorithm library at https://en.cppreference.com/w/cpp/algorithm
and about lambda functions in cpp at https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
A very simple way is to use Formatter
(see date time conversions) or more directly String.format
as in
String.format("%tR", new Date())
parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]
{% for dict_item in parent_list %}
{% for key, value in dict_item.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
{% endfor %}
Make sure you have the list of dict items. If you get UnicodeError
may be the value inside the dict contains unicode format. That issue can be solved in your views.py
.
If the dict is unicode
object, you have to encode into utf-8
.
ones
and zeros
, which create arrays full of ones and zeros respectively, take an optional dtype
parameter:
>>> numpy.ones((2, 2), dtype=bool)
array([[ True, True],
[ True, True]], dtype=bool)
>>> numpy.zeros((2, 2), dtype=bool)
array([[False, False],
[False, False]], dtype=bool)
Although this question has several answers, they may now be a little dated.
New readers may prefer to consider the xlsx or "sheetsJS" package, which now seems to now be by far the most popular node package for this use case.
The current top answer recommends excel4node , which does look quite good - but the latter package seems less maintained (and far less popular) than the former.
Answering the question directly, using xlsx:
const XLSX = require('xlsx');
/* create a new blank workbook */
const wb = XLSX.utils.book_new();
// Do stuff, write data
//
//
// write the workbook object to a file
XLSX.writeFile(workbook, 'out.xlsx');
We can achieve the same without using angular-ui. This can be done using angular directives.
First add the directive to the modal.
<div class="modal fade" my-modal ....>...</div>
Create a new angular directive:
app.directive('myModal', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
scope.dismiss = function() {
element.modal('hide');
};
}
}
});
Now call the dismiss() method from your controller.
app.controller('MyCtrl', function($scope, $http) {
// You can call dismiss() here
$scope.dismiss();
});
I am still in my early days with angular js. I know that we should not manipulate the DOM inside the controllers. So I have the DOM manipulation in the directive. I am not sure if this is equally bad. If I have a better alternative, I shall post it here.
The important thing to note is that we cannot simply use ng-hide or ng-show in the view to hide or show the modal. That simply hides the modal and not the modal backdrop. We have to call the modal() instance method to completely remove the modal.
In your case, you are creating an array on the stack and once you leave the function scope, the array will be deallocated. Instead, create a dynamically allocated array and return a pointer to it.
char * returnArray(char *arr, int size) {
char *new_arr = malloc(sizeof(char) * size);
for(int i = 0; i < size; ++i) {
new_arr[i] = arr[i];
}
return new_arr;
}
int main() {
char arr[7]= {1,0,0,0,0,1,1};
char *new_arr = returnArray(arr, 7);
// don't forget to free the memory after you're done with the array
free(new_arr);
}
You can append to the end of a list:
foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])
print(foo) # [1, 2, 3, 4, 5, 4, [8, 7]]
You can edit items in the list like this:
foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4
print(foo) # [1, 2, 3, 8, 5]
Insert integers into the middle of a list:
x = [2, 5, 10]
x.insert(2, 77)
print(x) # [2, 5, 77, 10]
If you are using PHP you might also want to take a look at minify which can minify and combine JavaScript files. The integration is pretty easy and can be done by defined groups of files or an easy query string. Minified files are also cached to reduce the server load and you can add expire headers through minify.
I've created a variant of https://stackoverflow.com/a/17845473/189411
where you can set min and max text size in relation of min and max size of box that you want "check" size. In addition you can check size of dom element different than box where you want apply text size.
You resize text between 19px and 25px on #size-2 element, based on 500px and 960px width of #size-2 element
resizeTextInRange(500,960,19,25,'#size-2');
You resize text between 13px and 20px on #size-1 element, based on 500px and 960px width of body element
resizeTextInRange(500,960,13,20,'#size-1','body');
complete code are there https://github.com/kiuz/sandbox-html-js-css/tree/gh-pages/text-resize-in-range-of-text-and-screen/src
function inRange (x,min,max) {
return Math.min(Math.max(x, min), max);
}
function resizeTextInRange(minW,maxW,textMinS,textMaxS, elementApply, elementCheck=0) {
if(elementCheck==0){elementCheck=elementApply;}
var ww = $(elementCheck).width();
var difW = maxW-minW;
var difT = textMaxS- textMinS;
var rapW = (ww-minW);
var out=(difT/100)*(rapW/(difW/100))+textMinS;
var normalizedOut = inRange(out, textMinS, textMaxS);
$(elementApply).css('font-size',normalizedOut+'px');
console.log(normalizedOut);
}
$(function () {
resizeTextInRange(500,960,19,25,'#size-2');
resizeTextInRange(500,960,13,20,'#size-1','body');
$(window).resize(function () {
resizeTextInRange(500,960,19,25,'#size-2');
resizeTextInRange(500,960,13,20,'#size-1','body');
});
});
So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:
import elementtree.ElementTree as ET
tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')
print thingy.attrib
and got the following back:
{'name': 'NWIS Time Series Instantaneous Values'}
It appears to have found the timeSeries element without needing to use numerical indices.
What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.
The answer of @DanielPlaisted before generally works, but the generic method must be public or one must use BindingFlags.NonPublic | BindingFlags.Instance
! Couldn't post it as a comment for lack of reputation.
Windows Solution:
https://sourceforge.net/projects/win32svn/
1.Download it, then add it to system path.
2.Go to work directory execute "svn clean" and "svn update" in cmd.
Try to insert this:
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
before getting the JDBC Connection.
To multiply a column of numbers with a constant(same number), I have done like this.
Let C2
to C12
be different numbers which need to be multiplied by a single number (constant). Then type the numbers from C2
to C12.
In D2
type 1 (unity) and in E2 type formula =PRODUCT(C2:C12,CONSTANT)
. SELECT RIGHT ICON TO APPLY. NOW DRAG E2
THROUGH E12
. YOU HAVE DONE IT.
C D E=PRODUCT(C2:C12,20)
25 1 500
30 600
35 700
40 800
45 900
50 1000
55 1100
60 1200
65 1300
70 1400
75 1500
You actually don't need jQuery, just CSS. For example, here's some HTML:
<div class="special"></div>
And here's the CSS:
.special
{
cursor: pointer;
}
I always thought that for a task that trivial, I wouldn't want to import anything. But i may be wrong, depending on collections.Counter being faster or not.
items = "Whats the simpliest way to add the list items to a dictionary "
stats = {}
for i in items:
if i in stats:
stats[i] += 1
else:
stats[i] = 1
# bonus
for i in sorted(stats, key=stats.get):
print("%d×'%s'" % (stats[i], i))
I think this may be preferable to using count(), because it will only go over the iterable once, whereas count may search the entire thing on every iteration. I used this method to parse many megabytes of statistical data and it always was reasonably fast.
If you want to split the String
at the /
character, the String.split
method will work:
For example:
String s = "prefix/dir1/dir2/dir3/dir4";
String[] tokens = s.split("/");
for (String t : tokens)
System.out.println(t);
Output
prefix
dir1
dir2
dir3
dir4
Edit
Case with a /
in the prefix, and we know what the prefix is:
String s = "slash/prefix/dir1/dir2/dir3/dir4";
String prefix = "slash/prefix/";
String noPrefixStr = s.substring(s.indexOf(prefix) + prefix.length());
String[] tokens = noPrefixStr.split("/");
for (String t : tokens)
System.out.println(t);
The substring without the prefix "slash/prefix/"
is made by the substring
method. That String
is then run through split
.
Output:
dir1
dir2
dir3
dir4
Edit again
If this String
is actually dealing with file paths, using the File
class is probably more preferable than using string manipulations. Classes like File
which already take into account all the intricacies of dealing with file paths is going to be more robust.
obj.__class__.__name__
will get you any objects name, so you can do this:
class Clazz():
def getName(self):
return self.__class__.__name__
Usage:
>>> c = Clazz()
>>> c.getName()
'Clazz'
Nowadays this generator pattern can be a solution in many situations.
Here an example of sequential console prompts in nodejs using async readline.question function:
var main = (function* () {
// just import and initialize 'readline' in nodejs
var r = require('readline')
var rl = r.createInterface({input: process.stdin, output: process.stdout })
// magic here, the callback is the iterator.next
var answerA = yield rl.question('do you want this? ', r=>main.next(r))
// and again, in a sync fashion
var answerB = yield rl.question('are you sure? ', r=>main.next(r))
// readline boilerplate
rl.close()
console.log(answerA, answerB)
})() // <-- executed: iterator created from generator
main.next() // kick off the iterator,
// runs until the first 'yield', including rightmost code
// and waits until another main.next() happens
Slight change to the FastArray from above:
'pushtest.vbs
imax = 10000000
value = "Testvalue"
s = imax & " of """ & value & """"
t0 = timer 'Fast array
a = array()
ub = UBound(a)
For i = 0 To imax
If i>ub Then
ReDim Preserve a(Int((ub+10)*1.1))
ub = UBound(a)
End If
a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"
MsgBox s
There is no point in checking UBound(a)
in every cycle of the for if we know exactly when it changes.
I've changed it so that it checks does UBound(a)
just before the for starts and then only every time the ReDim
is called
On my computer the old method took 7.52 seconds for an imax of 10 millions.
The new method took 5.29 seconds for an imax of also 10 millions, which signifies a performance increase of over 20% (for 10 millions tries, obviously this percentage has a direct relationship to the number of tries)
Because not all variables are of a serializable nature
Sorry for being late on the party. Depending on your server configuration, You may be required to specify character strictly with lowercase letters utf-8, otherwise it will be ignored. Try this if you end up here searching for solutions and none of answers above helps:
$mail->CharSet = "UTF-8";
should be replaced with:
$mail->CharSet = "utf-8";
Sort of:
class some_class {
static std::vector<std::string> v; // declaration
};
const char *vinit[] = {"one", "two", "three"};
std::vector<std::string> some_class::v(vinit, end(vinit)); // definition
end
is just so I don't have to write vinit+3
and keep it up to date if the length changes later. Define it as:
template<typename T, size_t N>
T * end(T (&ra)[N]) {
return ra + N;
}
1.Go to "/Users/****/.gradle/wrapper/dists/gradle-.-all/*****".
2.Delete the "gradle-.-all.zip.lck" file.
3.Invalidate Cache and Restart.
The best method is given in the docs
$('#myModal').on('shown.bs.modal', function () {
// will only come inside after the modal is shown
});
for more info refer http://getbootstrap.com/javascript/#modals
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
In case you use MVC to accomplish it - you will have to do something like this
<form action="/ControllerName/ActionName" method="post">
<a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
<input type="hidden" name="mess" value=<%=n%>/>
</form>
I just went through some examples here and did not see the MVC one figured it won't hurt to post it.
Then on your Action in the Controller I would just put <HTTPPost>
On the top of it.
I believe if you don't have <HTTPGET>
on the top of it it would still work but explicitly putting it there feels a bit safer.
This isn't really a fixing solution but it may help others. Unlike Nick had said for me it was due to code in my program. I have the mega ADK model. The issue was tied to a switch statement for processing and parsing the returned byte[] from the usb connection to the Android. Its very strange because it would compile perfectly every time but would fail as the OP had stated. I commented it out and it worked fine.
An alternative to the answer Max Fahl gave.
You can define callback function as an arrow function in the parent component so that you won't need to bind that.
@Component({_x000D_
..._x000D_
// unlike this, template: '<child [myCallback]="theCallback.bind(this)"></child>',_x000D_
template: '<child [myCallback]="theCallback"></child>',_x000D_
directives: [ChildComponent]_x000D_
})_x000D_
export class ParentComponent {_x000D_
_x000D_
// unlike this, public theCallback(){_x000D_
public theCallback = () => {_x000D_
..._x000D_
}_x000D_
}_x000D_
_x000D_
@Component({...})_x000D_
export class ChildComponent{_x000D_
//This will be bound to the ParentComponent.theCallback_x000D_
@Input()_x000D_
public myCallback: Function; _x000D_
..._x000D_
}
_x000D_
The easiest answer: jQuery. Do something like this:
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
});
If you want to add content dynamically and still need it to work, and also with more than one form, you can do this:
$('form').live('submit', function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
If you using selenium IDE then you have to click on Ok button manually because when alert message command run that time browser stop working and if you want to click on ok button automatically then you have to use selenium RC or webdriver and below command is for Selenium IDE
In selenium ide use storeeval
command, different type of boxes
storeEval | alert("This is alert box") |
storeEval | prompt("This is prompt box. Please enter the value") | text
storeEval | confirm("this is cofirm box") |
This example might help you. by using simple casting you can get code behind urdu character.
string str = "?????";
char ch = ' ';
int number = 0;
for (int i = 0; i < str.Length; i++)
{
ch = str[i];
number = (int)ch;
Console.WriteLine(number);
}
For anyone who, like me, reads this because they need to update a giant legacy project to 5.6: as the answers here point out, there is no quick fix: you really do need to find each occurrence of the problem manually, and fix it.
The most convenient way I found to find all problematic lines in a project (short of using a full-blown static code analyzer, which is very accurate but I don't know any that take you to the correct position in the editor right away) was using Visual Studio Code, which has a nice PHP linter built in, and its search feature which allows searching by Regex. (Of course, you can use any IDE/Code editor for this that does PHP linting and Regex searches.)
Using this regex:
^(?!.*function).*(\&\$)
it is possible to search project-wide for the occurrence of &$
only in lines that are not a function definition.
This still turns up a lot of false positives, but it does make the job easier.
VSCode's search results browser makes walking through and finding the offending lines super easy: you just click through each result, and look out for those that the linter underlines red. Those you need to fix.
Its also important to note that you will lose the chronological stack trace of the exception if you you have a void return type on an async method. I would recommend returning Task as follows. Going to make debugging a whole lot easier.
public async Task DoFoo()
{
try
{
return await Foo();
}
catch (ProtocolException ex)
{
/* Exception with chronological stack trace */
}
}
If you were using IBM Informix Dynamic Server, you would have a MONEY type which is a minor variant on the DECIMAL or NUMERIC type. It is always a fixed-point type (whereas DECIMAL can be a floating point type). You can specify a scale from 1 to 32, and a precision from 0 to 32 (defaulting to a scale of 16 and a precision of 2). So, depending on what you need to store, you might use DECIMAL(16,2) - still big enough to hold the US Federal Deficit, to the nearest cent - or you might use a smaller range, or more decimal places.
This message will appear if you are using a case-insensitive file system (e.g. on a Mac) and you're trying to capitalize the name (or another change of case). In which case you need to rename to a third, dummy, name:
svn mv file-name file-name_
svn mv file-name_ FILE_Name
svn commit
You need to follow the following steps:
Find line that read follows
Require ip 127.0.0.1
Replace with your workstation IP address:
Require ip 10.1.3.53
Again find the following line:
Allow from 127.0.0.1
Replace as follows:
Allow from 10.1.3.53
Also find deny from all
and comment it in the entire file.
Save and close the file.Restart Apache httpd server
:
# service httpd restart
Edit: Since this is the selected answer and gets best visibility ... please also make sure that PHP is installed, otherwise you get same Forbidden
error.
You can use Task.WhenAll
function that you can pass n tasks; Task.WhenAll
will return a task which runs to completion when all the tasks that you passed to Task.WhenAll
complete. You have to wait asynchronously on Task.WhenAll
so that you'll not block your UI thread:
public async Task DoSomeThing() {
var Task[] tasks = new Task[numTasks];
for(int i = 0; i < numTask; i++)
{
tasks[i] = CallSomeAsync();
}
await Task.WhenAll(tasks);
// code that'll execute on UI thread
}
In database design, a compound key is a set of superkeys that is not minimal.
A composite key is a set that contains a compound key and at least one attribute that is not a superkey
Given table: EMPLOYEES {employee_id, firstname, surname}
Possible superkeys are:
{employee_id}
{employee_id, firstname}
{employee_id, firstname, surname}
{employee_id} is the only minimal superkey, which also makes it the only candidate key--given that {firstname} and {surname} do not guarantee uniqueness. Since a primary key is defined as a chosen candidate key, and only one candidate key exists in this example, {employee_id} is the minimal superkey, the only candidate key, and the only possible primary key.
The exhaustive list of compound keys is:
{employee_id, firstname}
{employee_id, surname}
{employee_id, firstname, surname}
The only composite key is {employee_id, firstname, surname} since that key contains a compound key ({employee_id,firstname}) and an attribute that is not a superkey ({surname}).
You can create external command Run -> External Tools -> External Tools Configuration...
It will be available under Run -> External Tools and can be run using shortcuts.
https://developer.mozilla.org/en/CSS/Media_queries#-moz-device-pixel-ratio
-moz-device-pixel-ratio
Gives the number of device pixels per CSS pixel.
this is almost self-explaining. the number describes the ratio of how much "real" pixels (physical pixerls of the screen) are used to display one "virtual" pixel (size set in CSS).
That should do the trick:
echo `pwd`/`dirname $0`
It might look ugly depending on how it was invoked and the cwd but should get you where you need to go (or you can tweak the string if you care how it looks).
This probably works for a lot of things but it's not enough for Maven and certainly not for the maven compiler plugin.
Check Mike's answer to his own question here: stackoverflow question 24705877
This solved the issue for me both command line AND within eclipse.
Also, @LinGao answer to stackoverflow question 2503658 and the use of the $JAVACMD variable might help but I haven't tested it myself.
On Windows, if you are unwilling or unable to restart the machine see below.
Install Process Explorer: https://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
In Process Explorer, Find > File Handle or DLL ...
Type in the file name mentioned in the error (for my error it was 'git-rebase-todo' but in the question above, 'done').
Process Explorer will highlight the process holding a lock on the file (for me it was 'grep').
Kill the process and you will be able to abort the git action in the standard way.
The Best Way I Can Use My Project.Use hasOwnProperty
in Tricky Way!.
var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();
arr.constructor.prototype.hasOwnProperty('push') //true (This is an Array)
obj.constructor.prototype.hasOwnProperty('push') // false (This is an Object)
Just using
HttpContext.Current.GetOwinContext()
did the trick in my case.
Contrary to all the other posts I suggest NOT using sudo
when installing gems.
Instead I recommend you install RVM and start a happy life with portable gem homes and different version of Ruby all living under one roof.
For the uninitiated, from the documentation:
RVM is a command line tool which allows us to easily install, manage and work with multiple ruby environments and sets of gems.
The reason why installing gems with sudo
is worse than just gem install
is because it installs the gems for ALL USERS as root
. This might be fine if you're the only person using the machine, but if you're not it can cause weirdness.
If you decide you want to blow away all your gems and start again it's much easier, and safer, to do so as a non-root user.
If you decide you want to use RVM
then using sudo
will cause all kinds of weirdness because each Ruby version you install through RVM
has its own GEM_HOME.
Also, it's nice if you can make your development environment as close to your production environment as possible, and in production you'll most likely install gems as a non-root user.
Cordova Apps
:We need to place the google-services.json
file in app root
(I believe; when working with Cordova apps, we are not to get into other folders/files such as Gradle, Java files, platforms, etc; instead only work with them VIA the config.xml
and www
folder) and refer it in the config.xml
like so:
<platform name="android">
<!-- Add this line -->
<resource-file src="google-services.json" target="app/google-services.json" />
</platform>
Firebase App packagename
is same as the id
attribute in <widget id="<packagename>" ... >
are same.For ex:
<!-- config.xml of Cordova App -->
<widget id="com.appFactory.torchapp" ...>
<!--google-serivces.json from generated from Firebase console.-->
{
...
packagename: "com.appFactory.torchapp",
...
}
Good Luck...
I had the same problem & in my case this is what I did
@Html.Partial("~/Views/Cabinets/_List.cshtml", (List<Shop>)ViewBag.cabinets)
and in Partial view
@foreach (Shop cabinet in Model)
{
//...
}
UPDATE You could retrieve the device from buildprop easitly.
static String GetDeviceName() {
Process p;
String propvalue = "";
try {
p = new ProcessBuilder("/system/bin/getprop", "ro.semc.product.name").redirectErrorStream(true).start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
propvalue = line;
}
p.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return propvalue;
}
But keep in mind, this doesn't work on some devices.
I have a similar situation, but I use the key and the certificate in different files.
in my case you can check the matching of the key and the lock by comparing the hashes (see https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/). This helped me to identify inconsistencies.
Use the length
property of the [String]
type:
if ($dbUserName.length -gt 8) {
Write-Output "Please enter more than 8 characters."
$dbUserName = Read-Host "Re-enter database username"
}
Please note that you have to use -gt
instead of >
in your if
condition. PowerShell uses the following comparison operators to compare values and test conditions:
If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:
# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>
If you use it in multiple places, clean the params in the controller:
# your_controller.rb
@params = params.slice(:sort, :per_page)
# view
<%= link_to 'Link', @params.merge(per_page: 20) %>
For those interested, Spring MVC (3.x at least) returns a 400 in this case, which seems wrong to me.
I tested several Google URLs (accounts.google.com) and removed required parameters, and they generally return a 404 in this case.
I would copy Google.
If your file has only one main function that you want to call/expose, then you can also just start the file with:
Param($Param1)
You can then call it e.g. as follows:
.\MyFunctions.ps1 -Param1 'value1'
This makes it much more convenient if you want to easily call just that function without having to import the function.
Use -C
option of tar:
tar zxvf <yourfile>.tar.gz -C /usr/src/
and then, the content of the tar should be in:
/usr/src/<yourfile>
As I want to handle both IPv4
and IPv6
, I am using VARBINARY(16)
and the following SQL CLR
functions to convert the text
IP address presentation to bytes and the reverse:
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true)]
public static SqlBytes GetIPAddressBytesFromString (SqlString value)
{
IPAddress IP;
if (IPAddress.TryParse(value.Value, out IP))
{
return new SqlBytes(IP.GetAddressBytes());
}
else
{
return new SqlBytes();
}
}
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true)]
public static SqlString GetIPAddressStringFromBytes(SqlBytes value)
{
string output;
if (value.IsNull)
{
output = "";
}
else
{
IPAddress IP = new IPAddress(value.Value);
output = IP.ToString();
}
return new SqlString(output);
}
select CUSTOMER_CODE,nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) DEBIT,nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) CREDIT,
nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) BALANCE from TRANSACTION
GROUP BY CUSTOMER_CODE
having nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) > 0
AND (nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0))) > 0
This is a known bug, you can work it around with a hack:
Open up site-packages/requests/packages/urllib3/connectionpool.py
(or otherwise just make a local copy of requests inside your own project), and change the block that says:
def connect(self):
# Add certificate verification
sock = socket.create_connection((self.host, self.port), self.timeout)
# Wrap socket using verification with the root certs in
# trusted_root_certs
self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,
cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs,
server_hostname=self.host,
ssl_version=self.ssl_version)
to:
def connect(self):
# Add certificate verification
sock = socket.create_connection((self.host, self.port), self.timeout)
# Wrap socket using verification with the root certs in
# trusted_root_certs
self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,
cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs,
server_hostname=self.host,
ssl_version=ssl.PROTOCOL_TLSv1)
Otherwise, I suppose there's an override somewhere which is less hacky, but I couldn't find one with a few glances.
NOTE: On a sidenote, requests
from PIP (1.0.4) on a MacOS just works with the URL you provided.
There is also EntityFunctions.TruncateTime
or DbFunctions.TruncateTime
in EF 6.0
I know this has been answered, but this issue confused me so many times I've put up a small reference website to help me remember: https://nitaym.github.io/ourstheirs/
Here are the basics:
$ git checkout master
$ git merge feature
If you want to select the version in master
:
$ git checkout --ours codefile.js
If you want to select the version in feature
:
$ git checkout --theirs codefile.js
$ git checkout feature
$ git rebase master
If you want to select the version in master
:
$ git checkout --ours codefile.js
If you want to select the version in feature
:
$ git checkout --theirs codefile.js
(This is for complete files, of course)
I don't know exactly what you are doing, but float("inf")
gives you a float Infinity, which is greater than any other number.
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
In conclusion:
distutils
doesn't support install_requires
or entry_points
, setuptools
does.
change from distutils.core import setup
in setup.py to from setuptools import setup
or refactor your setup.py to use only distutils
features.
I came here because I hadn't realized entry_points
was only a setuptools
feature.
If you are here wanting to convert setuptools
to distutils
like me:
install_requires
from setup.py and just use requirements.txt with pip
entry_points
to scripts
(doc) and refactor any modules relying on entry_points
to be full scripts with shebangs and an entry point.If you have an array such as
var people = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" }
];
You can use the filter
method of an Array object:
people.filter(function (person) { return person.dinner == "sushi" });
// => [{ "name": "john", "dinner": "sushi" }]
In newer JavaScript implementations you can use a function expression:
people.filter(p => p.dinner == "sushi")
// => [{ "name": "john", "dinner": "sushi" }]
You can search for people who have "dinner": "sushi"
using a map
people.map(function (person) {
if (person.dinner == "sushi") {
return person
} else {
return null
}
}); // => [null, { "name": "john", "dinner": "sushi" }, null]
or a reduce
people.reduce(function (sushiPeople, person) {
if (person.dinner == "sushi") {
return sushiPeople.concat(person);
} else {
return sushiPeople
}
}, []); // => [{ "name": "john", "dinner": "sushi" }]
I'm sure you are able to generalize this to arbitrary keys and values!
You can simply specify a series of images like this:
\includegraphics<1>{A}
\includegraphics<2>{B}
\includegraphics<3>{C}
This will produce three slides with the images A to C in exactly the same position.
Beside sys.argv
, also take a look at the argparse module, which helps define options and arguments for scripts.
The argparse module makes it easy to write user-friendly command-line interfaces.
This should do it for you ^wp.*php$
Matches
wp-comments-post.php
wp.something.php
wp.php
Doesn't match
something-wp.php
wp.php.txt
document.currentScript
document.currentScript
will return the <script>
element whose script is currently being processed.
<script>
var me = document.currentScript;
</script>
defer
& async
)<script type="module">
Giving the script an id attribute will let you easily select it by id from within using document.getElementById()
.
<script id="myscript">
var me = document.getElementById('myscript');
</script>
defer
& async
)id
attribute may cause weird behaviour for scripts in some browsers for some edge casesdata-*
attributeGiving the script a data-*
attribute will let you easily select it from within.
<script data-name="myscript">
var me = document.querySelector('script[data-name="myscript"]');
</script>
This has few benefits over the previous option.
defer
& async
)querySelector()
not compliant in all browsersid
attribute<script>
with id
edge cases. Instead of using the data attributes, you can use the selector to choose the script by source:
<script src="//example.com/embed.js"></script>
In embed.js:
var me = document.querySelector('script[src="//example.com/embed.js"]');
defer
& async
)id
attributeWe can also loop over every script element and check each individually to select the one we want:
<script>
var me = null;
var scripts = document.getElementsByTagName("script")
for (var i = 0; i < scripts.length; ++i) {
if( isMe(scripts[i])){
me = scripts[i];
}
}
</script>
This lets us use both previous techniques in older browsers that don't support querySelector()
well with attributes. For example:
function isMe(scriptElem){
return scriptElem.getAttribute('src') === "//example.com/embed.js";
}
This inherits the benefits and problems of whatever approach is taken, but does not rely on querySelector()
so will work in older browsers.
Since the scripts are executed sequentially, the last script element will very often be the currently running script:
<script>
var scripts = document.getElementsByTagName( 'script' );
var me = scripts[ scripts.length - 1 ];
</script>
defer
& async
)There's software for content-based image retrieval, which does (partially) what you need. All references and explanations are linked from the project site and there's also a short text book (Kindle): LIRE
Do keep in mind that the file.getContentType
could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.
class MyComponent extends Component {
constructor(props){
super(props)
this.myInput = React.createRef()
}
componentDidMount () {
console.log(this.myInput.current.offsetWidth)
}
render () {
return (
// new way - as of [email protected]
<div ref={this.myInput}>some elem</div>
// legacy way
// <div ref={(ref) => this.myInput = ref}>some elem</div>
)
}
}
Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:
function add (a, b) {
return a + b;
}
add(3, 4); // returns 7
This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:
function add (a) {
return function (b) {
return a + b;
}
}
This is a function that takes one argument, a, and returns a function that takes another argument, b, and that function returns their sum.
add(3)(4);
var add3 = add(3);
add3(4);
The first statement returns 7, like the add(3, 4) statement. The second statement defines a new function called add3 that will add 3 to its argument. This is what some people may call a closure. The third statement uses the add3 operation to add 3 to 4, again producing 7 as a result.
If you're running MacOS and have recently upgraded to Catalina, you may need to run brew services restart redis
as suggested in this issue.
A pure solution without jQuery:
function chbg(color) {
document.getElementById('b').style.backgroundColor = color;
}
<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>
JSFiddle: http://jsfiddle.net/YShs2/
this was someone else's answer in the comments...but it should be a real answer:
$("#SomeValue").removeAttr("data-val-required")
tested on MVC 6 with a field having the [Required]
attribute
answer stolen from https://stackoverflow.com/users/73382/rob above
Here is the function I use to prevent chrome and opera from showing the invalid input dialog even when using novalidate.
window.submittingForm = false;
$('input[novalidate]').bind('invalid', function(e) {
if(!window.submittingForm){
window.submittingForm = true;
$(e.target.form).submit();
setTimeout(function(){window.submittingForm = false;}, 100);
}
e.preventDefault();
return false;
});
if you just want to set the style attribute use
$('.handle').attr('style','left: 300px');
Or you can use css method of jQuery to set only one css style property
$('.handle').css('left', '300px');
OR same as key value
$('.handle').css({'left': '300px', position});
In a docker environment, all containers are found in the directory:
/var/lib/docker/aufs/required-docker-id/
To copy the source directory/file to any part of the container, type the given command:
sudo cp -r mydir/ /var/lib/docker/aufs/mnt/required-docker-id/mnt/
Easier way:
#required_number = 18
required_number=input("Insert a number: ")
while required_number != 18
print("Oops! Something is wrong")
required_number=input("Try again: ")
if required_number == '18'
print("That's right!")
#continue the code
The procedure shown at http://off-topic.biz/en/eclipse-hangs-at-startup-showing-only-the-splash-screen/ worked for me:
In other answers:
eclipse -clean -clearPersistedState
is mentioned - which seems to have the same or even better effect.
Here is a script for MacOS (using Macports) and Linux (tested on Ubuntu with Eclipse Equinox) to do the start with an an optional kill of the running eclipse. You might want to adapt the script to your needs. If you add new platforms please edit the script right in this answer.
#!/bin/bash
# WF 2014-03-14
#
# ceclipse:
# start Eclipse cleanly
#
# this script calls eclipse with -clean and -clearPersistedState
# if an instance of eclipse is already running the user is asked
# if it should be killed first and if answered yes the process will be killed
#
# usage: ceclipse
#
#
# error
#
# show an error message and exit
#
# params:
# 1: l_msg - the message to display
error() {
local l_msg="$1"
echo "error: $l_msg" 1>&2
exit 1
}
#
# autoinstall
#
# check that l_prog is available by calling which
# if not available install from given package depending on Operating system
#
# params:
# 1: l_prog: The program that shall be checked
# 2: l_linuxpackage: The apt-package to install from
# 3: l_macospackage: The MacPorts package to install from
#
autoinstall() {
local l_prog=$1
local l_linuxpackage=$2
local l_macospackage=$3
echo "checking that $l_prog is installed on os $os ..."
which $l_prog
if [ $? -eq 1 ]
then
case $os in
# Mac OS
Darwin)
echo "installing $l_prog from MacPorts package $l_macospackage"
sudo port install $l_macospackage
;;
# e.g. Ubuntu/Fedora/Debian/Suse
Linux)
echo "installing $l_prog from apt-package $l_linuxpackage"
sudo apt-get install $l_linuxpackage
;;
# git bash (Windows)
MINGW32_NT-6.1)
error "$l_prog ist not installed"
;;
*)
error "unknown operating system $os"
esac
fi
}
# global operating system variable
os=`uname`
# first set
# eclipse_proc - the name of the eclipse process to look for
# eclipse_app - the name of the eclipse application to start
case $os in
# Mac OS
Darwin)
eclipse_proc="Eclipse.app"
eclipse_app="/Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse"
;;
# e.g. Ubuntu/Fedora/Debian/Suse
Linux)
eclipse_proc="/usr/lib/eclipse//plugins/org.eclipse.equinox.launcher_1.2.0.dist.jar"
eclipse_app=`which eclipse`
;;
# git bash (Windows)
MINGW32_NT-6.1)
eclipse_app=`which eclipse`
error "$os not implemented yet"
;;
*)
error "unknown operating system $os"
esac
# check that pgrep is installed or install it
autoinstall pgrep procps
# check whether eclipse process is running
# first check that we only find one process
echo "looking for $eclipse_proc process"
pgrep -fl "$eclipse_proc"
# can't use -c option on MacOS - use platform independent approach
#eclipse_count=`pgrep -cfl "$eclipse_proc"`
eclipse_count=`pgrep -fl "$eclipse_proc" | wc -l | tr -d ' '`
# check how many processes matched
case $eclipse_count in
# no eclipse - do nothing
0) ;;
# exactly one - offer to kill it
1)
echo "Eclipse is running - shall i kill and restart it with -clean? y/n?"
read answer
case $answer in
y|Y) ;;
*) error "aborted ..." ;;
esac
echo "killing current $eclipse_proc"
pkill -f "$eclipse_proc"
;;
# multiple - this is bogus
*) error "$eclipse_count processes matching $eclipse_proc found - please adapt $0";;
esac
tmp=/tmp/eclipse$$
echo "starting eclipse cleanly ... using $tmp for nohup.out"
mkdir -p $tmp
cd $tmp
# start eclipse with clean options
nohup $eclipse_app -clean -clearPersistedState&
I got same error while running JAVA command. To resolve this, I moved the java path as the first entry in the path, and it resolved the issue. Please have look at this screenshot for reference:
As the name suggests, snapshot refers to a state of project and its dependencies at that moment of time. Whenever maven finds a newer SNAPSHOT of the project, it downloads and replaces the older .jar file of the project in the local repository.
Snapshot versions are used for projects under active development. If your project depends on a software component that is under active development, you can depend on a snapshot release, and Maven will periodically attempt to download the latest snapshot from a repository when you run a build.
think works
Criteria criteria = getSession().createCriteria(clazz);
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"),
Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"),
Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));
String hexToAscii(String s) {
int n = s.length();
StringBuilder sb = new StringBuilder(n / 2);
for (int i = 0; i < n; i += 2) {
char a = s.charAt(i);
char b = s.charAt(i + 1);
sb.append((char) ((hexToInt(a) << 4) | hexToInt(b)));
}
return sb.toString();
}
private static int hexToInt(char ch) {
if ('a' <= ch && ch <= 'f') { return ch - 'a' + 10; }
if ('A' <= ch && ch <= 'F') { return ch - 'A' + 10; }
if ('0' <= ch && ch <= '9') { return ch - '0'; }
throw new IllegalArgumentException(String.valueOf(ch));
}
You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);
example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4));
will merge from B2 to E2. Remember it is zero based indexing (ex. POI version 3.12).
for detail refer BusyDeveloper's Guide
The URLs you link to show how to pop up a dialog with a time picker and another dialog with a date picker. However you need to be aware that you can use those UI widgets directly in your own layout. You could build your own dialog that includes both a TimePicker and DatePicker in the same view, thus accomplishing what I think you are looking for.
In other words, instead of using TimePickerDialog and DatePickerDialog, just use the UI widgets TimePicker and DatePicker directly in your own dialog or activity.
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
Looks like this is unimplemented, as of the time of this writing:
https://github.com/sass/sass/issues/193
For libsass (C/C++ implementation), import works for *.css
the same way as for *.scss
files - just omit the extension:
@import "path/to/file";
This will import path/to/file.css
.
See this answer for further details.
See this answer for Ruby implementation (sass gem)
In python, it is very easy to process the complicated cases like this and only by python's built-in type.
Let me show you how to do !
Method 1: General Case
The way (1 line code) to remove duplicated element in list and still keep sorting order
line = [1, 2, 3, 1, 2, 5, 6, 7, 8]
new_line = sorted(set(line), key=line.index) # remove duplicated element
print(new_line)
You will get the result
[1, 2, 3, 5, 6, 7, 8]
Method 2: Special Case
TypeError: unhashable type: 'list'
The special case to process unhashable (3 line codes)
line=[['16.4966155686595', '-27.59776154691', '52.3786295521147']
,['16.4966155686595', '-27.59776154691', '52.3786295521147']
,['17.6508629295574', '-27.143305738671', '47.534955022564']
,['17.6508629295574', '-27.143305738671', '47.534955022564']
,['18.8051102904552', '-26.688849930432', '42.6912804930134']
,['18.8051102904552', '-26.688849930432', '42.6912804930134']
,['19.5504702331098', '-26.205884452727', '37.7709192714727']
,['19.5504702331098', '-26.205884452727', '37.7709192714727']
,['20.2929416861422', '-25.722717575124', '32.8500163147157']
,['20.2929416861422', '-25.722717575124', '32.8500163147157']]
tuple_line = [tuple(pt) for pt in line] # convert list of list into list of tuple
tuple_new_line = sorted(set(tuple_line),key=tuple_line.index) # remove duplicated element
new_line = [list(t) for t in tuple_new_line] # convert list of tuple into list of list
print (new_line)
You will get the result :
[
['16.4966155686595', '-27.59776154691', '52.3786295521147'],
['17.6508629295574', '-27.143305738671', '47.534955022564'],
['18.8051102904552', '-26.688849930432', '42.6912804930134'],
['19.5504702331098', '-26.205884452727', '37.7709192714727'],
['20.2929416861422', '-25.722717575124', '32.8500163147157']
]
Because tuple is hashable and you can convert data between list and tuple easily
The macro ARRAYELEMENTCOUNT(x)
that everyone is making use of evaluates incorrectly. This, realistically, is just a sensitive matter, because you can't have expressions that result in an 'array' type.
/* Compile as: CL /P "macro.c" */
# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x[0]))
ARRAYELEMENTCOUNT(p + 1);
Actually evaluates as:
(sizeof (p + 1) / sizeof (p + 1[0]));
Whereas
/* Compile as: CL /P "macro.c" */
# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x)[0])
ARRAYELEMENTCOUNT(p + 1);
It correctly evaluates to:
(sizeof (p + 1) / sizeof (p + 1)[0]);
This really doesn't have a lot to do with the size of arrays explicitly. I've just noticed a lot of errors from not truly observing how the C preprocessor works. You always wrap the macro parameter, not an expression in might be involved in.
This is correct; my example was a bad one. But that's actually exactly what should happen. As I previously mentioned p + 1
will end up as a pointer type and invalidate the entire macro (just like if you attempted to use the macro in a function with a pointer parameter).
At the end of the day, in this particular instance, the fault doesn't really matter (so I'm just wasting everyone's time; huzzah!), because you don't have expressions with a type of 'array'. But really the point about preprocessor evaluation subtles I think is an important one.
DF[ ! ( ( DF$sub ==1 & DF$day==2) | ( DF$sub ==3 & DF$day==4) ) , ] # note the ! (negation)
Or if sub is a factor as suggested by your use of quotes:
DF[ ! paste(sub,day,sep="_") %in% c("1_2", "3_4"), ]
Could also use subset:
subset(DF, ! paste(sub,day,sep="_") %in% c("1_2", "3_4") )
(And I endorse the use of which
in Dirk's answer when using "[" even though some claim it is not needed.)
There is no need to kill entire session. In Oracle 18c you could use ALTER SYSTEM CANCEL
:
Cancelling a SQL Statement in a Session
You can cancel a SQL statement in a session using the ALTER SYSTEM CANCEL SQL statement.
Instead of terminating a session, you can cancel a high-load SQL statement in a session. When you cancel a DML statement, the statement is rolled back.
ALTER SYSTEM CANCEL SQL 'SID, SERIAL[, @INST_ID][, SQL_ID]';
If @INST_ID is not specified, the instance ID of the current session is used.
If SQL_ID is not specified, the currently running SQL statement in the specified session is terminated.
The Date functions posted by others are the most correct way to handle this.
However, it's funny you mention the term "floor", because there's a little hack that will run somewhat faster:
CAST(FLOOR(CAST(@dateParam AS float)) AS DateTime)
I have created following class
@Configuration
public class ConfigUtility {
@Autowired
private Environment env;
public String getProperty(String pPropertyKey) {
return env.getProperty(pPropertyKey);
}
}
and called as follow to get application.properties value
@Autowired
private ConfigUtility configUtil;
public AppResponse getDetails() {
AppResponse response = new AppResponse();
String email = configUtil.getProperty("emailid");
return response;
}
unit tested, working as expected...
SELECT *
FROM
(First_query) AS ONE
LEFT OUTER JOIN
(Second_query ) AS TWO ON ONE.First_query_ID = TWO.Second_Query_ID;
Little bit off topic but say i want to remove all 2s from a list. Here's a very elegant way to do that.
void RemoveAll<T>(T item,List<T> list)
{
while(list.Contains(item)) list.Remove(item);
}
With predicate:
void RemoveAll<T>(Func<T,bool> predicate,List<T> list)
{
while(list.Any(predicate)) list.Remove(list.First(predicate));
}
+1 only to encourage you to leave your answer here for learning purposes. You're also right about it being off-topic, but I won't ding you for that because of there is significant value in leaving your examples here, again, strictly for learning purposes. I'm posting this response as an edit because posting it as a series of comments would be unruly.
Though your examples are short & compact, neither is elegant in terms of efficiency; the first is bad at O(n2), the second, absolutely abysmal at O(n3). Algorithmic efficiency of O(n2) is bad and should be avoided whenever possible, especially in general-purpose code; efficiency of O(n3) is horrible and should be avoided in all cases except when you know n will always be very small. Some might fling out their "premature optimization is the root of all evil" battle axes, but they do so naïvely because they do not truly understand the consequences of quadratic growth since they've never coded algorithms that have to process large datasets. As a result, their small-dataset-handling algorithms just run generally slower than they could, and they have no idea that they could run faster. The difference between an efficient algorithm and an inefficient algorithm is often subtle, but the performance difference can be dramatic. The key to understanding the performance of your algorithm is to understand the performance characteristics of the primitives you choose to use.
In your first example, list.Contains()
and Remove()
are both O(n), so a while()
loop with one in the predicate & the other in the body is O(n2); well, technically O(m*n), but it approaches O(n2) as the number of elements being removed (m) approaches the length of the list (n).
Your second example is even worse: O(n3), because for every time you call Remove()
, you also call First(predicate)
, which is also O(n). Think about it: Any(predicate)
loops over the list looking for any element for which predicate()
returns true. Once it finds the first such element, it returns true. In the body of the while()
loop, you then call list.First(predicate)
which loops over the list a second time looking for the same element that had already been found by list.Any(predicate)
. Once First()
has found it, it returns that element which is passed to list.Remove()
, which loops over the list a third time to yet once again find that same element that was previously found by Any()
and First()
, in order to finally remove it. Once removed, the whole process starts over at the beginning with a slightly shorter list, doing all the looping over and over and over again starting at the beginning every time until finally no more elements matching the predicate remain. So the performance of your second example is O(m*m*n), or O(n3) as m approaches n.
Your best bet for removing all items from a list that match some predicate is to use the generic list's own List<T>.RemoveAll(predicate)
method, which is O(n) as long as your predicate is O(1). A for()
loop technique that passes over the list only once, calling list.RemoveAt()
for each element to be removed, may seem to be O(n) since it appears to pass over the loop only once. Such a solution is more efficient than your first example, but only by a constant factor, which in terms of algorithmic efficiency is negligible. Even a for()
loop implementation is O(m*n) since each call to Remove()
is O(n). Since the for()
loop itself is O(n), and it calls Remove()
m times, the for()
loop's growth is O(n2) as m approaches n.
As @Kimble has said, with Jackson 2, using the default formatting is very easy; simply register JodaModule
on your ObjectMapper
.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
For custom serialization/de-serialization of DateTime
, you need to implement your own StdScalarSerializer
and StdScalarDeserializer
; it's pretty convoluted, but anyway.
For example, here's a DateTime
serializer that uses the ISODateFormat
with the UTC time zone:
public class DateTimeSerializer extends StdScalarSerializer<DateTime> {
public DateTimeSerializer() {
super(DateTime.class);
}
@Override
public void serialize(DateTime dateTime,
JsonGenerator jsonGenerator,
SerializerProvider provider) throws IOException, JsonGenerationException {
String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
jsonGenerator.writeString(dateTimeAsString);
}
}
And the corresponding de-serializer:
public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {
public DateTimeDesrializer() {
super(DateTime.class);
}
@Override
public DateTime deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
try {
JsonToken currentToken = jsonParser.getCurrentToken();
if (currentToken == JsonToken.VALUE_STRING) {
String dateTimeAsString = jsonParser.getText().trim();
return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
}
} finally {
throw deserializationContext.mappingException(getValueClass());
}
}
Then tie these together with a module:
public class DateTimeModule extends SimpleModule {
public DateTimeModule() {
super();
addSerializer(DateTime.class, new DateTimeSerializer());
addDeserializer(DateTime.class, new DateTimeDeserializer());
}
}
Then register the module on your ObjectMapper
:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new DateTimeModule());
To elaborate on @Marc B's answer,
$ passwd
$ while [ $? -ne 0 ]; do !!; done
Is nice way of doing the same thing that's not command specific.
The config file is just an XML file, you can open it by:
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
catch (Exception ex)
{
return null;
}
}
and later retrieving values by:
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
A slight variation on Jack's answer to add support for PHP < 7:
// Get an RFC-4122 compliant globaly unique identifier
function get_guid() {
$data = PHP_MAJOR_VERSION < 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
I think Ctrl + Alt + O works when the import is unused but a valid import. However, say you try to import a class from a package that does not exist or no longer exists (which can happen during refactoring), the shortcut command does not work (atleast it didn't for me). If you have more than one file like this, things can get problematic.
To solve this problem, click on Analyse -> Inspect code -> (select your module / project). Let it perform the analysis. Go down to Imports -> Unused imports. Click on the "Delete unnecessary import" button that appears on the right.
git rebase -i HEAD~<quantity of your commits>
(i.e. git rebase -i HEAD~5
)txt
file change pick
keyword to squash
for all commits, except first commit (which is on the top). For top one change it to reword
(which means you will provide a new comment for this commit in the next step) and click SAVE! If in vim, press esc
then save by entering wq!
and press enter.Done
**node_modules
This works for me
recursive approach to ignore all node_modules present in sub folders
the easiest way to do that in angular or angularjs without external modules or directives is using list and datalist HTML5. You just get a json and use ng-repeat for feeding the options in datalist. The json you can fetch it from ajax.
in this example:
then you can add filters and orderby in the ng-reapet
!! list and datalist id must have the same name !!
<input type="text" list="autocompleList" ng-model="ctrl.query" placeholder={{ctrl.msg}}>
<datalist id="autocompleList">
<option ng-repeat="Ids in ctrl.dataList value={{Ids}} >
</datalist>
UPDATE : is native HTML5 but be carreful with the type browser and version. check it out : https://caniuse.com/#search=datalist.
Define the query method with signatures as follows.
@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
@Param("forename") String firstname);
}
For further details, check the Spring Data JPA reference
UNIQUE
constraint (of which a PRIMARY KEY
constraint is a variant). Checks that all values of a given field are unique across the table. This is X
-axis constraint (records)
CHECK
constraint (of which a NOT NULL
constraint is a variant). Checks that a certain condition holds for the expression over the fields of the same record. This is Y
-axis constraint (fields)
FOREIGN KEY
constraint. Checks that a field's value is found among the values of a field in another table. This is Z
-axis constraint (tables).
This is a function online, I created a header file with it, and I use Setcolor();
instead, I hope this helped! You can change the color by choosing any color in the range of 0-256. :) Sadly, I believe CodeBlocks has a later build of the window.h library...
#include <windows.h> //This is the header file for windows.
#include <stdio.h> //C standard library header file
void SetColor(int ForgC);
int main()
{
printf("Test color"); //Here the text color is white
SetColor(30); //Function call to change the text color
printf("Test color"); //Now the text color is green
return 0;
}
void SetColor(int ForgC)
{
WORD wColor;
//This handle is needed to get the current background attribute
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
//csbi is used for wAttributes word
if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
//To mask out all but the background attribute, and to add the color
wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
SetConsoleTextAttribute(hStdOut, wColor);
}
return;
}
Check out GnuWin's make (for windows), which provides a native port for Windows (without requiring a full runtime environment like Cygwin)
If you have winget, you can install via the CLI like this:
winget install GnuWin32.Make
Also, be sure to add the install path to your system PATH
:
C:\Program Files (x86)\GnuWin32\bin
The 2020 answer: it probably doesn't matter
The best answer here was from 2012, so I decided to test for myself. On Chrome for Android, the JS and CSS resources are downloaded in parallel and I could not detect a difference in page rendering speed.
I included a more detailed writeup on my blog
Use $elemMatch to find the array of particular object
db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})
Do a cross-domain AJAX call
Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do
then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Check the following for more information
Using awk
:
awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
Explanation:
/.../
print $0
RS
is built-in awk
variable that is by default set to new-line
. 1
at the end results in printing of every other lines. Using next
before it allows us to prevent the current line since you have already printed it using print $0
.
$ awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
abcd
accd
cdef
line1
line2
line3
line4
line
web
To make changes to the file you can do:
awk '...' input.txt > tmp && mv tmp input.txt
When you create any activity in android file you have to specify it in AndroidManifest.xml like
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MyCreativityActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OrderScreen"></activity>
</application>
The following Links my help you
Database Helper Class:
A helper class to manage database creation and version management.
You create a subclass implementing onCreate(SQLiteDatabase)
, onUpgrade(SQLiteDatabase, int, int)
and optionally onOpen(SQLiteDatabase)
, and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the database is always in a sensible state.
This class makes it easy for ContentProvider
implementations to defer opening and upgrading the database until first use, to avoid blocking application startup with long-running database upgrades.
You need more refer this link Sqlite Helper
Here is the simplest solution to your query
$date=date_create("2013-03-15"); // or your date string
date_add($date,date_interval_create_from_date_string("40 days"));// add number of days
echo date_format($date,"Y-m-d"); //set date format of the result
If you were interested in the function not just the answer here is how it is done:
int ipToInt(int first, int second,
int third, int fourth)
{
return Convert.ToInt32((first * Math.Pow(256, 3))
+ (second * Math.Pow(256, 2)) + (third * 256) + fourth);
}
with first
through fourth
being the segments of the IPv4 address.