if you happened to use NLog in your ASP.net project, you can add a Debugger target:
<targets>
<target name="debugger" xsi:type="Debugger"
layout="${date:format=HH\:mm\:ss}|${pad:padding=5:inner=${level:uppercase=true}}|${message} "/>
and writes logs to this target for the levels you want:
<rules>
<logger name="*" minlevel="Trace" writeTo="debugger" />
now you have console output just like Jetty in "Output" window of VS, and make sure you are running in Debug Mode(F5).
Shortest one liners for ES6+
Filter all falsy values ( ""
, 0
, false
, null
, undefined
)
Object.entries(obj).reduce((a,[k,v]) => (v ? (a[k]=v, a) : a), {})
Filter null
and undefined
values:
Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {})
Filter ONLY null
Object.entries(obj).reduce((a,[k,v]) => (v === null ? a : (a[k]=v, a)), {})
Filter ONLY undefined
Object.entries(obj).reduce((a,[k,v]) => (v === undefined ? a : (a[k]=v, a)), {})
Recursive Solutions: Filters null
and undefined
For Objects:
const cleanEmpty = obj => Object.entries(obj)
.map(([k,v])=>[k,v && typeof v === "object" ? cleanEmpty(v) : v])
.reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});
For Objects and Arrays:
const cleanEmpty = obj => {
if (Array.isArray(obj)) {
return obj
.map(v => (v && typeof v === 'object') ? cleanEmpty(v) : v)
.filter(v => !(v == null));
} else {
return Object.entries(obj)
.map(([k, v]) => [k, v && typeof v === 'object' ? cleanEmpty(v) : v])
.reduce((a, [k, v]) => (v == null ? a : (a[k]=v, a)), {});
}
}
Personally, I try to always use this when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see this used consistently, they will know if they are looking at a member variable or not.
You may face two errors while testing tomcat server startup.
Fixes -
The reason for choosing this option is, When the default option is given as eclipse location, we will see 404 error as it changes Catalina parameters (sometimes). But if we change it to Tomcat location, it works fine.
Basically
extern linkage
variable is visible in all filesinternal linkage
variable is visible in single file.Explain: const variables internally link by default unless otherwise declared as extern
external linkage
const
global variable is internal linkage
extern const
global variable is external linkage
A pretty good material about linkage in C++
http://www.goldsborough.me/c/c++/linker/2016/03/30/19-34-25-internal_and_external_linkage_in_c++/
It's a lambda expression.
It means that, from the listOfCars, arg0 is one of the items of that list. With that item he is going to do, hence the ->, whatever is inside of the brackets.
In this example, he's going to return a list of cars that fit the condition
Car.SEDAN == ((Car)arg0).getStyle();
Bash supports arithmetic expansion with $(( expression ))
. For example:
$ echo $(( 5 * 5 ))
25
A number of utilities provide arithmetic, including bc and expr.
$ echo '5 * 5' | /usr/bin/bc
25
$ /usr/bin/expr 5 \* 5
25
There's a jQuery Timer plugin you may want to try
None of the above answers helped me. I was struggling to understand why code works in Java but not in Kotlin.
Then I figured it out from this thread.
You have to make class and member functions open
, otherwise NPE was being thrown.
After making function open
tests started to pass.
You might as well consider using compiler's "all-open" plugin:
Kotlin has classes and their members final by default, which makes it inconvenient to use frameworks and libraries such as Spring AOP that require classes to be open. The
all-open
compiler plugin adapts Kotlin to the requirements of those frameworks and makes classes annotated with a specific annotation and their members open without the explicit open keyword.
Have look on project
Target -> Buid Phases -> Copy Bundle Resources
You will find your xib/storyborad with red color.
Just remove it.Also remove all references of missing file from project.
Now drag this storyboard/xib file again to this Copy Bundle Resources
.It will still show you file with red color but dont worry about it.
Just clean and build project.
Now you will get your project running again successfully!!
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
There are some more interesting ones along with related info.
If you want to check for local files first do:
@font-face {
font-family: 'Green Sans Web';
src:
local('Green Web'),
local('GreenWeb-Regular'),
url('GreenWeb.ttf');
}
There is a more elaborate description of what to do here.
This saved me a lot of time debugging what's wrong. In many cases are just mirrors out of date. This function can install multiple packages with their dependencies using https://cran.rstudio.com/
:
packages <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE, repos='https://cran.rstudio.com/')
sapply(pkg, require, character.only = TRUE)
}
packages(c("foo", "bar", "baz"))
For i=1 To 10
Do
'Do everything in here and
If I_Dont_Want_Finish_This_Loop Then
Exit Do
End If
'Of course, if I do want to finish it,
'I put more stuff here, and then...
Loop While False 'quit after one loop
Next i
In ESC mode, when set mouse=a, select the text using mouse. This would enable the visual mode in vim. Then you can press 'y' to yank the selected text and 'p' to paste it wherever you want. This happens only within vim.
It's an abstract reference value to a resource, often memory or an open file, or a pipe.
Properly, in Windows, (and generally in computing) a handle is an abstraction which hides a real memory address from the API user, allowing the system to reorganize physical memory transparently to the program. Resolving a handle into a pointer locks the memory, and releasing the handle invalidates the pointer. In this case think of it as an index into a table of pointers... you use the index for the system API calls, and the system can change the pointer in the table at will.
Alternatively a real pointer may be given as the handle when the API writer intends that the user of the API be insulated from the specifics of what the address returned points to; in this case it must be considered that what the handle points to may change at any time (from API version to version or even from call to call of the API that returns the handle) - the handle should therefore be treated as simply an opaque value meaningful only to the API.
I should add that in any modern operating system, even the so-called "real pointers" are still opaque handles into the virtual memory space of the process, which enables the O/S to manage and rearrange memory without invalidating the pointers within the process.
This might be a simple solution to achieve this:
INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
FROM dual
WHERE NOT EXISTS (SELECT 1
FROM funds
WHERE ID = 23
AND date = DATE('2013-02-12'));
p.s. alternatively (if ID
a primary key):
INSERT INTO funds (ID, date, price)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need
see this Fiddle.
Try creating a handler for select event on those elements and in the handler you can clear the selection.
Take a look at this:
Clear Text Selection with JavaScript
It's an example of clearing the selection. You'd only need to modify it to work only on the specific element that you need.
Use WebRequest. From Scott Hanselman:
public static string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending.
//Post'ed Faked Forms should be name=value&
byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream ();
os.Write (bytes, 0, bytes.Length); //Push it out there
os.Close ();
System.Net.WebResponse resp = req.GetResponse();
if (resp== null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
Java Language Support extension provides basic features for the Java programming language. Current editing features include:
And if you wish to contribute then the project has been moved to its own GitHub repository
try {
java.util.Collections.sort(data,
new Comparator<Map<String, String>>() {
SimpleDateFormat sdf = new SimpleDateFormat(
"MM/dd/yyyy");
public int compare(final Map<String, String> map1,
final Map<String, String> map2) {
Date date1 = null, date2 = null;
try {
date1 = sdf.parse(map1.get("Date"));
date2 = sdf.parse(map2.get("Date"));
} catch (ParseException e) {
e.printStackTrace();
}
if (date1.compareTo(date2) > 0) {
return +1;
} else if (date1.compareTo(date2) == 0) {
return 0;
} else {
return -1;
}
}
});
} catch (Exception e) {
}
It's worth noting that Java can overload a method such as abs
so that it works with an integer or a double. In C, overloading doesn't exist, so you need different functions for integer versus double.
according to dr. hipp in a recent list post:
CREATE TABLE whatever(
....
timestamp DATE DEFAULT (datetime('now','localtime')),
...
);
One thing to keep in mind is :
The name 'ReentrantLock' gives out a wrong message about other locking mechanism that they are not re-entrant. This is not true. Lock acquired via 'synchronized' is also re-entrant in Java.
Key difference is that 'synchronized' uses intrinsic lock ( one that every Object has ) while Lock API doesn't.
mootools example:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});
I made a CSS approach to this that is sized by the viewport width, but maxes out at 100% of the viewport height. It doesn't require box-sizing:border-box
. If a pseudo element cannot be used, the pseudo-code's CSS can be applied to a child. Demo
.container {
position: relative;
max-width:100vh;
max-height:100%;
margin:0 auto;
overflow: hidden;
}
.container:before {
content: "";
display: block;
margin-top: 100%;
}
.child {
position: absolute;
top: 0;
left: 0;
}
Support table for viewport units
I wrote about this approach and others in a CSS-Tricks article on scaling responsive animations that you should check out.
I would suggest following extension methods for string parsing into int value with ability to define default value in case parsing is not possible:
public static int ParseInt(this string value, int defaultIntValue = 0)
{
return int.TryParse(value, out var parsedInt) ? parsedInt : defaultIntValue;
}
public static int? ParseNullableInt(this string value)
{
if (string.IsNullOrEmpty(value))
return null;
return value.ParseInt();
}
While the w32tm /resync
in theory does the job, it only does so under certain conditions. When "down to the millisecond" matters, however, I found that Windows wouldn't actually make the adjustment; as if "oh, I'm off by 2.5 seconds, close enough bro, nothing to see or do here".
In order to truly force the resync (Windows 7):
w32tm /resync
watch -n 0.1 date
on a Linux machine on the network that I had SSH'd over into)--- Rapid Method ---
net start w32time
(Time Service must be running)time 8
(where 8 may be replaced by any 'hour' value, presumably 0-23)w32tm /resync
Use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider
API
A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates.
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>);
scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));
for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
System.out.println(bd.getBeanClassName());
This is meant half as a joke, since the question is kinda silly.
public static bool IsNull (this System.Object o)
{
return (o == null);
}
This is an extension method, however it extends System.Object, so every object you use now has an IsNull() method.
Then you can save tons of code by doing:
if (foo.IsNull())
instead of the super lame:
if (foo == null)
These instructions work fine in Linux. In Windows, they are not working for me today.
I found an answer that helps for me, maybe this will help OP. I kissed a lot of frogs trying to solve this. You need to add your new non-standard-named key file with "ssh-add"! Here's instruction for the magic bullet: Generating a new SSH key and adding it to the ssh-agent. Once you know the magic search terms are "add key with ssh-add in windows" you find plenty of other links.
If I were using Windows often, I'd find some way to make this permanent. https://github.com/raeesbhatti/ssh-agent-helper.
The ssh key agent looks for default "id_rsa" and other keys it knows about. The key you create with a non-standard name must be added to the ssh key agent.
First, I start the key agent in the Git BASH shell:
$ eval $(ssh-agent -s)
Agent pid 6276
$ ssh-add ~/.ssh/Paul_Johnson-windowsvm-20180318
Enter passphrase for /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318:
Identity added: /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318 (/c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318)
Then I change to the directory where I want to clone the repo
$ cd ~/Documents/GIT/
$ git clone [email protected]:test/spr2018.git
Cloning into 'spr2018'...
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.
I fought with this for a long long time.
Here are other things I tried along the way
At first I was certain it is because of file and folder permissions. On Linux, I have seen .ssh settings rejected if the folder is not set at 700. Windows has 711. In Windows, I cannot find any way to make permissions 700.
After fighting with that, I think it must not be the problem. Here's why. If the key is named "id_rsa" then git works! Git is able to connect to server. However, if I name the key file something else, and fix the config file in a consistent way, no matter what, then git fails to connect. That makes me think permissions are not the problem.
A thing you can do to debug this problem is to watch verbose output from ssh commands using the configured key.
In the git bash shell, run this
$ ssh -T git@name-of-your-server
Note, the user name should be "git" here. If your key is set up and the config file is found, you see this, as I just tested in my Linux system:
$ ssh -T [email protected]
Welcome to GitLab, Paul E. Johnson!
On the other hand, in Windows I have same trouble you do before applying "ssh-add". It wants git's password, which is always a fail.
$ ssh -T [email protected]
[email protected]'s password:
Again, If i manually copy my key to "id_rsa" and "id_rsa.pub", then this works fine. After running ssh-add, observe the victory in Windows Git BASH:
$ ssh -T [email protected]
Welcome to GitLab, Paul E. Johnson!
You would hear the sound of me dancing with joy if you were here.
To figure out what was going wrong, you can I run 'ssh' with "-Tvv"
In Linux, I see this when it succeeds:
debug1: Offering RSA public key: pauljohn@pols124
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug2: input_userauth_pk_ok: fp SHA256:bCoIWSXE5fkOID4Kj9Axt2UOVsRZz9JW91RQDUoasVo
debug1: Authentication succeeded (publickey).
In Windows, when this fails, I see it looking for default names:
debug1: Found key in /c/Users/pauljohn32/.ssh/known_hosts:1
debug2: set_newkeys: mode 1
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 4294967296 blocks
debug2: key: /c/Users/pauljohn32/.ssh/id_rsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_dsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_ecdsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_ed25519 (0x0)
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_rsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_dsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ecdsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ed25519
debug2: we did not send a packet, disable method
debug1: Next authentication method: password
[email protected]'s password:
That was the hint I needed, it says it finds my ~/.ssh/config file but never tries the key I want it to try.
I only use Windows once in a long while and it is frustrating. Maybe the people who use Windows all the time fix this and forget it.
y = (y != undefined) ? y : x;
The parenthesis are not necessary, I just add them because I think it's easier to read this way.
I found that using
<mvc:default-servlet-handler />
in the spring MVC servlet bean definition file works for me. It passes any request that isn't handled by a registered MVC controller on to the container's original default handler, which should serve it as static content. Just make sure you have no controller registered that handles everything, and it should work just fine. Not sure why @logixplayer suggests URL rewriting; you can achieve the effect he's looking for just adequately using Spring MVC alone.
Why are you using a List if you want to initialize it with a fixed value ? I can understand that -for the sake of performance- you want to give it an initial capacity, but isn't one of the advantages of a list over a regular array that it can grow when needed ?
When you do this:
List<int> = new List<int>(100);
You create a list whose capacity is 100 integers. This means that your List won't need to 'grow' until you add the 101th item. The underlying array of the list will be initialized with a length of 100.
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xyz.name"
minSdkVersion 14
targetSdkVersion 27
versionCode 7
versionName "1.6"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.volley:volley:1.0.0'
implementation 'com.wang.avi:library:2.1.3'
implementation 'com.android.support:design:27.1.0'
implementation 'com.android.support:support-v4:27.1.0'
implementation 'de.hdodenhof:circleimageview:2.1.0'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.theartofdev.edmodo:android-image-cropper:2.6.0'
implementation 'com.loopj.android:android-async-http:1.4.9'
implementation 'com.google.firebase:firebase-messaging:11.8.0'
implementation 'com.felipecsl.asymmetricgridview:library:2.0.1'
implementation 'com.android.support:recyclerview-v7:27.1.0'
implementation 'com.github.darsh2:MultipleImageSelect:3474549'
implementation 'it.sephiroth.android.library.horizontallistview:hlistview:1.2.2'
implementation 'com.android.support:multidex:1.0.1'
}
apply plugin: 'com.google.gms.google-services'
Note: update your all support library to 27.1.0 like above and remove duplicates
The answer I came up with:
const int16_t TM_MON_DAYS_ACCU[12] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
int tm_is_leap_year(unsigned year) {
return ((year & 3) == 0) && ((year % 400 == 0) || (year % 100 != 0));
}
// The "Doomsday" the the day of the week of March 0th,
// i.e the last day of February.
// In common years January 3rd has the same day of the week,
// and on leap years it's January 4th.
int tm_doomsday(int year) {
int result;
result = TM_WDAY_TUE;
result += year; // I optimized the calculation a bit:
result += year >>= 2; // result += year / 4
result -= year /= 25; // result += year / 100
result += year >>= 2; // result += year / 400
return result;
}
void tm_get_wyday(int year, int mon, int mday, int *wday, int *yday) {
int is_leap_year = tm_is_leap_year(year);
// How many days passed since Jan 1st?
*yday = TM_MON_DAYS_ACCU[mon] + mday + (mon <= TM_MON_FEB ? 0 : is_leap_year) - 1;
// Which day of the week was Jan 1st of the given year?
int jan1 = tm_doomsday(year) - 2 - is_leap_year;
// Now just add these two values.
*wday = (jan1 + *yday) % 7;
}
with these defines (matching struct tm
of time.h
):
#define TM_WDAY_SUN 0
#define TM_WDAY_MON 1
#define TM_WDAY_TUE 2
#define TM_WDAY_WED 3
#define TM_WDAY_THU 4
#define TM_WDAY_FRI 5
#define TM_WDAY_SAT 6
#define TM_MON_JAN 0
#define TM_MON_FEB 1
#define TM_MON_MAR 2
#define TM_MON_APR 3
#define TM_MON_MAY 4
#define TM_MON_JUN 5
#define TM_MON_JUL 6
#define TM_MON_AUG 7
#define TM_MON_SEP 8
#define TM_MON_OCT 9
#define TM_MON_NOV 10
#define TM_MON_DEC 11
for i in arr1:
if i in arr2:
return 1
return 0
arr1=[1,2,5]
arr2=[2,4,15]
q=checkarrayequalornot(arr1,arr2)
print(q)
>>0
In my case, I used a keyword as a column name, which resulted in ERROR: operator does not exist: name = bigint
The solution was to use double quotes around the column name.
I got the same problem when I try to use FirstOrDefaultAsync()
in the async method in the code below. And when I fixed FirstOrDefault()
- the problem was solved!
_context.Issues.Add(issue);
await _context.SaveChangesAsync();
int userId = _context.Users
.Where(u => u.UserName == Options.UserName)
.FirstOrDefaultAsync()
.Id;
...
If you are programming in PHP, it is useful to split lines by \n
and then trim()
each line (provided you don't care about whitespace) to give you a "clean" line regardless.
foreach($line in explode("\n", $data))
{
$line = trim($line);
...
}
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd
greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)
).
A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.
FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF
:loopbody
ECHO %1
DEL %1
GOTO :EOF
Well, I came across another sweet solution.
window['functioName'](params);
Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.
So instead, you can use the xhr2 module. In other words:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
becomes:
var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();
But ... of course, there are more popular modules like Axios, because -for example- uses promises:
// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
In mvc 4 Could be rendered with Underscore(" _ ")
Razor:
@Html.ActionLink("Vote", "#", new { id = item.FileId, }, new { @class = "votes", data_fid = item.FileId, data_jid = item.JudgeID, })
Rendered Html
<a class="votes" data-fid="18587" data-jid="9" href="/Home/%23/18587">Vote</a>
It is strange, that no one yet has suggested the most robust way of closing a feature branches... You can just combine merge commit with --close-branch flag (i.e. commit modified files and close the branch simultaneously):
hg up feature-x
hg merge default
hg ci -m "Merge feature-x and close branch" --close-branch
hg branch default -f
So, that is all. No one extra head on revgraph. No extra commit.
What you posted literally means "Find any divs that are inside of section divs and are the first child of their parent." The sub contains one tag that matches that description.
It is unclear to me whether you want both children of the main div or not. If so, use this:
div.section > div
If you only want the header, use this:
div.section > div:first-child
Using the >
changes the description to: "Find any divs that are the direct descendents of section divs" which is what you want.
Please note that all major browsers support this method, except IE6. If IE6 support is mission-critical, you will have to add classes to the child divs and use that, instead. Otherwise, it's not worth caring about.
First off:
public class ProfileCollection implements Iterable<Profile> {
Second:
return m_Profiles.get(m_ActiveProfile);
This is a guess. Generally recursion probably doesn't beat looping often or ever on problems of decent size if both are using really good algorithms(not counting implementation difficulty) , it may be different if used with a language w/ tail call recursion(and a tail recursive algorithm and with loops also as part of the language)-which would probably have very similar and possibly even prefer recursion some of the time.
For JPG Image compression you can use the best compression technique called JIC (Javascript Image Compression)This will definitely help you -->https://github.com/brunobar79/J-I-C
You must activate virtual environment where you have installed django. Then run this command - python manage.py runserver
Suppose there are 2 tables TableA and TableB with only 2 columns (Id, Data) and following data:
TableA:
+----+---------+
| Id | Data |
+----+---------+
| 1 | DataA11 |
| 1 | DataA12 |
| 1 | DataA13 |
| 2 | DataA21 |
| 3 | DataA31 |
+----+---------+
TableB:
+----+---------+
| Id | Data |
+----+---------+
| 1 | DataB11 |
| 2 | DataB21 |
| 2 | DataB22 |
| 2 | DataB23 |
| 4 | DataB41 |
+----+---------+
Inner Join on column Id
will return columns from both the tables and only the matching records:
.----.---------.----.---------.
| Id | Data | Id | Data |
:----+---------+----+---------:
| 1 | DataA11 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA12 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA13 | 1 | DataB11 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB21 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB22 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB23 |
'----'---------'----'---------'
Left Join (or Left Outer join) on column Id
will return columns from both the tables and matching records with records from left table (Null values from right table):
.----.---------.----.---------.
| Id | Data | Id | Data |
:----+---------+----+---------:
| 1 | DataA11 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA12 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA13 | 1 | DataB11 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB21 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB22 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB23 |
:----+---------+----+---------:
| 3 | DataA31 | | |
'----'---------'----'---------'
Right Join (or Right Outer join) on column Id
will return columns from both the tables and matching records with records from right table (Null values from left table):
+-----------------------------+
¦ Id ¦ Data ¦ Id ¦ Data ¦
+----+---------+----+---------¦
¦ 1 ¦ DataA11 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA12 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA13 ¦ 1 ¦ DataB11 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB21 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB22 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB23 ¦
¦ ¦ ¦ 4 ¦ DataB41 ¦
+-----------------------------+
Full Outer Join on column Id
will return columns from both the tables and matching records with records from left table (Null values from right table) and records from right table (Null values from left table):
+-----------------------------+
¦ Id ¦ Data ¦ Id ¦ Data ¦
¦----+---------+----+---------¦
¦ - ¦ ¦ ¦ ¦
¦ 1 ¦ DataA11 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA12 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA13 ¦ 1 ¦ DataB11 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB21 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB22 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB23 ¦
¦ 3 ¦ DataA31 ¦ ¦ ¦
¦ ¦ ¦ 4 ¦ DataB41 ¦
+-----------------------------+
Left Semi Join on column Id
will return columns only from left table and matching records only from left table:
+--------------+
¦ Id ¦ Data ¦
+----+---------¦
¦ 1 ¦ DataA11 ¦
¦ 1 ¦ DataA12 ¦
¦ 1 ¦ DataA13 ¦
¦ 2 ¦ DataA21 ¦
+--------------+
You can override Text behaviour by adding this in any of your component using Text:
let oldRender = Text.prototype.render;
Text.prototype.render = function (...args) {
let origin = oldRender.call(this, ...args);
return React.cloneElement(origin, {
style: [{color: 'red', fontFamily: 'Arial'}, origin.props.style]
});
};
Edit: since React Native 0.56, Text.prototype
is not working anymore. You need to remove the .prototype
:
let oldRender = Text.render;
Text.render = function (...args) {
let origin = oldRender.call(this, ...args);
return React.cloneElement(origin, {
style: [{color: 'red', fontFamily: 'Arial'}, origin.props.style]
});
};
if setting height to 100% doesn't work, try min-height=100% for div. You still have to set the html tag.
html {
height: 100%;
margin: 0px;
padding: 0px;
position: relative;
}
#fullHeight{
width: 450px;
**min-height: 100%;**
background-color: blue;
}
It is Aug 2011, Xcode 4.1 and it continues to be nightmare. Why not allow Cmd+ and Cmd- like everywhere else. < end rant >
As suggested by other respondents I suggest that you copy your preferred theme before you tweak the fonts for there is no ease way to undo.
In my case, all I wanted to do was increase the font size. Mercifully you can select multiple items (Shift+select or Cmd+select) and set the font for all the ones selected in one fell swoop.
Minor relief for a major irritation.
For Java applications, i.e. programs that are delivered (usually) as .jar
files and started with java -jar xxx.jar
or via a shortcut that does the same, the JRE that will be launched will be the first one found on the PATH
.
If you installed a JRE or JDK, the likely places to find the .exe
s are below directories like C:\Program Files\JavaSoft\JRE\x.y.z
. However, I've found some "out of the box" Windows installations to (also?) have copies of java.exe
and javaw.exe
in C:\winnt\system32
(NT and 2000) or C:\windows\system
(Windows 95, 98). This is usually a pretty elderly version of Java: 1.3, maybe? You'll want to do java -version
in a command window to check that you're not running some antiquated version of Java.
You can of course override the PATH setting or even do without it by explicitly stating the path to java.exe / javaw.exe in your command line or shortcut definition.
If you're running applets from the browser, or possibly also Java Web Start applications (they look like applications insofar as they have their own window, but you start them from the browser), the choice of JRE is determined by a set of registry settings:
Key: HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment
Name: CurrentVersion
Value: (e.g.) 1.3
More registry keys are created using this scheme:
(e.g.)
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.3
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.3.1
i.e. one for the major and one including the minor version number. Each of these keys has values like these (examples shown):
JavaHome : C:\program Files\JavaSoft\JRE\1.3.1
RuntimeLib : C:\Program Files\JavaSoft\JRE\1.3.1\bin\hotspot\jvm.dll
MicroVersion: 1
... and your browser will look to these settings to determine which JRE to fire up.
Since Java versions are changing pretty frequently, there's now a "wizard" called the "Java Control Panel" for manually switching your browser's Java version. This works for IE, Firefox and probably others like Opera and Chrome as well: It's the 'Java' applet in Windows' System Settings
app. You get to pick any one of the installed JREs. I believe that wizard fiddles with those registry entries.
If you're like me and have "uninstalled" old Java versions by simply wiping out directories, you'll find these "ghosts" among the choices too; so make sure the JRE you choose corresponds to an intact Java installation!
Some other answers are recommending setting the environment variable JAVA_HOME
. This is meanwhile outdated advice. Sun came to realize, around Java 2, that this environment setting is
There's hardly any modern Java software left that needs or respects the JAVA_HOME
environment variable.
More Information:
...and some useful information on multi-version support:
Instant.parse ( "2010-04-05T17:16:00Z" )
Your String complies with the ISO 8601 standard (of which the mentioned RFC 3339 is a profile).
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
Instead use either the Joda-Time library or the new java.time package in Java 8. Both use ISO 8601 as their defaults for parsing and generating string representations of date-time values.
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
The Instant
class in java.time represents a moment on the timeline in UTC time zone.
The Z
at the end of your input string means Zulu
which stands for UTC
. Such a string can be directly parsed by the Instant
class, with no need to specify a formatter.
String input = "2010-04-05T17:16:00Z";
Instant instant = Instant.parse ( input );
Dump to console.
System.out.println ( "instant: " + instant );
instant: 2010-04-05T17:16:00Z
From there you can apply a time zone (ZoneId
) to adjust this Instant
into a ZonedDateTime
. Search Stack Overflow for discussion and examples.
If you must use a java.util.Date
object, you can convert by calling the new conversion methods added to the old classes such as the static method java.util.Date.from( Instant )
.
java.util.Date date = java.util.Date.from( instant );
Example in Joda-Time 2.5.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ):
DateTime dateTime = new DateTime( "2010-04-05T17:16:00Z", timeZone );
Convert to UTC.
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
Convert to a java.util.Date if necessary.
java.util.Date date = dateTime.toDate();
To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING
and CHAR_LENGTH
functions together:
SELECT col
, /* ANSI Syntax */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
, /* MySQL Syntax */ SUBSTRING(col, 1, CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl
To remove a specific substring from the end of string, use the TRIM
function:
SELECT col
, TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.txt remains index.txt
After pondering this for a little while, I believe this will show them who's boss...
if(top != self) {
window.open(location.href, '_top');
}
Using _top
as the target parameter for window.open()
will launch it in the same window.
List<string> myCollection = new List<string>()
{
"Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};
myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}
output: Abdi 3 Alex 2 Bob 4
I was able to get Jenkins to build a tag by setting the Refspec and Branch Specifier as detailed in this blog post.
I also had to set the Repository Name (to "origin" in my case) so that I could reference it in the Refspec (otherwise it would apparently use a randomly generated name).
butangDonload.php
$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;
Try this,
<?php
$name=$_SESSION['name'];
download($name);
function download($name){
$file = $nama_fail;
?>
Old Question,but I would like to add complete Console Application example, considering you have files and proper permissions for the given folder, here is the code
class Program
{
static void Main(string[] args)
{
//path of file
string pathToOriginalFile = @"E:\C-sharp-IO\test.txt";
//duplicate file path
string PathForDuplicateFile = @"E:\C-sharp-IO\testDuplicate.txt";
//provide source and destination file paths
File.Copy(pathToOriginalFile, PathForDuplicateFile);
Console.ReadKey();
}
}
Source: File I/O in C# (Read, Write, Delete, Copy file using C#)
I know I'm a bit late to the party, but I got around the issue by tweaking the CSS to have the width span 100%, and setting l/r margins to 0px;
#div_id
{
margin-left: 0px;
margin-right: 0px;
width: 100%;
}
There is currently a problem with R12 where the SDK location cannot contain any spaces.
The default installation location is: C:\Programme Files(x86)\Android\android-sdk
. They are currently fixing the problem but you can currently work around it by changing the SDK location path in eclipse to C:\PROGRA~2\Android\android-sdk
.
If you are running 32-bit Windows, change the path to C:\PROGRA~1\Android\android-sdk
.
In JQuery you can call
$("form:first").trigger("submit")
Don't know if that is much better. I think form.submit(); is pretty universal.
Try this-
CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
insert into student (name,user_name,branch) values (name ,user_name,branch);
END
$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);
Note: only work for your example.
Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc
) as it's allocated on the heap:
char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);
More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation
In android studio, it is possible to see the difference between branches using graphical interface. Select your remote branch and and "Compare with current" from the list. From then you can select the files tab to see if there are any files that have content difference between both branches. If no file is seen, then both branches are up-to-date with each other.
In the Windows command prompt you can use "tree /F" to view a tree of the current folder and all descending files & folders.
In File Explorer under Windows 8.1:
tree /f > tree.txt
and press EnterYou now have an editable tree structure file.
This works for versions of Windows from Windows XP to Windows 8.1.
this may help you.
In .cs page,
//Declare a string
public string usertypeurl = "";
//check who is the user
//place your code to check who is the user
//if it is admin
usertypeurl = "help/AdminTutorial.html";
//if it is other
usertypeurl = "help/UserTutorial.html";
In .aspx age pass this variabe
<a href='<%=usertypeurl%>'>Tutorial</a>
For anyone finding this. Your better off using the jQuery UI version because it works on all browsers. The color plugin has issues with Safari and Chrome. It only works sometimes.
It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:
string = string.replace("to", "xyz");
or
String newString = string.replace("to", "xyz");
API Docs
public String replace (CharSequence target, CharSequence replacement)
Since: API Level 1
Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end.
Parameters
target
the sequence to replace.replacement
the replacement
sequence.Returns the resulting string.
Throws NullPointerException
if target or replacement is null.
Comparator
is a functional interface, and Integer::max
complies with that interface (after autoboxing/unboxing is taken into consideration). It takes two int
values and returns an int
- just as you'd expect a Comparator<Integer>
to (again, squinting to ignore the Integer/int difference).
However, I wouldn't expect it to do the right thing, given that Integer.max
doesn't comply with the semantics of Comparator.compare
. And indeed it doesn't really work in general. For example, make one small change:
for (int i = 1; i <= 20; i++)
list.add(-i);
... and now the max
value is -20 and the min
value is -1.
Instead, both calls should use Integer::compare
:
System.out.println(list.stream().max(Integer::compare).get());
System.out.println(list.stream().min(Integer::compare).get());
Other way to get the minor version is:
SELECT extversion
FROM pg_catalog.pg_extension
WHERE extname='postgis'
Here are some high level thoughts and info that might help, aside from the other answers.
Pollyfills are like a compatability patch for specific browsers. Shims are changes to specific arguments. Fallbacks can be used if say a @mediaquery is not compatible with a browser.
It kind of depends on the requirements of what your app/website needs to be compatible with.
You cna check this site out for compatability of specific libraries with specific browsers. https://caniuse.com/
Try this:
mtcars %>%
group_by(am, gear) %>%
summarise(n = n()) %>%
mutate(freq = n / sum(n))
# am gear n freq
# 1 0 3 15 0.7894737
# 2 0 4 4 0.2105263
# 3 1 4 8 0.6153846
# 4 1 5 5 0.3846154
From the dplyr vignette:
When you group by multiple variables, each summary peels off one level of the grouping. That makes it easy to progressively roll-up a dataset.
Thus, after the summarise
, the last grouping variable specified in group_by
, 'gear', is peeled off. In the mutate
step, the data is grouped by the remaining grouping variable(s), here 'am'. You may check grouping in each step with groups
.
The outcome of the peeling is of course dependent of the order of the grouping variables in the group_by
call. You may wish to do a subsequent group_by(am)
, to make your code more explicit.
For rounding and prettification, please refer to the nice answer by @Tyler Rinker.
So for me and my pals working on a Node.js app (with Postgres and Sequelize), we had to
brew install postgresql
(one of us was missing postgres, one of us was not, and yet we were getting the same error msg as listed above)
brew services start postgresql
**** (utilize Homebrew to start postgres)
createdb <name of database in config.json file>
node_modules/.bin/sequelize db:migrate
npm start
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog" ;
fdlg.InitialDirectory = @"c:\" ;
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName ;
}
In this code you can put your address in a text box.
Use
$ mysqladmin -u <db_user_name> -p create <db_name>
You will be prompted for password. Also make sure the mysql user you use has privileges to create database.
Perhaps a function along these lines is what you're after:
def add_unique_to_dict_list(dict_list, key, value):
for d in dict_list:
if key in d:
return d[key]
dict_list.append({ key: value })
return value
Using Keras:
from keras.preprocessing import image
img = image.load_img('path_to_image', target_size=(300, 300))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
All what I did in my case is to set the Top in my css knowing the height of the modal
<div id="myModal" class="modal fade"> ... </div>
in my css i set
#myModal{
height: 400px;
top: calc(50% - 200px) !important;
}
I did a quick performance check on these with perfplot (a project of mine) and found that it's hard to recommend anything else but numpy (note the log scale):
Code to reproduce the plot:
import perfplot
import numpy
def sorted_enumerate(seq):
return [i for (v, i) in sorted((v, i) for (i, v) in enumerate(seq))]
def sorted_enumerate_key(seq):
return [x for x, y in sorted(enumerate(seq), key=lambda x: x[1])]
def sorted_range(seq):
return sorted(range(len(seq)), key=seq.__getitem__)
def numpy_argsort(x):
return numpy.argsort(x)
perfplot.save(
"argsort.png",
setup=lambda n: numpy.random.rand(n),
kernels=[sorted_enumerate, sorted_enumerate_key, sorted_range, numpy_argsort],
n_range=[2 ** k for k in range(15)],
xlabel="len(x)",
)
See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):
var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );
https.createServer({
key: privateKey,
cert: certificate
}, app).listen(port);
Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
Line numbers are OK if you can guarantee the position of what you want. Over the years, my favorite flavor of this has been something like this:
sed "/First Line of Text/,/Last Line of Text/d" filename
which deletes all lines from the first matched line to the last match, including those lines.
Use sed -n with "p" instead of "d" to print those lines instead. Way more useful for me, as I usually don't know where those lines are.
var myVar = $("#start").find('.myClass').first().val();
Well, the most likely difference is that you still have to do an actual lookup of localhost
somewhere.
If you use 127.0.0.1
, then (intelligent) software will just turn that directly into an IP address and use it. Some implementations of gethostbyname
will detect the dotted format (and presumably the equivalent IPv6 format) and not do a lookup at all.
Otherwise, the name has to be resolved. And there's no guarantee that your hosts
file will actually be used for that resolution (first, or at all) so localhost
may become a totally different IP address.
By that I mean that, on some systems, a local hosts
file can be bypassed. The host.conf
file controls this on Linux (and many other Unices).
Try saving your .c file before building. I believe your computer is referencing a path to a file with no information inside of it.
--Had similar issue when building C projects
import tensorflow as tf
import numpy as np
def softmax(x):
return (np.exp(x).T / np.exp(x).sum(axis=-1)).T
logits = np.array([[1, 2, 3], [3, 10, 1], [1, 2, 5], [4, 6.5, 1.2], [3, 6, 1]])
sess = tf.Session()
print(softmax(logits))
print(sess.run(tf.nn.softmax(logits)))
sess.close()
Depends on what you mean by better. This works if your goal is removal of redundancy.
s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))
$("#employeeTable td").parent().remove();
This will remove all tr
having td
as child. i.e all rows except the header will be deleted.
You can pass values by using the below .
@Html.ActionLink("About", "About", "Home",new { name = ViewBag.Name }, htmlAttributes:null )
Controller:
public ActionResult About(string name)
{
ViewBag.Message = "Your application description page.";
ViewBag.NameTransfer = name;
return View();
}
And the URL looks like
http://localhost:50297/Home/About?name=My%20Name%20is%20Vijay
Yes, else
can be used in Python inside a list
comprehension with a Conditional Expression ("ternary operator"):
>>> [("A" if b=="e" else "c") for b in "comprehension"]
['c', 'c', 'c', 'c', 'c', 'A', 'c', 'A', 'c', 'c', 'c', 'c', 'c']
Here, the parentheses "()" are just to emphasize the conditional expression, they are not necessarily required (Operator precedence).
Additionaly, several expressions can be nested, resulting in more else
s and harder to read code:
>>> ["A" if b=="e" else "d" if True else "x" for b in "comprehension"]
['d', 'd', 'd', 'd', 'd', 'A', 'd', 'A', 'd', 'd', 'd', 'd', 'd']
>>>
On a related note, a comprehension can also contain its own if
condition(s) at the end:
>>> ["A" if b=="e" else "c" for b in "comprehension" if False]
[]
>>> ["A" if b=="e" else "c" for b in "comprehension" if "comprehension".index(b)%2]
['c', 'c', 'A', 'A', 'c', 'c']
Conditions? Yes, multiple if
s are possible, and actually multiple for
s, too:
>>> [i for i in range(3) for _ in range(3)]
[0, 0, 0, 1, 1, 1, 2, 2, 2]
>>> [i for i in range(3) if i for _ in range(3) if _ if True if True]
[1, 1, 2, 2]
(The single underscore _
is a valid variable name (identifier) in Python, used here just to show it's not actually used. It has a special meaning in interactive mode)
Using this for an additional conditional expression is possible, but of no real use:
>>> [i for i in range(3)]
[0, 1, 2]
>>> [i for i in range(3) if i]
[1, 2]
>>> [i for i in range(3) if (True if i else False)]
[1, 2]
Comprehensions can also be nested to create "multi-dimensional" lists ("arrays"):
>>> [[i for j in range(i)] for i in range(3)]
[[], [1], [2, 2]]
Last but not least, a comprehension is not limited to creating a list
, i.e. else
and if
can also be used the same way in a set
comprehension:
>>> {i for i in "set comprehension"}
{'o', 'p', 'm', 'n', 'c', 'r', 'i', 't', 'h', 'e', 's', ' '}
and a dictionary
comprehension:
>>> {k:v for k,v in [("key","value"), ("dict","comprehension")]}
{'key': 'value', 'dict': 'comprehension'}
The same syntax is also used for Generator Expressions:
>>> for g in ("a" if b else "c" for b in "generator"):
... print(g, end="")
...
aaaaaaaaa>>>
which can be used to create a tuple
(there is no tuple comprehension).
Great !! It has helped me a lot. I used to do the same using VB6 but now it is completely different. we should add this
listView1.View = System.Windows.Forms.View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
If you are going to be getting a random element multiple times, you want to make sure your random number generator is initialized only once.
import java.util.Random;
public class RandArray {
private int[] items = new int[]{1,2,3};
private Random rand = new Random();
public int getRandArrayElement(){
return items[rand.nextInt(items.length)];
}
}
If you are picking random array elements that need to be unpredictable, you should use java.security.SecureRandom rather than Random. That ensures that if somebody knows the last few picks, they won't have an advantage in guessing the next one.
If you are looking to pick a random number from an Object array using generics, you could define a method for doing so (Source Avinash R in Random element from string array):
import java.util.Random;
public class RandArray {
private static Random rand = new Random();
private static <T> T randomFrom(T... items) {
return items[rand.nextInt(items.length)];
}
}
I tried the accepted answer, it did not work.
However the simple way to do it is below:-
<option value="1" <c:if test="${item.quantity == 1}"> <c:out value= "selected=selected"/</c:if>>1</option>
<option value="2" <c:if test="${item.quantity == 2}"> <c:out value= "selected=selected"/</c:if>>2</option>
<option value="3" <c:if test="${item.quantity == 3}"> <c:out value= "selected=selected"/</c:if>>3</option>
Enjoy!!
According to HTML5 drafts, the checked
attribute is a “boolean attribute”, and “The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.” It is the name of the attribute that matters, and suffices. Thus, to make a checkbox initially checked, you use
<input type=checkbox checked>
By default, in the absence of the checked
attribute, a checkbox is initially unchecked:
<input type=checkbox>
Keeping things this way keeps them simple, but if you need to conform to XML syntax (i.e. to use HTML5 in XHTML linearization), you cannot use an attribute name alone. Then the allowed (as per HTML5 drafts) values are the empty string and the string checked
, case insensitively. Example:
<input type="checkbox" checked="checked" />
I would argue that both
let str = String(format:"%d, %f, %ld", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE)
and
let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE)"
are both acceptable since the user asked about formatting and both cases fit what they are asking for:
I need to create a string with format which can convert int, long, double etc. types into string.
Obviously the former allows finer control over the formatting than the latter, but that does not mean the latter is not an acceptable answer.
As I understand, you want the average value for each id at each pass. The solution is
SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;
We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.
Default @INC
Perl interpreter is compiled with a specific @INC
default value. To find out this value, run env -i perl -V
command (env -i
ignores the PERL5LIB
environmental variable - see #2) and in the output you will see something like this:
$ env -i perl -V ... @INC: /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/5.18.0 .
Note .
at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T
(taint checks enabled).
To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs
:
Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3
Environmental variable PERL5LIB
(or PERLLIB
)
Perl pre-pends @INC
with a list of directories (colon-separated) contained in PERL5LIB
(if it is not defined, PERLLIB
is used) environment variable of your shell. To see the contents of @INC
after PERL5LIB
and PERLLIB
environment variables have taken effect, run perl -V
.
$ perl -V ... %ENV: PERL5LIB="/home/myuser/test" @INC: /home/myuser/test /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/5.18.0 .
-I
command-line option
Perl pre-pends @INC
with a list of directories (colon-separated) passed as value of the -I
command-line option. This can be done in three ways, as usual with Perl options:
Pass it on command line:
perl -I /my/moduledir your_script.pl
Pass it via the first line (shebang) of your Perl script:
#!/usr/local/bin/perl -w -I /my/moduledir
Pass it as part of PERL5OPT
(or PERLOPT
) environment variable (see chapter 19.02 in Programming Perl)
Pass it via the lib
pragma
Perl pre-pends @INC
with a list of directories passed in to it via use lib
.
In a program:
use lib ("/dir1", "/dir2");
On the command line:
perl -Mlib=/dir1,/dir2
You can also remove the directories from @INC
via no lib
.
You can directly manipulate @INC
as a regular Perl array.
Note: Since @INC
is used during the compilation phase, this must be done inside of a BEGIN {}
block, which precedes the use MyModule
statement.
Add directories to the beginning via unshift @INC, $dir
.
Add directories to the end via push @INC, $dir
.
Do anything else you can do with a Perl array.
Note: The directories are unshifted onto @INC
in the order listed in this answer, e.g. default @INC
is last in the list, preceded by PERL5LIB
, preceded by -I
, preceded by use lib
and direct @INC
manipulation, the latter two mixed in whichever order they are in Perl code.
@INC
?There does not seem to be a comprehensive @INC
FAQ-type post on Stack Overflow, so this question is intended as one.
If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC
compiled into the Perl binary.
If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC
in previous use case), set the users' PERL5LIB
, usually during user login.
Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su
.
If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB
manually, or pass the -I
option to perl.
If the modules need to be used only for specific scripts, by all users using them, use use lib
/no lib
pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).
If the directories in @INC
need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib
/no lib
pragmas, then use direct @INC
manipulation inside BEGIN {}
block or inside a special purpose library designated for @INC
manipulation, which must be used by your script(s) before any other modules are used.
An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.
An additional use case for directly manipulating @INC
is to be able to add subroutine references or object references (yes, Virginia, @INC
can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).
Unless you are loading the files into memory each time you boot, use a database. Simple as that.
That is assuming that your colleges already have the program to handle queries to the files. If not, then use a database.
Although @Vega provides the direct answer to your question, there are issues. It breaks the browser's back/forward button. If you're user clicks the browser back or forward button, they lose their place and gets scrolled way at the top. This can be a bit of a pain for your users if they had to scroll way down to get to a link and decided to click back only to find the scrollbar had been reset to the top.
Here's my solution to the problem.
export class AppComponent implements OnInit {
isPopState = false;
constructor(private router: Router, private locStrat: LocationStrategy) { }
ngOnInit(): void {
this.locStrat.onPopState(() => {
this.isPopState = true;
});
this.router.events.subscribe(event => {
// Scroll to top if accessing a page, not via browser history stack
if (event instanceof NavigationEnd && !this.isPopState) {
window.scrollTo(0, 0);
this.isPopState = false;
}
// Ensures that isPopState is reset
if (event instanceof NavigationEnd) {
this.isPopState = false;
}
});
}
}
For me the solution was just replace unsigned with index
This is the full code:
Schema::create('champions_overview',function (Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('cid')->index();
$table->longText('name');
});
Schema::create('champions_stats',function (Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('championd_id')->index();
$table->foreign('championd_id', 'ch_id')->references('cid')->on('champions_overview');
});
Isn't this the same as updateOrCreate()?
It is similar but not the same. The updateOrCreate() will only work for one row at a time which doesn't allow bulk insert. InsertOnDuplicateKey will work on many rows.
I just had the same issue and it seems it also shows this message if the resource cannot be found.
In my case I had updated the API, but forgotten to redeploy. The issue was resolved after deploying the updated API to my stage.
What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon
In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.
If you learn Python first and then Java. I think it plays the same role as __str__()
method in Python, it is a magic method like __dict__()
and __init__()
but to refer to a string representing the the object.
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
def newline(p1, p2):
ax = plt.gca()
xmin, xmax = ax.get_xbound()
if(p2[0] == p1[0]):
xmin = xmax = p1[0]
ymin, ymax = ax.get_ybound()
else:
ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])
l = mlines.Line2D([xmin,xmax], [ymin,ymax])
ax.add_line(l)
return l
So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.
import numpy as np
x = np.linspace(0,10)
y = x**2
p1 = [1,20]
p2 = [6,70]
plt.plot(x, y)
newline(p1,p2)
plt.show()
Try this...
SELECT TO_CHAR(column_name,'99G999D99MI')
as format_column
FROM DUAL;
There is really no limit on the size of JSON data to be send or receive. We can send Json data in file too. According to the capabilities of browser that you are working with, Json data can be handled.
You can use something similar to the below:
if (strlen($str) > 10)
$str = substr($str, 0, 7) . '...';
If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.
val uri = myUriString.toUri()
To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
Use Throwable.printStackTrace(PrintWriter pw)
to send the stack trace to an appropriate writer.
import java.io.StringWriter;
import java.io.PrintWriter;
// ...
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String sStackTrace = sw.toString(); // stack trace as a string
System.out.println(sStackTrace);
I got the same problem, but i find the answer in this page! it works for me, you can try it.
iconv -f cp936 -t utf-8
You can use:
mpstat -P ALL 1
It shows how much each core is busy and it updates automatically each second. The output would be something like this (on a quad-core processor):
10:54:41 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle
10:54:42 PM all 8.20 0.12 0.75 0.00 0.00 0.00 0.00 0.00 90.93
10:54:42 PM 0 24.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 74.00
10:54:42 PM 1 22.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 76.00
10:54:42 PM 2 2.02 1.01 0.00 0.00 0.00 0.00 0.00 0.00 96.97
10:54:42 PM 3 2.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 98.00
10:54:42 PM 4 14.15 0.00 1.89 0.00 0.00 0.00 0.00 0.00 83.96
10:54:42 PM 5 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 99.00
10:54:42 PM 6 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
10:54:42 PM 7 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
This command doesn't answer original question though i.e. it does not show CPU core usage for a specific process.
Here is a query, you can run it in SQL Developer (or SQL*Plus):
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
GROUP BY DS.TABLESPACE_NAME,
SEGMENT_NAME;
simple solution and work 100%
if (getActivity() == null || !isAdded()) return;
There is no real way to do that in git. And if you won’t be making changes that affect both trees at once as a single work unit, there is no good reason to use a single repository for both. I thought I would miss this Subversion feature, but I found that creating repositories has so little administrative mental overhead (simply due to the fact that repositories are stored right next to their working copy, rather than requiring me to explicitly pick some place outside of the working copy) that I got used to just making lots of small single-purpose repositories.
If you insist (or really need it), though, you could make a git repository with just mytheme
and myplugins
directories and symlink those from within the WordPress install.
MDCore wrote:
making a commit to, e.g., mytheme will increment the revision number for myplugin
Note that this is not a concern for git, if you do decide to put both directories in a single repository, because git does away entirely with the concept of monotonically increasing revision numbers of any form.
The sole criterion for what things to put together in a single repository in git is whether it constitutes a single unit, ie. in your case whether there are changes where it does not make sense to look at the edits in each directory in isolation. If you have changes where you need to edit files in both directories at once and the edits belong together, they should be one repository. If not, then don’t glom them together.
Git really really wants you to use separate repositories for separate entities.
Submodules do not address the desire to keep both directories in one repository, because they would actually enforce having a separate repository for each directory, which are then brought together in another repository using submodules. Worse, since the directories inside the WordPress install are not direct subdirectories of the same directory and are also part of a hierarchy with many other files, using the per-directory repositories as submodules in a unified repository would offer no benefit whatsoever, because the unified repository would not reflect any use case/need.
I know this question is old and most answers here explains padding really well, but while trying to understand it myself I figured having a "visual" image of what is happening helped.
The processor reads the memory in "chunks" of a definite size (word). Say the processor word is 8 bytes long. It will look at the memory as a big row of 8 bytes building blocks. Every time it needs to get some information from the memory, it will reach one of those blocks and get it.
As seem in the image above, doesn't matter where a Char (1 byte long) is, since it will be inside one of those blocks, requiring the CPU to process only 1 word.
When we deal with data larger than one byte, like a 4 byte int or a 8 byte double, the way they are aligned in the memory makes a difference on how many words will have to be processed by the CPU. If 4-byte chunks are aligned in a way they always fit the inside of a block (memory address being a multiple of 4) only one word will have to be processed. Otherwise a chunk of 4-bytes could have part of itself on one block and part on another, requiring the processor to process 2 words to read this data.
The same applies to a 8-byte double, except now it must be in a memory address multiple of 8 to guarantee it will always be inside a block.
This considers a 8-byte word processor, but the concept applies to other sizes of words.
The padding works by filling the gaps between those data to make sure they are aligned with those blocks, thus improving the performance while reading the memory.
However, as stated on others answers, sometimes the space matters more then performance itself. Maybe you are processing lots of data on a computer that doesn't have much RAM (swap space could be used but it is MUCH slower). You could arrange the variables in the program until the least padding is done (as it was greatly exemplified in some other answers) but if that's not enough you could explicitly disable padding, which is what packing is.
On Mac OSX you can add your private key to the keychain using the command:
ssh-add -K /path/to/private_key
If your private key is stored at ~/.ssh and is named id_rsa:
ssh-add -K ~/.ssh/id_rsa
You will then be prompted for your password, which will be stored in your keychain.
Edit - Handle restart
In order to not have to fill in your password even after a restart add the following to your ssh configuration file (commonly located at ~/.ssh/config)
Host *
UseKeychain yes
AddKeysToAgent yes
IdentityFile ~/.ssh/id_rsa
I had this issue and I thought I was crazy. I have been using SSH for 20 years. and git over SSH since 2012... but why couldn't I fetch my bitbucket repository on my home computer?
well, I have two bitbucket accounts and had 4 SSH keys loaded inside my agent. even if my .ssh/config was configured to use the right key. when ssh was initializing the connection, it was using them in order loaded into the agent. so I was getting logged into my personal bitbucket account.
then getting a Forbidden error trying to fetch the repo. makes sense.
I unloaded the key from the agent
ssh-add -d ~/.ssh/personal_rsa
then I could fetch the repos.
... Later I found out I can force it to use the specified identity only
Host bitbucket.org-user2
HostName bitbucket.org
User git
IdentityFile ~/.ssh/user2
IdentitiesOnly yes
I didn't know about that last option IdentitiesOnly
from the bitbucket documentation itself
https://blog.developer.atlassian.com/different-ssh-keys-multiple-bitbucket-accounts/
Try this:
retVal = Shell("python.exe <full path to your python script>", vbNormalFocus)
replace <full path to your python script>
with the full path
Comparison of execution time of bubble sort and selection sort I have a program which compares the execution time of bubble sort and selection sort. To find out the time of execution of a block of code compute the time before and after the block by
clock_t start=clock();
…
clock_t end=clock();
CLOCKS_PER_SEC is constant in time.h library
Example code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a[10000],i,j,min,temp;
for(i=0;i<10000;i++)
{
a[i]=rand()%10000;
}
//The bubble Sort
clock_t start,end;
start=clock();
for(i=0;i<10000;i++)
{
for(j=i+1;j<10000;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
end=clock();
double extime=(double) (end-start)/CLOCKS_PER_SEC;
printf("\n\tExecution time for the bubble sort is %f seconds\n ",extime);
for(i=0;i<10000;i++)
{
a[i]=rand()%10000;
}
clock_t start1,end1;
start1=clock();
// The Selection Sort
for(i=0;i<10000;i++)
{
min=i;
for(j=i+1;j<10000;j++)
{
if(a[min]>a[j])
{
min=j;
}
}
temp=a[min];
a[min]=a[i];
a[i]=temp;
}
end1=clock();
double extime1=(double) (end1-start1)/CLOCKS_PER_SEC;
printf("\n");
printf("\tExecution time for the selection sort is %f seconds\n\n", extime1);
if(extime1<extime)
printf("\tSelection sort is faster than Bubble sort by %f seconds\n\n", extime - extime1);
else if(extime1>extime)
printf("\tBubble sort is faster than Selection sort by %f seconds\n\n", extime1 - extime);
else
printf("\tBoth algorithms have the same execution time\n\n");
}
You can do it very easily.
ALTER TABLE `table_name` CHANGE COLUMN `column_name` `column_name` LONGTEXT NULL DEFAULT NULL ;
The above query worked for me. I hope it helps you too.
I'm not entirely sure what you want, and your last line of code does not help either, but anyway:
"Chained" filtering is done by "chaining" the criteria in the boolean index.
In [96]: df
Out[96]:
A B C D
a 1 4 9 1
b 4 5 0 2
c 5 5 1 0
d 1 3 9 6
In [99]: df[(df.A == 1) & (df.D == 6)]
Out[99]:
A B C D
d 1 3 9 6
If you want to chain methods, you can add your own mask method and use that one.
In [90]: def mask(df, key, value):
....: return df[df[key] == value]
....:
In [92]: pandas.DataFrame.mask = mask
In [93]: df = pandas.DataFrame(np.random.randint(0, 10, (4,4)), index=list('abcd'), columns=list('ABCD'))
In [95]: df.ix['d','A'] = df.ix['a', 'A']
In [96]: df
Out[96]:
A B C D
a 1 4 9 1
b 4 5 0 2
c 5 5 1 0
d 1 3 9 6
In [97]: df.mask('A', 1)
Out[97]:
A B C D
a 1 4 9 1
d 1 3 9 6
In [98]: df.mask('A', 1).mask('D', 6)
Out[98]:
A B C D
d 1 3 9 6
Q1:
$(document).ready(function() {
var totalMinutes = $('.totalMin').html();
var hours = Math.floor(totalMinutes / 60);
var minutes = totalMinutes % 60;
$('.convertedHour').html(hours);
$('.convertedMin').html(minutes);
});
Q2:
$(document).ready(function() {
var minutes = 0;
$('.min').each(function() {
minutes = parseInt($(this).html()) + minutes;
});
var realmin = minutes % 60
var hours = Math.floor(minutes / 60)
$('.hour').each(function() {
hours = parseInt($(this).html()) + hours;
});
$('.totalHour').html(hours);
$('.totalMin').html(realmin);
});
New, improved answer to an old, frequently asked question...
Double quote ("
) may appear without escaping:
In XML textual content:
<NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
In XML attributes delimited by single quotes ('
):
<NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
Note: switching to single quotes ('
) also requires no escaping:
<NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
Double quote ("
) must be escaped:
In XML attributes delimited by double quotes:
<EscapeNeeded name="Pete "Maverick" Mitchell"/>
Double quote ("
) must be escaped as "
in XML only in very limited contexts.
BufferedReader in = new BufferedReader(new InputStreamReader(
new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"))));
String content;
while ((content = in.readLine()) != null)
System.out.println(content);
The accepted answer has been edited and its explanation become a bit incorrect. Code sample has been refreshed, but the text below stays the same. You cannot assume that BOOL is a char for now since it depends on architecture and platform. Thus, if you run you code at 32bit platform(for example iPhone 5) and print @encode(BOOL) you will see "c". It corresponds to a char type. But if you run you code at iPhone 5s(64 bit) you will see "B". It corresponds to a bool type.
The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:
<form action="http://someotherserver.com">
and there is no javascript involved in posting the form, then the same origin policy is not applicable.
See wikipedia for more information
Installing proxyconf will solve this, but behind a proxy you can't install a plugin simply using the command vagrant plugin install
, Bundler will raise an error.
set your proxy in your environment if you're using a unix like system
export http_proxy=http://user:password@host:port
or get a more detailed answer here: How to use bundler behind a proxy?
after this set up proxyconf
I know this is an old thread, but there's another way that I've found useful for any extension.
Run
php -m | grep <module_name>
In this particular case:
php -m | grep memcache
If you want to list all PHP modules then:
php -m
Depending on your system you'd get an output similar to this:
[PHP Modules]
apc
bcmath
bz2
... lots of other modules ...
mbstring
memcache
... and still more modules ...
zip
zlib
[Zend Modules]
You can see that memcache is in this list.
Like @Maximiliangerhardt said, MiniJson do not have the capability to deserialize properly. I used JsonFx and works like a charm. Works with the []
player[] p = JsonReader.Deserialize<player[]>(serviceData);
Debug.Log(p[0].playerId +" "+ p[0].playerLoc+"--"+ p[1].playerId + " " + p[1].playerLoc+"--"+ p[2].playerId + " " + p[2].playerLoc);
From the help docs.
Python 2.7.12
>>> print range.__doc__
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
>>> print xrange.__doc__
xrange(stop) -> xrange object
xrange(start, stop[, step]) -> xrange object
Like range(), but instead of returning a list, returns an object that
generates the numbers in the range on demand. For looping, this is
slightly faster than range() and more memory efficient.
Python 3.5.2
>>> print(range.__doc__)
range(stop) -> range object
range(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements.
When step is given, it specifies the increment (or decrement).
>>> print(xrange.__doc__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'xrange' is not defined
Difference is apparent. In Python 2.x, range
returns a list, xrange
returns an xrange object which is iterable.
In Python 3.x, range
becomes xrange
of Python 2.x, and xrange
is removed.
In case of windows, in cmd try to run pip install using python executable
e.g.
python -m pip install mitmproxy
this should work, at least it worked for me for other package installation.
This way you will be able to send ZPL to a printer no matter how it is connected (LPT, USB, Network Share...)
Create the RawPrinterHelper class (from the Microsoft article on How to send raw data to a printer by using Visual C# .NET):
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class RawPrinterHelper
{
// Structure and API declarions:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)] public string pDocName;
[MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)] public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint="OpenPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="StartDocPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool StartDocPrinter( IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint="EndDocPrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="StartPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="EndPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="WritePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten );
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter( string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "My C#.NET RAW Document";
di.pDataType = "RAW";
// Open the printer.
if( OpenPrinter( szPrinterName.Normalize(), out hPrinter, IntPtr.Zero ) )
{
// Start a document.
if( StartDocPrinter(hPrinter, 1, di) )
{
// Start a page.
if( StartPagePrinter(hPrinter) )
{
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if( bSuccess == false )
{
dwError = Marshal.GetLastWin32Error();
}
return bSuccess;
}
public static bool SendFileToPrinter( string szPrinterName, string szFileName )
{
// Open the file.
FileStream fs = new FileStream(szFileName, FileMode.Open);
// Create a BinaryReader on the file.
BinaryReader br = new BinaryReader(fs);
// Dim an array of bytes big enough to hold the file's contents.
Byte []bytes = new Byte[fs.Length];
bool bSuccess = false;
// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);
int nLength;
nLength = Convert.ToInt32(fs.Length);
// Read the contents of the file into the array.
bytes = br.ReadBytes( nLength );
// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return bSuccess;
}
public static bool SendStringToPrinter( string szPrinterName, string szString )
{
IntPtr pBytes;
Int32 dwCount;
// How many characters are in the string?
dwCount = szString.Length;
// Assume that the printer is expecting ANSI text, and then convert
// the string to ANSI text.
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
// Send the converted ANSI string to the printer.
SendBytesToPrinter(szPrinterName, pBytes, dwCount);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
}
Call the print method:
private void BtnPrint_Click(object sender, System.EventArgs e)
{
string s = "^XA^LH30,30\n^FO20,10^ADN,90,50^AD^FDHello World^FS\n^XZ";
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new PrinterSettings();
if(DialogResult.OK == pd.ShowDialog(this))
{
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s);
}
}
There are 2 gotchas I've come across that happen when you're sending txt files with ZPL codes to the printer:
Encoding has to be set to Encoding.Default when reading ANSI txt files with special characters
public static bool SendTextFileToPrinter(string szFileName, string printerName)
{
var sb = new StringBuilder();
using (var sr = new StreamReader(szFileName, Encoding.Default))
{
while (!sr.EndOfStream)
{
sb.AppendLine(sr.ReadLine());
}
}
return RawPrinterHelper.SendStringToPrinter(printerName, sb.ToString());
}
Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads
From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.
Just enter plt.hold(False)
before the first plt.plot, and you can stick to your original code.
There are multiple ways
return \Response::json(['hello' => $value], STATUS_CODE);
return response()->json(['hello' => $value], STATUS_CODE);
where STATUS_CODE is your HTTP status code you want to send. Both are identical.
if you are using Eloquent model, then simple return will also be auto converted in JSON by default like,
return User::all();
My 'hack' solution is
<div class="col-sm-5">
<laps
[lapsData]="rawLapsData"
[selectedTps]="selectedTps"
(lapsHandler)="lapsHandler($event)">
</laps>
</div>
<map
[lapsData]="rawLapsData"
[selectedTps]="selectedTps" // <--------
class="col-sm-7">
</map>
selectedTps changes at the same time as rawLapsData and that gives map another chance to detect the change through a simpler object primitive type. It is NOT elegant, but it works.
What you're looking for is componentWillMount
.
From the documentation:
Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call
setState
within this method,render()
will see the updated state and will be executed only once despite the state change.
So you would do something like this:
componentWillMount : function () {
var data = this.getData();
this.setState({data : data});
},
This way, render()
will only be called once, and you'll have the data you're looking for in the initial render.
Just for the sake of performance, I tested all the answers given here:
var substringTest = function (str) {
return str.substring(str.lastIndexOf('/')+1);
}
var replaceTest = function (str) {
return str.replace(/^.*(\\|\/|\:)/, '');
}
var execTest = function (str) {
return /([^\\]+)$/.exec(str)[1];
}
var splitTest = function (str) {
return str.split('\\').pop().split('/').pop();
}
substringTest took 0.09508600000000023ms
replaceTest took 0.049203000000000004ms
execTest took 0.04859899999999939ms
splitTest took 0.02505500000000005ms
And the winner is the Split and Pop style answer, Thanks to bobince !
.env
and .env.production
VUE_APP_
eg: VUE_APP_WHATEVERYOUWANT
.env
and build uses .env.production
process.env.VUE_APP_WHATEVERYOUWANT
to call valueBe sure you are using vue-cli version 3 or above
For more information: https://cli.vuejs.org/guide/mode-and-env.html
Are you missing the reference to System.Configuration.dll? ConfigurationManager
class lies there.
EDIT: The System.Configuration
namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default...
Just returning response()->json($promotion)
won't solve the issue in this question. $promotion
is an Eloquent object, which Laravel will automatically json_encode for the response. The json encoding is failing because of the img
property, which is a PHP stream resource, and cannot be encoded.
Whatever you return from your controller, Laravel is going to attempt to convert to a string. When you return an object, the object's __toString()
magic method will be invoked to make the conversion.
Therefore, when you just return $promotion
from your controller action, Laravel is going to call __toString()
on it to convert it to a string to display.
On the Model
, __toString()
calls toJson()
, which returns the result of json_encode
. Therefore, json_encode
is returning false
, meaning it is running into an error.
Your dd
shows that your img
attribute is a stream resource
. json_encode
cannot encode a resource
, so this is probably causing the failure. You should add your img
attribute to the $hidden
property to remove it from the json_encode
.
class Promotion extends Model
{
protected $hidden = ['img'];
// rest of class
}
Actually AnnotationConfigApplicationContext
derived from AbstractApplicationContext
, which has empty postProcessBeanFactory
method left for override
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for registering special
* BeanPostProcessors etc in certain ApplicationContext implementations.
* @param beanFactory the bean factory used by the application context
*/
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
To leverage this, Create AnnotationConfigApplicationContextProvider
class which may look like following(given for Vertx
instance example, you can use MyClass
instead)...
public class CustomAnnotationApplicationContextProvider {
private final Vertx vertx;
public CustomAnnotationApplicationContextProvider(Vertx vertx) {
this.vertx = vertx;
}
/**
* Register all beans to spring bean factory
*
* @param beanFactory, spring bean factory to register your instances
*/
private void configureBeans(ConfigurableListableBeanFactory beanFactory) {
beanFactory.registerSingleton("vertx", vertx);
}
/**
* Proxy method to create {@link AnnotationConfigApplicationContext} instance with no params
*
* @return {@link AnnotationConfigApplicationContext} instance
*/
public AnnotationConfigApplicationContext get() {
return new AnnotationConfigApplicationContext() {
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.postProcessBeanFactory(beanFactory);
configureBeans(beanFactory);
}
};
}
/**
* Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)} with our logic
*
* @param beanFactory bean factory for spring
* @return
* @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)
*/
public AnnotationConfigApplicationContext get(DefaultListableBeanFactory beanFactory) {
return new AnnotationConfigApplicationContext(beanFactory) {
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.postProcessBeanFactory(beanFactory);
configureBeans(beanFactory);
}
};
}
/**
* Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])} with our logic
*
* @param annotatedClasses, set of annotated classes for spring
* @return
* @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])
*/
public AnnotationConfigApplicationContext get(Class<?>... annotatedClasses) {
return new AnnotationConfigApplicationContext(annotatedClasses) {
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.postProcessBeanFactory(beanFactory);
configureBeans(beanFactory);
}
};
}
/**
* proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)} with our logic
*
* @param basePackages set of base packages for spring
* @return
* @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)
*/
public AnnotationConfigApplicationContext get(String... basePackages) {
return new AnnotationConfigApplicationContext(basePackages) {
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.postProcessBeanFactory(beanFactory);
configureBeans(beanFactory);
}
};
}
}
While creating ApplicationContext
you can create it using
Vertx vertx = ...; // either create or for vertx, it'll be passed to main verticle
ApplicationContext context = new CustomAnnotationApplicationContextProvider(vertx).get(ApplicationSpringConfig.class);
i just added
select = $('#' + id);
length = $('#' + id + ' > option').length;
if (length > 20)
length = 20;
select.attr('size', length);
select.css('position', 'absolute');
select.focus();
and add into the select
onchange="$(this).removeAttr('size');"
onblur="$(this).removeAttr('size');"
to make the same appearance like the classic one (overlap the rest of html)
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
Try this
SELECT *
FROM people P
where P.IDNo in (SELECT DISTINCT IDNo
FROM people)
Use empty
- http://php.net/manual/en/function.empty.php.
Example:
$a = '';
if(empty($a)) {
echo 'is empty';
}
Swift 3.0 (macOS 10.10 and later), you can get it from className
self.className.components(separatedBy: ".").last!
You can run your program by: Debug -> Start Without Debugging
. It will keep a console opened after the program will be finished.
hist
can not only plot an histogram but also return you the count of elements in each bin, so you can get that count, normalize it by dividing each bin by the total and plotting the result using bar
. Example:
Y = rand(10,1);
C = hist(Y);
C = C ./ sum(C);
bar(C)
or if you want a one-liner:
bar(hist(Y) ./ sum(hist(Y)))
Edit: This solution answers the question How to have the sum of all bins equal to 1. This approximation is valid only if your bin size is small relative to the variance of your data. The sum used here correspond to a simple quadrature formula, more complex ones can be used like trapz
as proposed by R. M.
Good and convenient solution:
In your ViewController:
@IBOutlet weak var label: LabelButton!
override func viewDidLoad() {
super.viewDidLoad()
self.label.onClick = {
// TODO
}
}
You can place this in your ViewController or in another .swift file(e.g. CustomView.swift):
@IBDesignable class LabelButton: UILabel {
var onClick: () -> Void = {}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
onClick()
}
}
In Storyboard select Label and on right pane in "Identity Inspector" in field class select LabelButton.
Don't forget to enable in Label Attribute Inspector "User Interaction Enabled"
You can easily do that with a for loop,
public static void main(String[] args) {
String aToZ="ABCD.....1234"; // 36 letter.
String randomStr=generateRandom(aToZ);
}
private static String generateRandom(String aToZ) {
Random rand=new Random();
StringBuilder res=new StringBuilder();
for (int i = 0; i < 17; i++) {
int randIndex=rand.nextInt(aToZ.length());
res.append(aToZ.charAt(randIndex));
}
return res.toString();
}
Use the name attribute selector:
$("input[name='nameGoesHere']").val();
It is a mandatory requirement to include quotes around the value, see: http://api.jquery.com/attribute-equals-selector/
As several people have already said, this is due to autoboxing.
You could create a utility method to check whether the object's class is Integer
, Double
, etc. But there is no way to know whether an object was created by autoboxing a primitive; once it's boxed, it looks just like an object created explicitly.
So unless you know for sure that your array will never contain a wrapper class without autoboxing, there is no real solution.
Use
var str = $("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.
I had the same problem on Ubuntu with Eclipse 4.3 (Kepler) and the problem was that I created the project with a minus-sign in it.
I recreated the project with no specialchars and it all worked fine
As the question title asks for a regex that finds many dates, I would like to propose a new solution, although there are many solutions already.
In order to find all dates of a string that are in this millennium (2000 - 2999), for me it worked the following:
dates = re.findall('([1-9]|1[0-9]|2[0-9]|3[0-1]|0[0-9])(.|-|\/)([1-9]|1[0-2]|0[0-9])(.|-|\/)(20[0-9][0-9])',dates_ele)
dates = [''.join(dates[i]) for i in range(len(dates))]
This regex is able to find multiple dates in the same string, like bla Bla 8.05/2020 \n BLAH bla15/05-2020 blaa. As one could observe, instead of / the date can have . or -, not necessary at the same time.
Some explaining
More specifically it can find dates of format day , moth year. Day is an one digit integer or a zero followed by one digit integer or 1 or 2 followed by an one digit integer or a 3 followed by 0 or 1. Month is an one digit integer or a zero followed by one digit integer or 1 followed by 0, 1, or 2. Year is the number 20 followed by any number between 00 and 99.
Useful notes
One can add more date splitting symbols by adding | symbol
at the end of both (.|-|\/)
. For example for adding -- one would do (.|-|\/|--)
To have years outside of this millennium one has to modify (20[0-9][0-9])
to ([0-9][0-9][0-9][0-9])
A great way to do it for a simple image is to do it using only CSS to set the background of the HTML element like so.
HTML {_x000D_
background: url('http://www.earthtimes.org/newsimage/eat-lead-by-example-obesity-expert-tells-parents_139.jpg');_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}
_x000D_
If you want to get fancy, and set its opacity, then, in IE9+*, you can set a transparent background color of the body. This works by overlaying semitransparent white to make the image whiter, and appear to be brighter. For example, white with 75% opacity (rgba(255,255,255,.75)
) would produce the following effect.
HTML {_x000D_
background: url('http://www.earthtimes.org/newsimage/eat-lead-by-example-obesity-expert-tells-parents_139.jpg');_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
body {_x000D_
width: 100%;_x000D_
min-height: 100%;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
margin: 0;_x000D_
background: rgba(255, 255, 255, .75);_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, et id, maecenas a convallis, elit facilisi congue augue id ac. Suscipit luctus egestas rutrum, amet tincidunt porttitor ante convallis magna, vivamus amet at turpis, ante lacinia blandit vel metus mauris rutrum. Ipsum nam adipiscing._x000D_
Est sapien quis sem vestibulum, quis cubilia turpis, suspendisse mattis vehicula enim risus pede, placerat suspendisse dui. Convallis nostrud pede, mollit lobortis, ornare ipsum tempor faucibus tortor, vel pede, porttitor nulla nonummy vestibulum purus._x000D_
Eros placerat tenetur augue ipsum aliquam, pellentesque congue condimentum sed vitae lectus.</p>_x000D_
<p>Aliquam venenatis curabitur pellentesque sociosqu quam. Tincidunt id erat vestibulum in, est fermentum ipsum et augue, nascetur etiam. Lorem elit, sed donec, leo vivamus ac id enim faucibus vel. Nullam sit feugiat sed massa consectetuer auctor, nulla_x000D_
et erat lacinia nec, eget ut ante nullam est non in, elit porttitor in in donec eget porttitor. Interdum ultricies sem morbi facilisis nibh erat. Id suspendisse, sed tincidunt fringilla sit, sapien odio vel, at culpa augue sed taciti neque inceptos,_x000D_
massa class non. Vel tristique condimentum at pellentesque, commodo nulla sagittis rhoncus lorem. Viverra maecenas tellus pretium urna mauris proin, vel libero morbi, ante volutpat vestibulum augue. Itaque leo mauris turpis, vivamus nisl congue nisl_x000D_
nulla in turpis, eget vitae accumsan dolor ipsum leo venenatis, feugiat vehicula in risus, donec eu pede vivamus itaque nam. Justo amet vitae pellentesque sed, posuere fusce sapien, sed nam placerat libero sed etiam curabitur, suspendisse justo, amet_x000D_
porttitor.</p>_x000D_
<p>Condimentum eget. Sem elementum a et mauris sem a, velit justo consectetuer in turpis mauris, sit sed elit cum, fusce suspendisse pretium dictum, mattis dui tortor tellus. Volutpat ut ante lorem nec laoreet aliquam, lorem est magna amet, integer mauris_x000D_
purus tellus. Porta enim repellendus aliquam eros. Turpis posuere elementum suscipit wisi lobortis, nec nunc consequat dictum ut unde at, mi lorem amet nunc. Cubilia pede, integer dolor, eget platea felis elit enim rhoncus, integer proin quam in ipsum_x000D_
lorem, diam curabitur netus pretium pellentesque. Donec rutrum ultrices placerat, curabitur maecenas, feugiat pede varius accumsan quam lorem, dui et dictumst asperiores nulla, vivamus urna nam leo libero. Posuere non convallis amet justo parturient,_x000D_
imperdiet consectetuer arcu praesent cursus risus, quis pretium dolor.</p>
_x000D_
position: relative
, while the body is position: absolute
. This is to prevent the background color of the body from behaving more like a highlighter of the text in the body.This could even be expanded to something comparable to, but still very distinct from, CSS filters by changing around the body's RGBA color background. For example, rgba(0,255,0,.75)
would create a very green tint as you can see in the code snippet.
HTML {_x000D_
background: url('http://www.earthtimes.org/newsimage/eat-lead-by-example-obesity-expert-tells-parents_139.jpg');_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
position: relative;_x000D_
}_x000D_
body {_x000D_
width: 100%;_x000D_
min-height: 100%;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
margin: 0;_x000D_
background: rgba(0,255,0,.75);_x000D_
}
_x000D_
<p>Aliquam venenatis curabitur pellentesque sociosqu quam. Tincidunt id erat vestibulum in, est fermentum ipsum et augue, nascetur etiam. Lorem elit, sed donec, leo vivamus ac id enim faucibus vel. Nullam sit feugiat sed massa consectetuer auctor, nulla et erat lacinia nec, eget ut ante nullam est non in, elit porttitor in in donec eget porttitor. Interdum ultricies sem morbi facilisis nibh erat. Id suspendisse, sed tincidunt fringilla sit, sapien odio vel, at culpa augue sed taciti neque inceptos, massa class non. Vel tristique condimentum at pellentesque, commodo nulla sagittis rhoncus lorem. Viverra maecenas tellus pretium urna mauris proin, vel libero morbi, ante volutpat vestibulum augue. Itaque leo mauris turpis, vivamus nisl congue nisl nulla in turpis, eget vitae accumsan dolor ipsum leo venenatis, feugiat vehicula in risus, donec eu pede vivamus itaque nam. Justo amet vitae pellentesque sed, posuere fusce sapien, sed nam placerat libero sed etiam curabitur, suspendisse justo, amet porttitor.</p>_x000D_
<p>Condimentum eget. Sem elementum a et mauris sem a, velit justo consectetuer in turpis mauris, sit sed elit cum, fusce suspendisse pretium dictum, mattis dui tortor tellus. Volutpat ut ante lorem nec laoreet aliquam, lorem est magna amet, integer mauris purus tellus. Porta enim repellendus aliquam eros. Turpis posuere elementum suscipit wisi lobortis, nec nunc consequat dictum ut unde at, mi lorem amet nunc. Cubilia pede, integer dolor, eget platea felis elit enim rhoncus, integer proin quam in ipsum lorem, diam curabitur netus pretium pellentesque. Donec rutrum ultrices placerat, curabitur maecenas, feugiat pede varius accumsan quam lorem, dui et dictumst asperiores nulla, vivamus urna nam leo libero. Posuere non convallis amet justo parturient, imperdiet consectetuer arcu praesent cursus risus, quis pretium dolor.</p>_x000D_
<p>Lorem ipsum dolor sit amet, et id, maecenas a convallis, elit facilisi congue augue id ac. Suscipit luctus egestas rutrum, amet tincidunt porttitor ante convallis magna, vivamus amet at turpis, ante lacinia blandit vel metus mauris rutrum. Ipsum nam adipiscing. Est sapien quis sem vestibulum, quis cubilia turpis, suspendisse mattis vehicula enim risus pede, placerat suspendisse dui. Convallis nostrud pede, mollit lobortis, ornare ipsum tempor faucibus tortor, vel pede, porttitor nulla nonummy vestibulum purus. Eros placerat tenetur augue ipsum aliquam, pellentesque congue condimentum sed vitae lectus.</p>
_x000D_
rgba(0,255,0,.75)
as something exemplified by {red:0, green:255, blue:0, alpha:'75%'}
.*A full compatibility table can be found at Can I Use. However, please also note that you need to click the "Show All" to see that IE9 supports it.
Since I have already answered the question but I have more I want to add, I am titling this section addendum and having it add some potentially helpful information. So, to extrapolate even further on the content above, you could use an SVG as a background image to do wicked awesome things. For example, you could create a loading screen background featuring a cool website icon as you can see in the example of a base64 encoded SVG below.
HTML {_x000D_
background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iNDAwIiBoZWlnaHQ9IjQwMCIgdmVyc2lvbj0iMS4xIiB2aWV3Qm94PSIwIDAgMSAxIiBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiIgYXJpYS1oaWRkZW49InRydWUiPjxnIGlkPSJrIj48ZGVmcz48bGluZWFyR3JhZGllbnQgaWQ9ImMiIGdyYWRpZW50VHJhbnNmb3JtPSJyb3RhdGUoLTEyMCkiIHRyYW5zZm9ybS1vcmlnaW49Ii41LjUiPjxzdG9wIG9mZnNldD0iMCUiIHN0b3AtY29sb3I9InJnYmEoMCwwLDAsLjYpIi8+PHN0b3Agb2Zmc2V0PSI0NyUiIHN0b3AtY29sb3I9InJnYmEoMCwwLDAsLjYpIi8+PHN0b3Agb2Zmc2V0PSI1MyUiIHN0b3AtY29sb3I9InJnYmEoMCwwLDAsLjMpIi8+PHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSJyZ2JhKDAsMCwwLC45KSIvPjxhbmltYXRlVHJhbnNmb3JtIGF0dHJpYnV0ZU5hbWU9ImdyYWRpZW50VHJhbnNmb3JtIiBhdHRyaWJ1dGVUeXBlPSJYTUwiIHR5cGU9InJvdGF0ZSIgZHVyPSI3MDAwbXMiIGZyb209IjAiIHRvPSIzNjAiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIi8+PC9saW5lYXJHcmFkaWVudD48cmFkaWFsR3JhZGllbnQgaWQ9ImQiIHI9Ii41IiBjeT0iLjUiIGN4PSIuNSI+PHN0b3Agb2Zmc2V0PSIzNSUiIHN0b3AtY29sb3I9ImJsYWNrIi8+PHN0b3Agb2Zmc2V0PSI1MCUiIHN0b3AtY29sb3I9ImdyZXkiLz48c3RvcCBvZmZzZXQ9IjY1JSIgc3RvcC1jb2xvcj0iYmxhY2siLz48L3JhZGlhbEdyYWRpZW50PjxyYWRpYWxHcmFkaWVudCBpZD0iZSIgcj0iLjUiIGN5PSIuNSIgY3g9Ii41Ij48c3RvcCBvZmZzZXQ9IjAlIiBzdG9wLWNvbG9yPSJ3aGl0ZSIvPjxzdG9wIG9mZnNldD0iMjUlIiBzdG9wLWNvbG9yPSJ5ZWxsb3ciLz48c3RvcCBvZmZzZXQ9Ijc1JSIgc3RvcC1jb2xvcj0ieWVsbG93Ii8+PHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSJ3aGl0ZSIvPjwvcmFkaWFsR3JhZGllbnQ+PGNsaXBQYXRoIGlkPSJmIj48cGF0aCBzdHJva2U9ImdyZXkiIHN0cm9rZS13aWR0aD0iLjAxIiBpZD0iYiIgZD0iTS43NS43MUEuMzEuMzEgMCAxIDEgLjc1LjMxTC42OS4zOEEuMjIuMjIgMCAxIDAgLjY4LjY2TC41Ni41N0wuNi41MUwuODIuNjh6TS42LjYzQS4xNC4xNCAwIDEgMSAuNjIuNDJMLjY2LjM5QS4xOS4xOSAwIDEgMCAuNjQuNjZ6TS41NS41OEEuMDcuMDcgMCAxIDEgLjU2LjQ2TC42LjQzQS4xMi4xMiAwIDEgMCAuNTkuNjF6Ii8+PC9jbGlwUGF0aD48Y2xpcFBhdGggaWQ9ImciPjxwYXRoIHN0cm9rZT0iZ3JleSIgZmlsbD0icmVkIiBzdHJva2Utd2lkdGg9Ii4wMSIgZD0iTS42LjYzQS4xNC4xNCAwIDEgMSAuNjIuNDJMLjY2LjM5QS4xOS4xOSAwIDEgMCAuNjQuNjZ6Ii8+PC9jbGlwUGF0aD48L2RlZnM+PGcgY2xpcC1wYXRoPSJ1cmwoI2YpIiBmaWxsPSJ1cmwoI2MpIj48cmVjdCB4PSIwIiB5PSIwIiB3aWR0aD0iMSIgaGVpZ2h0PSIxIi8+PHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0icmVkIiBjbGlwLXBhdGg9InVybCgjZykiLz48L2c+PGcgdHJhbnNmb3JtPSJzY2FsZSgxLjEpIiB0cmFuc2Zvcm0tb3JpZ2luPSIuNS41Ij48dGV4dD48dGV4dFBhdGggaHJlZj0iI2IiIGZvbnQtc2l6ZT0iLjY1JSIgZm9udC1mYW1pbHk9Im1vbm9zcGFjZSIgbGV0dGVyLXNwYWNpbmc9Ii0uNSUiIHN0eWxlPSJ3aGl0ZS1zcGFjZTpwcmUiPiBZT1VSIDx0c3BhbiBmaWxsPSJyZWQiPkVYQU1QTEUgV0VCU0lURTwvdHNwYW4+IExPR088L3RleHRQYXRoPjwvdGV4dD48L2c+PC9nPjwvc3ZnPg==');_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
position: relative;_x000D_
background-size: cover;_x000D_
}_x000D_
body {_x000D_
width: 100%;_x000D_
min-height: 100%;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
margin: 0;_x000D_
background: rgba(255,255,255,.5);_x000D_
}
_x000D_
<p>Condimentum eget. Sem elementum a et mauris sem a, velit justo consectetuer in turpis mauris, sit sed elit cum, fusce suspendisse pretium dictum, mattis dui tortor tellus. Volutpat ut ante lorem nec laoreet aliquam, lorem est magna amet, integer mauris purus tellus. Porta enim repellendus aliquam eros. Turpis posuere elementum suscipit wisi lobortis, nec nunc consequat dictum ut unde at, mi lorem amet nunc. Cubilia pede, integer dolor, eget platea felis elit enim rhoncus, integer proin quam in ipsum lorem, diam curabitur netus pretium pellentesque. Donec rutrum ultrices placerat, curabitur maecenas, feugiat pede varius accumsan quam lorem, dui et dictumst asperiores nulla, vivamus urna nam leo libero. Posuere non convallis amet justo parturient, imperdiet consectetuer arcu praesent cursus risus, quis pretium dolor.</p>_x000D_
<p>Lorem ipsum dolor sit amet, et id, maecenas a convallis, elit facilisi congue augue id ac. Suscipit luctus egestas rutrum, amet tincidunt porttitor ante convallis magna, vivamus amet at turpis, ante lacinia blandit vel metus mauris rutrum. Ipsum nam adipiscing. Est sapien quis sem vestibulum, quis cubilia turpis, suspendisse mattis vehicula enim risus pede, placerat suspendisse dui. Convallis nostrud pede, mollit lobortis, ornare ipsum tempor faucibus tortor, vel pede, porttitor nulla nonummy vestibulum purus. Eros placerat tenetur augue ipsum aliquam, pellentesque congue condimentum sed vitae lectus.</p>_x000D_
<p>Aliquam venenatis curabitur pellentesque sociosqu quam. Tincidunt id erat vestibulum in, est fermentum ipsum et augue, nascetur etiam. Lorem elit, sed donec, leo vivamus ac id enim faucibus vel. Nullam sit feugiat sed massa consectetuer auctor, nulla et erat lacinia nec, eget ut ante nullam est non in, elit porttitor in in donec eget porttitor. Interdum ultricies sem morbi facilisis nibh erat. Id suspendisse, sed tincidunt fringilla sit, sapien odio vel, at culpa augue sed taciti neque inceptos, massa class non. Vel tristique condimentum at pellentesque, commodo nulla sagittis rhoncus lorem. Viverra maecenas tellus pretium urna mauris proin, vel libero morbi, ante volutpat vestibulum augue. Itaque leo mauris turpis, vivamus nisl congue nisl nulla in turpis, eget vitae accumsan dolor ipsum leo venenatis, feugiat vehicula in risus, donec eu pede vivamus itaque nam. Justo amet vitae pellentesque sed, posuere fusce sapien, sed nam placerat libero sed etiam curabitur, suspendisse justo, amet porttitor.</p>
_x000D_
background-size: cover
CSS causes the SVG logo in the background to be resized to the size of the HTML element.I get the following error message when trying to push with the GitHub Extension for Visual Studio:
Error encountered while pushing branch to the remote repository: Git failed with a fatal error repository 'https://github.com/my-repo' not found
I know that the repository exists, I pulled from it. Unfortunately the error message in this situation does not indicate the root cause: I did not have write permissions for that repository
You can use functools.partial
for this (as you suspected):
from functools import partial
def target(lock, iterable_item):
for item in iterable_item:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
l = multiprocessing.Lock()
func = partial(target, l)
pool.map(func, iterable)
pool.close()
pool.join()
Example:
def f(a, b, c):
print("{} {} {}".format(a, b, c))
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
a = "hi"
b = "there"
func = partial(f, a, b)
pool.map(func, iterable)
pool.close()
pool.join()
if __name__ == "__main__":
main()
Output:
hi there 1
hi there 2
hi there 3
hi there 4
hi there 5
Swift 2.0 Compability
func listWithFilter () {
let fileManager = NSFileManager.defaultManager()
// We need just to get the documents folder url
let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
do {
// if you want to filter the directory contents you can do like this:
if let directoryUrls = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants) {
print(directoryUrls)
........
}
}
}
OR
func listFiles() -> [String] {
var theError = NSErrorPointer()
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if dirs != nil {
let dir = dirs![0]
do {
let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir)
return fileList as [String]
}catch {
}
}else{
let fileList = [""]
return fileList
}
let fileList = [""]
return fileList
}
Both questions are answered in git status
.
To unstage adding a new file use git rm --cached filename.ext
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: test
To unstage deleting a file use git reset HEAD filename.ext
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: test
In the other hand, git checkout --
never unstage, it just discards non-staged changes.
try this to close the connection:
socket.close();
and if you want to open it again:
socket.connect();
Swift 4 Examples
Example #1 using closure
NotificationCenter.default.addObserver(forName: .UIApplicationUserDidTakeScreenshot,
object: nil,
queue: OperationQueue.main) { notification in
print("\(notification) that a screenshot was taken!")
}
Example #2 with selector
NotificationCenter.default.addObserver(self,
selector: #selector(screenshotTaken),
name: .UIApplicationUserDidTakeScreenshot,
object: nil)
@objc func screenshotTaken() {
print("Screenshot taken!")
}
I was having same issue.
String[] arr= new String[] { "A", "B", "C" };
Object obj = arr;
And then passed the obj as varargs argument. It worked.
I know this is a little old, but this but here is a concise function for counting regex patterns.
def regex_cnt(string, pattern):
return len(re.findall(pattern, string))
string = 'abc123'
regex_cnt(string, '[0-9]')
A Unix timestamp is simply the number of seconds since January the first 1970, so to add 24 hours to a Unix timestamp we just add the number of seconds in 24 hours. (24 * 60 *60)
time() + 24*60*60;
Now there is the pandas_profiling
package, which is a more complete alternative to df.describe()
.
If your pandas dataframe is df
, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.
import pandas_profiling
pandas_profiling.ProfileReport(df)
See the example notebook detailing the usage.
A vector
is functionally same as an array. But, to the language vector
is a type, and int
is also a type. To a function argument, an array of any type (including vector[]
) is treated as pointer. A vector<int>
is not same as int[]
(to the compiler). vector<int>
is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor.
So, you must use vector<int>&
(preferably with const
, if function isn't modifying it) to pass it as a reference.
You will need to give your textarea a set height and then set overflow-y
textarea
{
resize: none;
overflow-y: scroll;
height:300px;
}
you need to put it after wp_head(); Because that loads your jQuery and you need to load jQuery first and then your js
Since Java 11 you may use that:
public FileReader(String fileName, Charset charset) throws IOException;
I've had some success, although it relies on a few properties to work:
table-layout: fixed
border-collapse: separate
and cell 'widths' that divide/span easily, i.e. 4 x cells of 25% width:
.div-table-cell,_x000D_
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.div-table {_x000D_
display: table;_x000D_
border: solid 1px #ccc;_x000D_
border-left: none;_x000D_
border-bottom: none;_x000D_
table-layout: fixed;_x000D_
margin: 10px auto;_x000D_
width: 50%;_x000D_
border-collapse: separate;_x000D_
background: #eee;_x000D_
}_x000D_
_x000D_
.div-table-row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.div-table-cell {_x000D_
display: table-cell;_x000D_
padding: 15px;_x000D_
border-left: solid 1px #ccc;_x000D_
border-bottom: solid 1px #ccc;_x000D_
text-align: center;_x000D_
background: #ddd;_x000D_
}_x000D_
_x000D_
.colspan-3 {_x000D_
width: 300%;_x000D_
display: table;_x000D_
background: #eee;_x000D_
}_x000D_
_x000D_
.row-1 .div-table-cell:before {_x000D_
content: "row 1: ";_x000D_
}_x000D_
_x000D_
.row-2 .div-table-cell:before {_x000D_
content: "row 2: ";_x000D_
}_x000D_
_x000D_
.row-3 .div-table-cell:before {_x000D_
content: "row 3: ";_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.div-table-row-at-the-top {_x000D_
display: table-header-group;_x000D_
}
_x000D_
<div class="div-table">_x000D_
_x000D_
<div class="div-table-row row-1">_x000D_
_x000D_
<div class="div-table-cell">Cell 1</div>_x000D_
<div class="div-table-cell">Cell 2</div>_x000D_
<div class="div-table-cell">Cell 3</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<div class="div-table-row row-2">_x000D_
_x000D_
<div class="div-table-cell colspan-3">_x000D_
Cor blimey he's only gone and done it._x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<div class="div-table-row row-3">_x000D_
_x000D_
<div class="div-table-cell">Cell 1</div>_x000D_
<div class="div-table-cell">Cell 2</div>_x000D_
<div class="div-table-cell">Cell 3</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
https://jsfiddle.net/sfjw26rb/2/
Also, applying display:table-header-group or table-footer-group is a handy way of jumping 'row' elements to the top/bottom of the 'table'.
If you have Xdebug installed you can override every setting by setting:
xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;
force_display_errors
Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this setting is set to 1 then errors will always be displayed, no matter what the setting of PHP's display_errors is.
force_error_reporting
Type: int, Default value: 0, Introduced in Xdebug >= 2.3 This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().
ES6 syntax with arrow function and interpolation:
var data=["a","b","c"];
$(data).each((index, element) => {
console.log(`current index : ${index} element : ${element}`)
});
You can't do what you ask (and the linked site does not do exactly that either).
You can, however, modify the part of the url after the #
sign, which is called the fragment, like this:
window.location.hash = 'something';
Fragments do not get sent to the server (so, for example, Google itself cannot tell the difference between http://www.google.com/
and http://www.google.com/#something
), but they can be read by Javascript on your page. In turn, this Javascript can decide to perform a different AJAX request based on the value of the fragment, which is how the site you linked to probably does it.
# Initialize variables
new_list = []
i = 0
# Iterate through the list
for i in range(len(elements)):
# Does this element belong in the resulting list?
if i%2==0:
# Add this element to the resulting list
new_list.append(elements[i])
# Increment i
i +=2
return new_list
string formatted = date.ToString("dd-MM-yyyy");
will do it.
Here is a good reference for different formats.
I can second the previous posters enthusiasm for the Gideros Lua game engine, whilst focusing currently on Mobile (iOS and Android - Windows phone 8 is in the works), desktop support for Mac, PC (possibly Linux) is also planned for the not too distant future.
Google for "Gideros Mobile"
You're on the right track. Now you just need to extract the desired group, as follows:
final Pattern pattern = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
final Matcher matcher = pattern.matcher("<tag>String I want to extract</tag>");
matcher.find();
System.out.println(matcher.group(1)); // Prints String I want to extract
If you want to extract multiple hits, try this:
public static void main(String[] args) {
final String str = "<tag>apple</tag><b>hello</b><tag>orange</tag><tag>pear</tag>";
System.out.println(Arrays.toString(getTagValues(str).toArray())); // Prints [apple, orange, pear]
}
private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
private static List<String> getTagValues(final String str) {
final List<String> tagValues = new ArrayList<String>();
final Matcher matcher = TAG_REGEX.matcher(str);
while (matcher.find()) {
tagValues.add(matcher.group(1));
}
return tagValues;
}
However, I agree that regular expressions are not the best answer here. I'd use XPath to find elements I'm interested in. See The Java XPath API for more info.
You can replace IList<DzieckoAndOpiekun> resultV
with var resultV
.
in the DBAdaper i.e Data Base helper class declare the table like this
private static final String USERDETAILS=
"create table userdetails(usersno integer primary key autoincrement,userid text not null ,username text not null,password text not null,photo BLOB,visibility text not null);";
insert the values like this,
first convert the images as byte[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] photo = baos.toByteArray();
db.insertUserDetails(value1,value2, value3, photo,value2);
in DEAdaper class
public long insertUserDetails(String uname,String userid, String pass, byte[] photo,String visibility)
{
ContentValues initialValues = new ContentValues();
initialValues.put("username", uname);
initialValues.put("userid",userid);
initialValues.put("password", pass);
initialValues.put("photo",photo);
initialValues.put("visibility",visibility);
return db.insert("userdetails", null, initialValues);
}
retrieve the image as follows
Cursor cur=your query;
while(cur.moveToNext())
{
byte[] photo=cur.getBlob(index of blob cloumn);
}
convert the byte[] into image
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
I think this content may solve your problem
I did it with jQuery:
page.execute_script %Q{ $('#some_id').prop('checked', true) }
As mentioned previously, a function needs to be passed to toThrow
as it is the function you're describing in your test: "I expect this function to throw x"
expect(() => parser.parse(raw))
.toThrow(new Error('Parsing is not possible'));
If using Jasmine-Matchers you can also use one of the following when they suit the situation;
// I just want to know that an error was
// thrown and nothing more about it
expect(() => parser.parse(raw))
.toThrowAnyError();
or
// I just want to know that an error of
// a given type was thrown and nothing more
expect(() => parser.parse(raw))
.toThrowErrorOfType(TypeError);
Console
outputs to the console window and Winforms applications do not show the console window. You should be able to use System.Diagnostics.Debug.WriteLine
to send output to the output window in your IDE.
Edit: In regards to the problem, have you verified your mainForm_Load
is actually being called? You could place a breakpoint at the beginning of mainForm_Load
to see. If it is not being called, I suspect that mainForm_Load
is not hooked up to the Load
event.
Also, it is more efficient and generally better to override On{EventName}
instead of subscribing to {EventName}
from within derived classes (in your case overriding OnLoad
instead of Load
).
Today March 6, 2013, Microsoft released SQL Server Data Tools – Business Intelligence for Visual Studio 2012 (SSDT BI) templates. With SSDT BI for Visual Studio 2012 you can develop and deploy SQL Server Business intelligence projects. Projects created in Visual Studio 2010 can be opened in Visual Studio 2012 and the other way around without upgrading or downgrading – it just works.
The download/install is named to ensure you get the SSDT templates that contain the Business Intelligence projects. The setup for these tools is now available from the web and can be downloaded in multiple languages right here: http://www.microsoft.com/download/details.aspx?id=36843
In my case, none of above answers nor google's official documentation helped me to grab the concept of PendingIntent
class.
And then I found this video, Google I/O 2013, Beyond the Blue Dot session. In this video, ex-googler Jaikumar Ganesh explains what PendingIntent
is, and that was the thing gave me the big picture of this.
Below is just transcription of above video (from 15:24).
So what's a pending intent?
It's a token that your app process will give to the location process, and the location process will use it to wake up your app when an event of interest happens. So this basically means that your app in the background doesn't have to be always running. When something of interest happens, we will wake you up. This saves a lot of battery.
This explanation becomes more clear with this snippet of code(which is included in the session's slide).
PendingIntent mIntent = PendingIntent.getService(...);
mLocationClient.requestLocationUpdates(locationRequest, mIntent);
public void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_LOCATION.equals(action)) {
Location location = intent.getParcelableExtra(...)
}
}
$postbody='';
// Check for presence of a body in the request
if (count($request->json()->all())) {
$postbody = $request->json()->all();
}
This is how it's done in laravel 5.2 now.
plt.plot(X_plot, X_plot*results.params[0] + results.params[1])
versus
plt.plot(X_plot, X_plot*results.params[1] + results.params[0])
Under the help menu, there should be a menu item labeled "About Eclipse" I can't say with absolute precision because I'm using STS which is the same thing but my label is different.
In the dialog box that opens after you click the relevant about menu item there should be an installation details button in the lower left hand corner.
The version of Java that you're running Eclipse against ought to be in "System properties:" under the "Configuration" tab.