You can also use this:
grep -v 'pattern' filename
Here -v
will print only other than your pattern (that means invert match).
No there is not : But I have created one easy class to help :
public class PropertiesUtility
{
private static Hashtable ht = new Hashtable();
public void loadProperties(string path)
{
string[] lines = System.IO.File.ReadAllLines(path);
bool readFlag = false;
foreach (string line in lines)
{
string text = Regex.Replace(line, @"\s+", "");
readFlag = checkSyntax(text);
if (readFlag)
{
string[] splitText = text.Split('=');
ht.Add(splitText[0].ToLower(), splitText[1]);
}
}
}
private bool checkSyntax(string line)
{
if (String.IsNullOrEmpty(line) || line[0].Equals('['))
{
return false;
}
if (line.Contains("=") && !String.IsNullOrEmpty(line.Split('=')[0]) && !String.IsNullOrEmpty(line.Split('=')[1]))
{
return true;
}
else
{
throw new Exception("Can not Parse Properties file please verify the syntax");
}
}
public string getProperty(string key)
{
if (ht.Contains(key))
{
return ht[key].ToString();
}
else
{
throw new Exception("Property:" + key + "Does not exist");
}
}
}
Hope this helps.
if(isset($rule["type"]) && ($rule["type"] == "radio") || ($rule["type"] == "checkbox") )
{
if(!isset($data[$field]))
$data[$field]="";
}
If you don't have dos2unix utility installed on your system, you can create your own to get rid of Windows endline characters:
vi ~/dos2unix.bash:
with the following content
#!/bin/bash
tr -d '\r' < $1 > repl.tmp
mv -f repl.tmp $1
In your ~/.bashrc, add the line:
alias 'dos2unix=~/dos2unix.bash'
Applying
dos2unix file_from_PC.txt
will remove ^M characters at lines ends in file_from_PC.txt. You can check if you have those or not by using cat:
cat -v file_from_PC.txt
A more straight forward way is to check for equality
if string1 == string2
puts "match"
else
puts "not match"
end
however, if you really want to stick to regular expression,
string1 =~ /^123456$/
String.prototype.trimStartWhile = function(predicate) {_x000D_
if (typeof predicate !== "function") {_x000D_
return this;_x000D_
}_x000D_
let len = this.length;_x000D_
if (len === 0) {_x000D_
return this;_x000D_
}_x000D_
let s = this, i = 0;_x000D_
while (i < len && predicate(s[i])) {_x000D_
i++;_x000D_
}_x000D_
return s.substr(i)_x000D_
}_x000D_
_x000D_
let str = "0000000000ABC",_x000D_
r = str.trimStartWhile(c => c === '0');_x000D_
_x000D_
console.log(r);
_x000D_
You could try this if you have 3 dataframes
# Merge multiple dataframes
df1 = pd.DataFrame(np.array([
['a', 5, 9],
['b', 4, 61],
['c', 24, 9]]),
columns=['name', 'attr11', 'attr12'])
df2 = pd.DataFrame(np.array([
['a', 5, 19],
['b', 14, 16],
['c', 4, 9]]),
columns=['name', 'attr21', 'attr22'])
df3 = pd.DataFrame(np.array([
['a', 15, 49],
['b', 4, 36],
['c', 14, 9]]),
columns=['name', 'attr31', 'attr32'])
pd.merge(pd.merge(df1,df2,on='name'),df3,on='name')
alternatively, as mentioned by cwharland
df1.merge(df2,on='name').merge(df3,on='name')
Try any one of the below. These should work:
int a = Character.getNumericValue('3');
int a = Integer.parseInt(String.valueOf('3');
In the latest version of Angular (1.1.5), they have included a conditional directive called ngIf
. It is different from ngShow
and ngHide
in that the elements aren't hidden, but not included in the DOM at all. They are very useful for components which are costly to create but aren't used:
<h1 ng-if="editMode" contenteditable=true>{{content.title}}</h1>
go plain for SWIFT 3 and APACHE simple Auth:
func urlSession(_ session: URLSession, task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let credential = URLCredential(user: "test",
password: "test",
persistence: .none)
completionHandler(.useCredential, credential)
}
I had this problem when missing a closing tag in the html.
So instead of:
<table></table>
..my HTML was
<table>...<table>
Tried to load jQuery after angular as mentioned above. This prevented the error message, but didn't really fix the problem. And jQuery '.find' didn't really work afterwards..
Solution was to fix the missing closing tag.
Holo
, for example Theme
)When you create the style incorrectly or from an existing style, this problem usually occurs. So select the "Graphical Layout" select "AppTheme" (The tab with a blue star). And select any of the predefined style. In my case "Light" which should resolve the problem.
Restart your Android Studio by choosing this option. It may take some time.
Then, if still doesn't work try to rebuild your project.
If it's Windows, all you need to do is delete the root of that project within the file explorer. Just right click on the name of the app in Android Studio, and then "show in file explorer". Then just delete the project folder all in all.
i like this clever syntax to do async work from an entrypoint
void async function main() {
await doSomeWork()
await doMoreWork()
}()
In my case it doesn't work, even with __DIR__
or getcwd()
it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:
if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }
require_once THISBASEPATH.'cache/crud.php';
/*every other require_once you need*/
I have MAMP with php 5.4.10 and my folder hierarchy is basilar:
q.php
w.php
e.php
r.php
cache/a.php
cache/b.php
setting/a.php
setting/b.php
....
As already pointed out by @snishalaka, you can increase the number of inotify watchers.
However, I think the default number is high enough and is only reached when processes are not cleaned up properly. Hence, I simply restarted my computer as proposed on a related github issue and the error message was gone.
Try this extension method to add the desired behaviour to any TextBox control. I havn't tested it extensively yet, but it seems to fulfil my needs.
public static class TextBoxExtensions
{
public static void SetupSelectAllOnGotFocus(this TextBox source)
{
source.GotFocus += SelectAll;
source.PreviewMouseLeftButtonDown += SelectivelyIgnoreMouseButton;
}
private static void SelectAll(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
textBox.SelectAll();
}
private static void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e)
{
var textBox = (sender as TextBox);
if (textBox != null)
{
if (!textBox.IsKeyboardFocusWithin)
{
e.Handled = true;
textBox.Focus();
}
}
}
}
I have a base profile .mp4 video which plays on one server, and does not on another.
The only difference is:
one gives a header "Content-Length: ..."
the other "Trasfer-Encoding: chunked".
I found out that Content-Length is not needed, it is only important, that there should be NO chunked header. This can be done by turning off compression (deflate or gzip) for .mp4 files. How this can be done is another issue and another topic: How to disable Apache gzip compression for some media files in .htaccess file?
There can be another server issue:
it has to give "Content-Type: video/mp4"
and NOT "Content-Type: text/plain"
Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:
Example:
POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"
content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"
content of picture_of_sunset.jpg ...
--12345--
I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:
POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde
--abcde
Content-Disposition: file; file="picture.jpg"
content of jpg...
--abcde
Content-Disposition: file; file="test.py"
content of test.py file ....
--abcde--
--12345--
Take a look at the link above.
If you plan on getting a random value a lot, you might want to define a function for it.
First, put this in your code somewhere:
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
Now:
[1,2,3,4].sample() //=> a random element
Code released into the public domain under the terms of the CC0 1.0 license.
This will add a new column to your data.frame
with the specified format.
df$Month_Yr <- format(as.Date(df$Date), "%Y-%m")
df
#> ID Date Month_Yr
#> 1 1 2004-02-06 2004-02
#> 2 2 2006-03-14 2006-03
#> 3 3 2007-07-16 2007-07
# your data sample
df <- data.frame( ID=1:3,Date = c("2004-02-06" , "2006-03-14" , "2007-07-16") )
a simple example:
dates <- "2004-02-06"
format(as.Date(dates), "%Y-%m")
> "2004-02"
side note:
the data.table
approach can be quite faster in case you're working with a big dataset.
library(data.table)
setDT(df)[, Month_Yr := format(as.Date(Date), "%Y-%m") ]
As a commenter mentioned you can get Values
from net/url
which has an Encode
method. You could do something like this (req.URL.Query()
returns the existing url.Values
)
package main
import (
"fmt"
"log"
"net/http"
"os"
)
func main() {
req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// Output:
// http://api.themoviedb.org/3/tv/popular?another_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}
Locate phpMyAdmin installation path.
Open phpMyAdmin/config.inc.php
in your favourite text editor. Copy config.sample.inc.php
to config.inc.php
if it's missing.
Search for $cfg['Servers'][$i]['auth_type'] = 'config';
Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';
You need to start the script with a preceding dot, this will put the exported variables in the current environment.
#!/bin/bash
...
export output="SUCCESS"
Then execute it like so
chmod +x /tmp/test.sh
. /tmp/test.sh
When you need the entire output and not just a single value, just put the output in a variable like the other answers indicate
Well, you are using both frame.setSize()
and frame.pack()
.
You should use one of them at one time.
Using setSize()
you can give the size of frame you want but if you use pack()
, it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.
Try removing frame.pack()
from your code or putting it before setting size and then run it.
In SQL Server 2000 you can try:
IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')
BEGIN
SELECT 1 AS 'res'
END
Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.
If InStr(myString, "A") > 0 Then
For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.
Left(oldStr, InStr(oldStr, "A"))
We know the above is true. Jon is never wrong; real life wishes can go a little further.
<ota:OTA_AirAvailRQ
xmlns:ota="http://www.opentravel.org/OTA/2003/05" EchoToken="740" Target=" Test" TimeStamp="2012-07-19T14:42:55.198Z" Version="1.1">
<ota:OriginDestinationInformation>
<ota:DepartureDateTime>2012-07-20T00:00:00Z</ota:DepartureDateTime>
</ota:OriginDestinationInformation>
</ota:OTA_AirAvailRQ>
For example, usually the problem is, how can we get EchoToken in the above XML document? Or how to blur the element with the name attribute.
You can find them by accessing with the namespace and the name like below
doc.Descendants().Where(p => p.Name.LocalName == "OTA_AirAvailRQ").Attributes("EchoToken").FirstOrDefault().Value
You can find it by the attribute content value, like this one.
SELECT * FROM table SAMPLE(10) WHERE ROWNUM <= 20;
This is more efficient as it doesn't need to sort the Table.
You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding
class.
or try this
System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);
I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):
Sub getData()
Dim Movie As Object
Dim scriptControl As Object
Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
scriptControl.Language = "JScript"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
.send
Set Movie = scriptControl.Eval("(" + .responsetext + ")")
.abort
With Sheets(2)
.Cells(1, 1).Value = Movie.Title
.Cells(1, 2).Value = Movie.Year
.Cells(1, 3).Value = Movie.Rated
.Cells(1, 4).Value = Movie.Released
.Cells(1, 5).Value = Movie.Runtime
.Cells(1, 6).Value = Movie.Director
.Cells(1, 7).Value = Movie.Writer
.Cells(1, 8).Value = Movie.Actors
.Cells(1, 9).Value = Movie.Plot
.Cells(1, 10).Value = Movie.Language
.Cells(1, 11).Value = Movie.Country
.Cells(1, 12).Value = Movie.imdbRating
End With
End With
End Sub
Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.
The way we do that is with og:meta
tags.
The tags look something like this -
<meta property="og:title" content="Stuffed Cookies" />
<meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
<meta property="og:description" content="The Turducken of Cookies" />
<meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">
You'll need to place these or similar meta tags in the <head>
of your HTML file. Don't forget to substitute the values for your own!
For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/
Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.
One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.
For me,
Even after upgrading to appcompat-v7:22.1.0
, in which AppCompatActivty
is added,
the problem was not resolved for me, Android Studio was giving same problem
Cannot resolve symbol 'AppCompatActivity'
Sometimes clearing the android studio caches help.
In android studio I just cleared the caches and restarted with the following option--
File->Invalidate Caches/Restart
Use Statement Fetch Size , if you are retrieving more number of records. like this.
Statement statement = connection.createStatement();
statement.setFetchSize(1000);
Apart from that i dont see an issue with the way you are doing in terms of performance
In terms of Neat. Always use seperate method delegate to map the resultset to POJO object. which can be reused later in the same class
like
private User mapResultSet(ResultSet rs){
User user = new User();
// Map Results
return user;
}
If you have the same name for both columnName and object's fieldName , you could also write reflection utility to load the records back to POJO. and use MetaData to read the columnNames . but for small scale projects using reflection is not an problem. but as i said before there is nothing wrong with the way you are doing.
Ubuntu 18.04.5 LTS (Bionic Beaver):
apt --reinstall install python3-debian
apt --reinstall install python3-six
If /usr/bin/chardet3 fails with error "ModuleNotFoundError: No module named 'pkg_resources'":
apt --reinstall install python3-pkg-resources
You can convert .jar file to .exe on these ways:
(source: viralpatel.net)
1- JSmooth .exe wrapper:
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a web site.
JSmooth provides a variety of wrappers for your java application, each of them having their own behaviour: Choose your flavour!
Download: http://jsmooth.sourceforge.net/
2- JarToExe 1.8
Jar2Exe is a tool to convert jar files into exe files.
Following are the main features as describe in their website:
Download: http://www.brothersoft.com/jartoexe-75019.html
3- Executor
Package your Java application as a jar, and Executor will turn the jar into a Windows exe file, indistinguishable from a native application. Simply double-clicking the exe file will invoke the Java Runtime Environment and launch your application.
Download: http://mpowers.net/executor/
EDIT: The above link is broken, but here is the page (with working download) from the Internet Archive. http://web.archive.org/web/20090316092154/http://mpowers.net/executor/
4- Advanced Installer
Advanced Installer lets you create Windows MSI installs in minutes. This also has Windows Vista support and also helps to create MSI packages in other languages.
Download: http://www.advancedinstaller.com/
Let me know other tools that you have used to convert JAR to EXE.
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
Another useful property of the cross product is that its magnitude is related to the sine of the angle between the two vectors:
| a x b | = |a| . |b| . sine(theta)
or
sine(theta) = | a x b | / (|a| . |b|)
So, in implementation 1 above, if a
and b
are known in advance to be unit vectors then the result of that function is exactly that sine() value.
Not sure if this matters to anyone else, but I prefer the id for the table to be the first column in the database. The syntax for that is:
ALTER TABLE your_db.your_table ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT FIRST;
Which is just a slight improvement over the first answer. If you wanted it to be in a different position, then
ALTER TABLE unique_address ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT AFTER some_other_column;
HTH, -ft
Your format specifier is incorrect. From the printf()
man page on my machine:
0
A zero '0
' character indicating that zero-padding should be used rather than blank-padding. A '-
' overrides a '0
' if both are used;Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);
Precision: An optional period, '
.
', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;
For your case, your format would be %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f\n", 4917.24);
return 0;
}
Output:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
Note that this answer is conditional on your embedded system having a printf()
implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.
I had a similar problem. I wanted to have two controllers:
homepage.php - public facing homepage
home.php - home screen once a user was logged in
and I wanted them both to read from 'mydomain.com'
I was able to accomplish this by setting 'hompepage' as the default controller in my routes config and adding a remap function to homepage.php
function _remap()
{
if(user_is_logged_in())
{
require_once(APPPATH.'controllers/home.php');
$oHome = new Home();
$oHome->index();
}
else
{
$this->index();
}
}
The best place for it is just before you need it and no sooner.
Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.
Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.
This article by Ian Griffiths gives two different solutions to the problem that he concludes are neat tricks that you should not use.
According to this discussion: http://bytes.com/topic/python/answers/464012-objects-list-index
Loop counter iteration
The current idiom for looping over the indices makes use of the built-in range
function:
for i in range(len(sequence)):
# work with index i
Looping over both elements and indices can be achieved either by the old idiom or by using the new zip
built-in function:
for i in range(len(sequence)):
e = sequence[i]
# work with index i and element e
or
for i, e in zip(range(len(sequence)), sequence):
# work with index i and element e
I was facing the same issue. I was missing DriverManager.registerDriver() call, before getting the connection using the connection URL and user credentials.
It got fixed on Linux as below:
DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
connection = DriverManager.getConnection("jdbc:derby://localhost:1527//tmp/Test/DB_Name", user, pass);
For Windows:
DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
connection = DriverManager.getConnection("jdbc:derby://localhost:1527/C:/Users/Test/DB_Name", user, pass);
The realpath
command prints the resolved path:
realpath *
To include dot files, pipe the output of ls -a
to realpath:
ls -a | xargs realpath
To list subdirectories recursively:
ls -aR | xargs realpath
In case you have spaces in file names, man xargs
recommends using the -o
option to prevent file names from being processed incorrectly, this works best with the output of find -print0
and it starts to look a lot more complex than other answers:
find -print0 |xargs -0 realpath
See also Unix and Linux stackexchange question on how to list all files in a directory with absolute path.
CREATE PROCEDURE [dbo].[sp_Myforeach_Date]
-- Add the parameters for the stored procedure here
@SatrtDate as DateTime,
@EndDate as dateTime,
@DatePart as varchar(2),
@OutPutFormat as int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
Declare @DateList Table
(Date varchar(50))
WHILE @SatrtDate<= @EndDate
BEGIN
INSERT @DateList (Date) values(Convert(varchar,@SatrtDate,@OutPutFormat))
IF Upper(@DatePart)='DD'
SET @SatrtDate= DateAdd(dd,1,@SatrtDate)
IF Upper(@DatePart)='MM'
SET @SatrtDate= DateAdd(mm,1,@SatrtDate)
IF Upper(@DatePart)='YY'
SET @SatrtDate= DateAdd(yy,1,@SatrtDate)
END
SELECT * FROM @DateList
END
Just put this Code and call the SP in This way
exec sp_Myforeach_Date @SatrtDate='03 Jan 2010',@EndDate='03 Mar 2010',@DatePart='dd',@OutPutFormat=106
128 characters. This is the max length of the sysname
datatype (nvarchar(128)
).
One way to achieve this is to add a DefaultDocument settings in the Web.config.
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="DefaultPage.aspx" />
</files>
</defaultDocument>
</system.webServer>
I Know, I am very late but, May be my answer can help someone. Basically it's very Simple. Here is my Code.
#include<iostream>
#include<windows.h>
using namespace std;
int main()
{
HANDLE colors=GetStdHandle(STD_OUTPUT_HANDLE);
string text;
int k;
cout<<" Enter your Text : ";
getline(cin,text);
for(int i=0;i<text.length();i++)
{
k>9 ? k=0 : k++;
if(k==0)
{
SetConsoleTextAttribute(colors,1);
}else
{
SetConsoleTextAttribute(colors,k);
}
cout<<text.at(i);
}
}
OUTPUT
This Image will show you how it works
If you want the full tutorial please see my video here: How to change Text color in C++
//gradle.properties
systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost
I've just come across this question too and found out that if anytime the build number gets corrupt because of any error-triggered hard shutdown of the jenkins instance you can set back the build number manually by just editing the file nextBuildNumber (pathToJenkins\jobs\jobxyz\nextBuildNumber) and then make a reload by using the option
Reload Configuration from Disk from the Manage Jenkins View.
Go to File->Settings->Version Control->Subversion enter the path for your SVN executable in the General tab under Subversion configuration directory. Also, you can download a latest SVN client such as VisualSVN and point the path to the executable as mentioned above. That will most likely solve your problem.
An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new
), whereas a class variable is a member of the class itself.
Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.
What’s the difference between a class variable and an instance variable?
This test class illustrates the difference:
public class Test {
public static String classVariable = "I am associated with the class";
public String instanceVariable = "I am associated with the instance";
public void setText(String string){
this.instanceVariable = string;
}
public static void setClassText(String string){
classVariable = string;
}
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test();
// Change test1's instance variable
test1.setText("Changed");
System.out.println(test1.instanceVariable); // Prints "Changed"
// test2 is unaffected
System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
// Change class variable (associated with the class itself)
Test.setClassText("Changed class text");
System.out.println(Test.classVariable); // Prints "Changed class text"
// Can access static fields through an instance, but there still is only one
// (not best practice to access static variables through instance)
System.out.println(test1.classVariable); // Prints "Changed class text"
System.out.println(test2.classVariable); // Prints "Changed class text"
}
}
It is inclusive. You are comparing datetimes to dates. The second date is interpreted as midnight when the day starts.
One way to fix this is:
SELECT *
FROM Cases
WHERE cast(created_at as date) BETWEEN '2013-05-01' AND '2013-05-01'
Another way to fix it is with explicit binary comparisons
SELECT *
FROM Cases
WHERE created_at >= '2013-05-01' AND created_at < '2013-05-02'
Aaron Bertrand has a long blog entry on dates (here), where he discusses this and other date issues.
Sharer.php no longer allows you to customize. The page you share will be scraped for OG Tags and that data will be shared.
To properly customize, use FB.UI
which comes with the JS-SDK.
Although there is clearly some kind of network instability or something interfering with your connection (15 minutes is possible that you could be crossing a NAT boundary or something in your network is dropping the session), I would think you want such a simple?) query to return well within any anticipated timeoue (like 1s).
I would talk to your DBA and get an index created on the underlying tables on MemberType, Status. If there isn't a single underlying table or these are more complex and created by the view or UDF, and you are running SQL Server 2005 or above, have him consider indexing the view (basically materializing the view in an indexed fashion).
Given the, most than probable similarities in performance, use whatever feel more correct and readable to the piece of code you're using.
I feel an operation that describes an addition, being the presence of the key already a really rare exception is best represented with the add. Semantically it makes more sense.
The dict[key] = value
represents better a substitution. If I see that code I half expect the key to already be in the dictionary anyway.
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
git stash && git stash pop
You can just simply add the following code;
<a class="btn btn-primary" href="http://localhost:8080/Home" role="button">Home Page</a>
You have done the stored procedure correctly but I think you have not referenced the valido
variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido
This statement SELECT valido;
should be like this SELECT @valido;
Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido
I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.
Date.parse()
is fairly intelligent but I can't guarantee that format will parse correctly.
If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split()
-- might be faster) paired with some parseInt()
will allow you to quickly make a date.
Try the following.
$d = [datetime](Get-ItemProperty -Path $source -Name LastWriteTime).lastwritetime
This is part of the item property weirdness. When you run Get-ItemProperty it does not return the value but instead the property. You have to use one more level of indirection to get to the value.
I was dealing with this issue after upgrading from Visual Studio 2013
to Visual Studio 2015
After trying most of the advice found in this and other similar SO posts, I finally found the problem. The first part of the fix was to update all of my NuGet
stuff to the latest version (you might need to do this in VS13
if you are experiencing the Nuget
bug) after, I had to, as you may need to, fix the versions listed in the Views Web.config
. This includes:
MVC
versions and its child libraries to the new version (expand the References
then right click onSytem.Web.MVC
then Properties
to get your version) Razor
version. Mine looked like this:
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.web>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
private void StudentForm_Load(object sender, EventArgs e)
{
string q = @"SELECT [BatchID] FROM [Batch]"; //BatchID column name of Batch table
SqlDataReader reader = DB.Query(q);
while (reader.Read())
{
cbsb.Items.Add(reader["BatchID"].ToString()); //cbsb is the combobox name
}
}
The Microsoft certification material addresses this same question. In the .NET world, the overhead for the StringBuilder object makes a simple concatenation of 2 String objects more efficient. I would assume a similar answer for Java strings.
I had a similar problem setting up eclipse in the office. I had set up the for HTTP, HTTPS and SOCKS in:
Window>pref>general>network connections
Clearing the proxy settings for SOCKS fixed the problem for me.
for line in file('/tmp/foo'):
print line.strip('\n')
$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
// enter your code here
} });
ALTER TABLE table_name ALTER COLUMN id SET DEFAULT uuid_in((md5((random())::text))::cstring);
After reading @ZuzEL's answer, i used the above code as the default value of the column id and it's working fine.
An alternative in Python 2.6 or above is to use collections.namedtuple()
-- it saves you writing any special methods:
from collections import namedtuple
MyThingBase = namedtuple("MyThingBase", ["name", "location"])
class MyThing(MyThingBase):
def __new__(cls, name, location, length):
obj = MyThingBase.__new__(cls, name, location)
obj.length = length
return obj
a = MyThing("a", "here", 10)
b = MyThing("a", "here", 20)
c = MyThing("c", "there", 10)
a == b
# True
hash(a) == hash(b)
# True
a == c
# False
You can't force accessing/changing element to which the user normally doesn't have access, as Selenium is designed to imitate user interaction.
If this error happens, check if:
maximize()
in node.js, maximize_window()
in Python),executeScript()
in node.js, execute_script()
in Python).Xamarin.iOS solution
public UIImage CreateImageFromColor()
{
var imageSize = new CGSize(30, 30);
var imageSizeRectF = new CGRect(0, 0, 30, 30);
UIGraphics.BeginImageContextWithOptions(imageSize, false, 0);
var context = UIGraphics.GetCurrentContext();
var red = new CGColor(255, 0, 0);
context.SetFillColor(red);
context.FillRect(imageSizeRectF);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return image;
}
Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage())
;
Depends on what you need.
In this case I suggest:
SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;
because there are few fields and the execution time of DISTINCT
is lower than the execution of GROUP BY
.
In other cases, for example where there are many fields, I prefer:
SELECT * FROM buy GROUP BY date ORDER BY date DESC;
You could use AsyncTask
, you'll have to customize to fit your needs, but something like the following
Async task has three primary methods:
onPreExecute()
- most commonly used for setting up and starting a progress dialog
doInBackground()
- Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).
onPostExecute()
- Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.First we will start the class, initialize a String
to hold the results outside of the methods but inside the class, then run the onPreExecute()
method setting up a simple progress dialog.
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
Then we need to set up the connection and how we want to handle the response:
@Override
protected Void doInBackground(String... params) {
String url_select = "http://yoururlhere.com";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
} // protected Void doInBackground(String... params)
Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
for(i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String name = jObject.getString("name");
String tab1_text = jObject.getString("tab1_text");
int active = jObject.getInt("active");
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
In short:
defaultdict(int)
- the argument int indicates that the values will be int type.
defaultdict(list)
- the argument list indicates that the values will be list type.
Here's a partial solution using xml2. Breaking the solution up into smaller pieces generally makes it easier to ensure everything is lined up:
library(xml2)
data <- read_xml("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")
# Point locations
point <- data %>% xml_find_all("//point")
point %>% xml_attr("latitude") %>% as.numeric()
point %>% xml_attr("longitude") %>% as.numeric()
# Start time
data %>%
xml_find_all("//start-valid-time") %>%
xml_text()
# Temperature
data %>%
xml_find_all("//temperature[@type='hourly']/value") %>%
xml_text() %>%
as.integer()
For run all lines of GridView don't use for
loop, use foreach
loop like:
foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
//if checked do something
}
}
}
You should be able to do that with the Batch Task plugin.
An alternative can also be Post build task plugin.
With respect to binning functions, I didn't expect the result of the functions offered so far. Namely, if my binwidth is 0.001, these functions were centering the bins on 0.0005 points, whereas I feel it's more intuitive to have the bins centered on 0.001 boundaries.
In other words, I'd like to have
Bin 0.001 contain data from 0.0005 to 0.0014
Bin 0.002 contain data from 0.0015 to 0.0024
...
The binning function I came up with is
my_bin(x,width) = width*(floor(x/width+0.5))
Here's a script to compare some of the offered bin functions to this one:
rint(x) = (x-int(x)>0.9999)?int(x)+1:int(x)
bin(x,width) = width*rint(x/width) + width/2.0
binc(x,width) = width*(int(x/width)+0.5)
mitar_bin(x,width) = width*floor(x/width) + width/2.0
my_bin(x,width) = width*(floor(x/width+0.5))
binwidth = 0.001
data_list = "-0.1386 -0.1383 -0.1375 -0.0015 -0.0005 0.0005 0.0015 0.1375 0.1383 0.1386"
my_line = sprintf("%7s %7s %7s %7s %7s","data","bin()","binc()","mitar()","my_bin()")
print my_line
do for [i in data_list] {
iN = i + 0
my_line = sprintf("%+.4f %+.4f %+.4f %+.4f %+.4f",iN,bin(iN,binwidth),binc(iN,binwidth),mitar_bin(iN,binwidth),my_bin(iN,binwidth))
print my_line
}
and here's the output
data bin() binc() mitar() my_bin()
-0.1386 -0.1375 -0.1375 -0.1385 -0.1390
-0.1383 -0.1375 -0.1375 -0.1385 -0.1380
-0.1375 -0.1365 -0.1365 -0.1375 -0.1380
-0.0015 -0.0005 -0.0005 -0.0015 -0.0010
-0.0005 +0.0005 +0.0005 -0.0005 +0.0000
+0.0005 +0.0005 +0.0005 +0.0005 +0.0010
+0.0015 +0.0015 +0.0015 +0.0015 +0.0020
+0.1375 +0.1375 +0.1375 +0.1375 +0.1380
+0.1383 +0.1385 +0.1385 +0.1385 +0.1380
+0.1386 +0.1385 +0.1385 +0.1385 +0.1390
When ever you require to communicate between child to parent at any level down, then it's better to make use of context. In parent component define the context that can be invoked by the child such as
In parent component in your case component 3
static childContextTypes = {
parentMethod: React.PropTypes.func.isRequired
};
getChildContext() {
return {
parentMethod: (parameter_from_child) => this.parentMethod(parameter_from_child)
};
}
parentMethod(parameter_from_child){
// update the state with parameter_from_child
}
Now in child component (component 5 in your case) , just tell this component that it want to use context of its parent.
static contextTypes = {
parentMethod: React.PropTypes.func.isRequired
};
render(){
return(
<TouchableHighlight
onPress={() =>this.context.parentMethod(new_state_value)}
underlayColor='gray' >
<Text> update state in parent component </Text>
</TouchableHighlight>
)}
you can find Demo project at repo
var newString = string.substr(0,string.indexOf(','));
A lot of Developers including have hard time at the beginning writing an AsyncTask because of the ambiguity of the parameters. The big reason is we try to memorize the parameters used in the AsyncTask. The key is Don't memorize. If you can visualize what your task really needs to do then writing the AsyncTask with the correct signature would be a piece of cake.
AsyncTask are background task which run in the background thread. It takes an Input, performs Progress and gives Output.
ie
AsyncTask<Input,Progress,Output>
Just figure out what your Input, Progress and Output are and you will be good to go.
For example
How does
doInbackground()
changes withAsyncTask
parameters?
How
doInBackground()
andonPostExecute()
,onProgressUpdate()
are related?
How can You write this in a code?
DownloadTask extends AsyncTask<String,Integer,String>{
@Override
public void onPreExecute(){
}
@Override
public String doInbackGround(String... params)
{
// Download code
int downloadPerc = // calculate that
publish(downloadPerc);
return "Download Success";
}
@Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
}
@Override
public void onProgressUpdate(Integer... params)
{
// show in spinner, access UI elements
}
}
How will you run this Task in Your Activity?
new DownLoadTask().execute("Paradise.mp3");
Correct syntax looks like this. See MSDN.
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS
This work for me
I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0);
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);
Yes it is, none of the Visual Stdio editions have C mentioned, but it is included with the C++ compiler (you therefore need to look under C++). The main difference between using C and C++ is the naming system (i.e. using .c and not .cpp).
You do have to be careful not to create a C++ project and rename it to C though, that does not work.
Much like you can use gcc
on Linux (or if you have MinGW installed) Visual Studio has a command to be used from command prompt (it must be the Visual Studio Developer Command Prompt though). As mentioned in the other answer you can use cl
to compile your c file (make sure it is named .c)
Example:
cl myfile.c
Or to check all the accepted commands:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27030.1 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
usage: cl [ option... ] filename... [ /link linkoption... ]
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>
Without doubt one of the best features of Visual Studio is the convenient IDE.
Although it takes more configuring, you get bonuses such as basic debugging before compiling (for example if you forget a ;
)
To create a C project do the following:
Start a new project, go under C++ and select Empty Project
, enter the Name
of your project and the Location
you want it to install to, then click Ok
. Now wait for the project to be created.
Next under Solutions Explorer
right click Source Files
, select Add
then New Item
. You should see something like this:
Rename Source.cpp
to include a .c
extension (Source.c
for example). Select the location you want to keep it in, I would recommend always keeping it within the project folder itself (in this case C:\Users\Simon\Desktop\Learn\My First C Code
)
It should open up the .c
file, ready to be modified. Visual Studio can now be used as normal, happy coding!
Just follow these steps to transfer the apk onto the real device(with debugger key) and which is just for testing purpose. (Note: For proper distribution to the market you may need to sign your app with your keys and follow all the steps.)
Good luck !
If you had python 2.x and then installed python3, your pip will be pointing to pip3.
you can verify that by typing pip --version
which would be the same as pip3 --version
.
On your system you have now pip, pip2 and pip3.
If you want you can change pip to point to pip2 instead of pip3.
Use ifelse
:
frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
data twohouses
1 0 1
2 1 1
3 2 2
4 3 2
5 4 2
...
16 0 1
17 2 2
18 1 1
19 2 2
20 0 1
21 4 2
The difference between if
and ifelse
:
if
is a control flow statement, taking a single logical value as an argumentifelse
is a vectorised function, taking vectors as all its arguments.The help page for if
, accessible via ?"if"
will also point you to ?ifelse
In Eztrieve it's really easy, below is an example how you could code it:
//STEP01 EXEC PGM=EZTPA00
//FILEA DD DSN=FILEA,DISP=SHR
//FILEB DD DSN=FILEB,DISP=SHR
//FILEC DD DSN=FILEC.DIF,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(100,50),RLSE),
// UNIT=PRMDA,
// DCB=(RECFM=FB,LRECL=5200,BLKSIZE=0)
//SYSOUT DD SYSOUT=*
//SRTMSG DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
FILE FILEA
FA-KEY 1 7 A
FA-REC1 8 10 A
FA-REC2 18 5 A
FILE FILEB
FB-KEY 1 7 A
FB-REC1 8 10 A
FB-REC2 18 5 A
FILE FILEC
FILE FILED
FD-KEY 1 7 A
FD-REC1 8 10 A
FD-REC2 18 5 A
JOB INPUT (FILEA KEY FA-KEY FILEB KEY FB-KEY)
IF MATCHED
FD-KEY = FB-KEY
FD-REC1 = FA-REC1
FD-REC2 = FB-REC2
PUT FILED
ELSE
IF FILEA
PUT FILEC FROM FILEA
ELSE
PUT FILEC FROM FILEB
END-IF
END-IF
/*
These are all great suggestions, but the one I use is:
du -ksh * | sort -n -r
-ksh
makes sure the files and folders are listed in a human-readable format and in megabytes, kilobytes, etc. Then you sort them numerically and reverse the sort so it puts the bigger ones first.
The only downside to this command is that the computer does not know that Gigabyte is bigger than Megabyte so it will only sort by numbers and you will often find listings like this:
120K
12M
4G
Just be careful to look at the unit.
This command also works on the Mac (whereas sort -h
does not for example).
No but JavaFX has it.
An ASP.NET HTTP
handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file
, the request is processed by the page via the page handler.
The ASP.NET page handler is only one type of handler. ASP.NET comes with several other built-in handlers such as the Web service handler for .asmx files
.
You can create custom HTTP handlers when you want special handling that you can identify using file name extensions in your application. For example, the following scenarios would be good uses of custom HTTP handlers:
RSS feeds To create an RSS feed for a site, you can create a handler that emits RSS-formatted XML. You can then bind the .rss extension (for example) in your application to the custom handler. When users send a request to your site that ends in .rss, ASP.NET will call your handler to process the request.
Image server If you want your Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them back to the user as the handler's response.
HTTP handlers have access to the application context, including the requesting user's identity (if known), application state, and session information. When an HTTP handler is requested, ASP.NET calls the ProcessRequest
method on the appropriate handler. The handler's ProcessRequest
method creates a response, which is sent back to the requesting browser. As with any page request, the response goes through any HTTP modules that have subscribed to events that occur after the handler has run.
Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.
You either need to catch it:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
Or declare that your method can throw an InterruptedException
:
public static void main(String[]args) throws InterruptedException
Related
Normaly for this operations you have to use the ecvt, fcvt or gcvt Functions:
/* gcvt example */
#include <stdio.h>
#include <stdlib.h>
main ()
{
char buffer [20];
gcvt (1365.249,6,buffer);
puts (buffer);
gcvt (1365.249,3,buffer);
puts (buffer);
return 0;
}
Output:
1365.25
1.37e+003
As a Function:
void double_to_char(double f,char * buffer){
gcvt(f,10,buffer);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
return true;
}
Horrible Answers Galore
Ozgur Ozcitak
When you cast from signed to unsigned (and vice versa) the internal representation of the number does not change. What changes is how the compiler interprets the sign bit.
This is completely wrong.
Mats Fredriksson
When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.
This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.
smh
Your addition operation causes the int to be converted to an unsigned int.
Wrong. Maybe it does and maybe it doesn't.
Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)
Wrong. It is either undefined behavior if it causes overflow or the value is preserved.
Anonymous
The value of i is converted to unsigned int ...
Wrong. Depends on the precision of an int relative to an unsigned int.
Taylor Price
As was previously answered, you can cast back and forth between signed and unsigned without a problem.
Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.
Now I can finally answer the question.
Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 [1]. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.
Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.
What is precision?
Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.
[Gotchas]
The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.
[1] The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.
Your function is probably in a different namespace than the one you're calling it from.
The | and & check both the sides everytime.
if (str == null | str.length() == 0)
here we have high possibility to get NullPointerException
Logical || and && check the right hand side only if necessary.
but with logical operator
no chance to get NPE because it will not check RHS
The file is created wherever the root of the python interpreter was started.
Eg, you start python in /home/user/program
, then the file "test.py" would be located at /home/user/program/test.py
project properities -> configuration properities -> general -> charater set
I would like to point out that if you can't find "Link Binaries With Libraries" in your build phases tab click the "Add build phase" button in the lower right corner.
When you install third-party extensions you need to make sure that all the compilation parameters match:
Common glitches includes:
php.ini
file (that's typical with bundles); the right path is shown in phpinfo()
.Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:
php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
If everything's right you should see sqlsrv
in the command output and/or phpinfo()
(depending on what SAPI you're configuring):
[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]
There is a refresh all option in the Pivot Table tool bar. That is enough. Dont have to do anything else.
Press ctrl+alt+F5
If your branch is behind by master then do:
git checkout master (you are switching your branch to master)
git pull
git checkout yourBranch (switch back to your branch)
git merge master
After merging it, check if there is a conflict or not.
If there is NO CONFLICT then:
git push
If there is a conflict then fix your file(s), then:
git add yourFile(s)
git commit -m 'updating my branch'
git push
For Sql Azure the following query works :
ALTER TABLE [TableName] ADD DEFAULT 'DefaultValue' FOR ColumnName
GO
The direct replacement is if
/elif
/else
.
However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".
In this case I would use a definition list as so:
<dl>
<dt>Fruits I like:</dt>
<dd>Apples</dd>
<dd>Bananas</dd>
<dd>Oranges</dd>
</dl>
Verify Google reCapcha is valid or not after form submit
if ($post['g-recaptcha-response']) {
$captcha = $post['g-recaptcha-response'];
$secretKey = 'type here private key';
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secretKey . "&response=" . $captcha);
$responseKeys = json_decode($response, true);
if (intval($responseKeys["success"]) !== 1) {
return "failed";
} else {
return "success";
}
}
else {
return "failed";
}
[This is a late answer addressing the title of the question (since that is what people would encounter when searching) rather than the specifics of OP's question which has already been answered adequately]
Ubound
is a bit fragile in that it provides no way to know how many dimensions an array has. You can use error trapping to determine the full layout of an array. The following returns a collection of arrays, one for each dimension. The count
property can be used to determine the number of dimensions and their lower and upper bounds can be extracted as needed:
Function Bounds(A As Variant) As Collection
Dim C As New Collection
Dim v As Variant, i As Long
On Error GoTo exit_function
i = 1
Do While True
v = Array(LBound(A, i), UBound(A, i))
C.Add v
i = i + 1
Loop
exit_function:
Set Bounds = C
End Function
Used like this:
Sub test()
Dim i As Long
Dim A(1 To 10, 1 To 5, 4 To 10) As Integer
Dim B(1 To 5) As Variant
Dim C As Variant
Dim sizes As Collection
Set sizes = Bounds(A)
Debug.Print "A has " & sizes.Count & " dimensions:"
For i = 1 To sizes.Count
Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
Next i
Set sizes = Bounds(B)
Debug.Print vbCrLf & "B has " & sizes.Count & " dimensions:"
For i = 1 To sizes.Count
Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
Next i
Set sizes = Bounds(C)
Debug.Print vbCrLf & "C has " & sizes.Count & " dimensions:"
For i = 1 To sizes.Count
Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
Next i
End Sub
Output:
A has 3 dimensions:
1 to 10
1 to 5
4 to 10
B has 1 dimensions:
1 to 5
C has 0 dimensions:
You might want to check out this page: http://pajhome.org.uk/crypt/md5/
However, if protecting the password is important, you should really be using something like SHA256 (MD5 is not cryptographically secure iirc). Even more, you might want to consider using TLS and getting a cert so you can use https.
{
void *mem = malloc(1024+16);
void *ptr = ((char *)mem+16) & ~ 0x0F;
memset_16aligned(ptr, 0, 1024);
free(mem);
}
{
void *mem = malloc(1024+15);
void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F;
memset_16aligned(ptr, 0, 1024);
free(mem);
}
The first step is to allocate enough spare space, just in case. Since the memory must be 16-byte aligned (meaning that the leading byte address needs to be a multiple of 16), adding 16 extra bytes guarantees that we have enough space. Somewhere in the first 16 bytes, there is a 16-byte aligned pointer. (Note that malloc()
is supposed to return a pointer that is sufficiently well aligned for any purpose. However, the meaning of 'any' is primarily for things like basic types — long
, double
, long double
, long long
, and pointers to objects and pointers to functions. When you are doing more specialized things, like playing with graphics systems, they can need more stringent alignment than the rest of the system — hence questions and answers like this.)
The next step is to convert the void pointer to a char pointer; GCC notwithstanding, you are not supposed to do pointer arithmetic on void pointers (and GCC has warning options to tell you when you abuse it). Then add 16 to the start pointer. Suppose malloc()
returned you an impossibly badly aligned pointer: 0x800001. Adding the 16 gives 0x800011. Now I want to round down to the 16-byte boundary — so I want to reset the last 4 bits to 0. 0x0F has the last 4 bits set to one; therefore, ~0x0F
has all bits set to one except the last four. Anding that with 0x800011 gives 0x800010. You can iterate over the other offsets and see that the same arithmetic works.
The last step, free()
, is easy: you always, and only, return to free()
a value that one of malloc()
, calloc()
or realloc()
returned to you — anything else is a disaster. You correctly provided mem
to hold that value — thank you. The free releases it.
Finally, if you know about the internals of your system's malloc
package, you could guess that it might well return 16-byte aligned data (or it might be 8-byte aligned). If it was 16-byte aligned, then you'd not need to dink with the values. However, this is dodgy and non-portable — other malloc
packages have different minimum alignments, and therefore assuming one thing when it does something different would lead to core dumps. Within broad limits, this solution is portable.
Someone else mentioned posix_memalign()
as another way to get the aligned memory; that isn't available everywhere, but could often be implemented using this as a basis. Note that it was convenient that the alignment was a power of 2; other alignments are messier.
One more comment — this code does not check that the allocation succeeded.
Windows Programmer pointed out that you can't do bit mask operations on pointers, and, indeed, GCC (3.4.6 and 4.3.1 tested) does complain like that. So, an amended version of the basic code — converted into a main program, follows. I've also taken the liberty of adding just 15 instead of 16, as has been pointed out. I'm using uintptr_t
since C99 has been around long enough to be accessible on most platforms. If it wasn't for the use of PRIXPTR
in the printf()
statements, it would be sufficient to #include <stdint.h>
instead of using #include <inttypes.h>
. [This code includes the fix pointed out by C.R., which was reiterating a point first made by Bill K a number of years ago, which I managed to overlook until now.]
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void memset_16aligned(void *space, char byte, size_t nbytes)
{
assert((nbytes & 0x0F) == 0);
assert(((uintptr_t)space & 0x0F) == 0);
memset(space, byte, nbytes); // Not a custom implementation of memset()
}
int main(void)
{
void *mem = malloc(1024+15);
void *ptr = (void *)(((uintptr_t)mem+15) & ~ (uintptr_t)0x0F);
printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr);
memset_16aligned(ptr, 0, 1024);
free(mem);
return(0);
}
And here is a marginally more generalized version, which will work for sizes which are a power of 2:
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void memset_16aligned(void *space, char byte, size_t nbytes)
{
assert((nbytes & 0x0F) == 0);
assert(((uintptr_t)space & 0x0F) == 0);
memset(space, byte, nbytes); // Not a custom implementation of memset()
}
static void test_mask(size_t align)
{
uintptr_t mask = ~(uintptr_t)(align - 1);
void *mem = malloc(1024+align-1);
void *ptr = (void *)(((uintptr_t)mem+align-1) & mask);
assert((align & (align - 1)) == 0);
printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr);
memset_16aligned(ptr, 0, 1024);
free(mem);
}
int main(void)
{
test_mask(16);
test_mask(32);
test_mask(64);
test_mask(128);
return(0);
}
To convert test_mask()
into a general purpose allocation function, the single return value from the allocator would have to encode the release address, as several people have indicated in their answers.
Uri commented: Maybe I am having [a] reading comprehension problem this morning, but if the interview question specifically says: "How would you allocate 1024 bytes of memory" and you clearly allocate more than that. Wouldn't that be an automatic failure from the interviewer?
My response won't fit into a 300-character comment...
It depends, I suppose. I think most people (including me) took the question to mean "How would you allocate a space in which 1024 bytes of data can be stored, and where the base address is a multiple of 16 bytes". If the interviewer really meant how can you allocate 1024 bytes (only) and have it 16-byte aligned, then the options are more limited.
However, if the interviewer expected either of those responses, I'd expect them to recognize that this solution answers a closely related question, and then to reframe their question to point the conversation in the correct direction. (Further, if the interviewer got really stroppy, then I wouldn't want the job; if the answer to an insufficiently precise requirement is shot down in flames without correction, then the interviewer is not someone for whom it is safe to work.)
The title of the question has changed recently. It was Solve the memory alignment in C interview question that stumped me. The revised title (How to allocate aligned memory only using the standard library?) demands a slightly revised answer — this addendum provides it.
C11 (ISO/IEC 9899:2011) added function aligned_alloc()
:
7.22.3.1 The
aligned_alloc
functionSynopsis
#include <stdlib.h> void *aligned_alloc(size_t alignment, size_t size);
Description
Thealigned_alloc
function allocates space for an object whose alignment is specified byalignment
, whose size is specified bysize
, and whose value is indeterminate. The value ofalignment
shall be a valid alignment supported by the implementation and the value ofsize
shall be an integral multiple ofalignment
.Returns
Thealigned_alloc
function returns either a null pointer or a pointer to the allocated space.
And POSIX defines posix_memalign()
:
#include <stdlib.h> int posix_memalign(void **memptr, size_t alignment, size_t size);
DESCRIPTION
The
posix_memalign()
function shall allocatesize
bytes aligned on a boundary specified byalignment
, and shall return a pointer to the allocated memory inmemptr
. The value ofalignment
shall be a power of two multiple ofsizeof(void *)
.Upon successful completion, the value pointed to by
memptr
shall be a multiple ofalignment
.If the size of the space requested is 0, the behavior is implementation-defined; the value returned in
memptr
shall be either a null pointer or a unique pointer.The
free()
function shall deallocate memory that has previously been allocated byposix_memalign()
.RETURN VALUE
Upon successful completion,
posix_memalign()
shall return zero; otherwise, an error number shall be returned to indicate the error.
Either or both of these could be used to answer the question now, but only the POSIX function was an option when the question was originally answered.
Behind the scenes, the new aligned memory function do much the same job as outlined in the question, except they have the ability to force the alignment more easily, and keep track of the start of the aligned memory internally so that the code doesn't have to deal with specially — it just frees the memory returned by the allocation function that was used.
Thanks to Chris for the starting point here is a improvement which addresses the resizing of the images used, the use of first-child is just to indicate you could use a variety of icons within the list to give you full control.
ul li:first-child:before {
content: '';
display: inline-block;
height: 25px;
width: 35px;
background-image: url('../images/Money.png');
background-size: contain;
background-repeat: no-repeat;
margin-left: -35px;
}
This seems to work well in all modern browsers, you will need to ensure that the width and the negative margin left have the same value, hope it helps
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
Since no public member function is needed to fetch and update protected members in the derived class, this increases the efficiency of code and reduces the amount of code we need to write. However, programmer of the derived class is supposed to be aware of what he is doing.
The following will order your data depending on both column in descending order.
ORDER BY article_rating DESC, article_time DESC
I ended up using a shell script with the following code:
#!/bin/bash
while [ 1 == 1 ]
do
clear
ps auxf |grep -ve "grep" |grep -E "MSG[^\ ]*" --color=auto
sleep 5
done
import java.util.Scanner;
public class Mostrepeatednumber
{
public static void main(String args[])
{
int most = 0;
int temp=0;
int count=0,tempcount;
Scanner in=new Scanner(System.in);
System.out.println("Enter any number");
int n=in.nextInt();
int arr[]=new int[n];
System.out.print("Enter array value:");
for(int i=0;i<=n-1;i++)
{
int n1=in.nextInt();
arr[i]=n1;
}
//!!!!!!!! user input concept closed
//logic can be started
for(int j=0;j<=n-1;j++)
{
temp=arr[j];
tempcount=0;
for(int k=1;k<=n-1;k++)
{
if(temp==arr[k])
{
tempcount++;
}
if(count<tempcount)
{
most=arr[k];
count=tempcount;
}
}
}
System.out.println(most);
}
}
SELECT T.TABLE_NAME, C.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME = C.TABLE_NAME
WHERE TABLE_TYPE = 'BASE TABLE'
AND COLUMN_NAME = 'ColName'
This returns tables only and ignores views for anyone who is interested!
On my machine:
C:\Program Files\PostgreSQL\8.4\data\postgresql.conf
Before I begin note that my project utilizes Carthage as a dependency manager.
None of the existing answers here resolved my issue. What did resolve the issue for me was the following.
First, I noticed that the build error pointed out one framework in particular. Next I filtered App Target > Build Phases for that framework. I noticed that that framework was present in both "Link Binary With Libraries" and "Embed Frameworks". Noting that none of the frameworks listed under "Embed Frameworks" were ones managed by Carthage I removed the framework in question from "Embed Frameworks". I then re-built my project and everything works fine including the functionality enabled by the framework in question.
Do I really have to create an NSString for "Wrong"?
No, why not just do:
if([statusString isEqualToString:@"Wrong"]){
//doSomething;
}
Using @""
simply creates a string literal, which is a valid NSString
.
Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?
Yes, you can do something like:
UILabel *label = ...;
if([someString isEqualToString:label.text]) {
// Do stuff here
}
The Keyboard Shortcut Commands are Go Forward
and Go Back
.
On Windows:
Alt+? .. navigate back
Alt+? .. navigate forward
On Mac:
Ctrl+- .. navigate back
Ctrl+Shift+- .. navigate forward
On Ubuntu Linux:
Ctrl+Alt+- .. navigate back
Ctrl+Shift+- .. navigate forward
Better to use android.R.drawable because it is public and documented.
The main difference is that sorted(some_list)
returns a new list
:
a = [3, 2, 1]
print sorted(a) # new list
print a # is not modified
and some_list.sort()
, sorts the list in place:
a = [3, 2, 1]
print a.sort() # in place
print a # it's modified
Note that since a.sort()
doesn't return anything, print a.sort()
will print None
.
Can a list original positions be retrieved after list.sort()?
No, because it modifies the original list.
In my case I needed project Y to be a WAR to be deployed through Tomcat, as well as it needed to be a JAR to be able to add it as a dependency in project X.
So in project Y's pom.xml
, I added this plugin to create a JAR along with the WAR:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<attachClasses>true</attachClasses>
<classesClassifier>classes</classesClassifier>
</configuration>
</plugin>
And while adding the dependency of project Y in project X's pom.xml
, I had to add a classifier
:
<dependency>
<groupId>groupId.of.project.Y</groupId>
<artifactId>project.Y</artifactId>
<version>1.0-SNAPSHOT</version>
<classifier>classes</classifier>
</dependency>
Note: when you build project Y, you will see 2 packagings in the target folder: project-Y.war
and project-Y-classes.jar
, so that's why while importing you are specifying the classes
classifier to import the JAR and not the WAR.
Try this,
# typically, os.path.join(os.path.dirname(__file__), 'media')
MEDIA_ROOT = '<your_path>/media'
MEDIA_URL = '/media/'
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
<img src="{{ MEDIA_URL }}<sub-dir-under-media-if-any>/<image-name.ext>" />
Beware! using Context()
will yield you an empty value for {{MEDIA_URL}}
. You must use RequestContext()
, instead.
I hope, this will help.
This snippet of code will recursively convert that data to a single type (array or object) without the nested foreach loops. Hope it helps someone!
Once an Object is in array format you can use array_merge and convert back to Object if you need to.
abstract class Util {
public static function object_to_array($d) {
if (is_object($d))
$d = get_object_vars($d);
return is_array($d) ? array_map(__METHOD__, $d) : $d;
}
public static function array_to_object($d) {
return is_array($d) ? (object) array_map(__METHOD__, $d) : $d;
}
}
Procedural way
function object_to_array($d) {
if (is_object($d))
$d = get_object_vars($d);
return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}
function array_to_object($d) {
return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}
All credit goes to: Jason Oakley
To be able to pass the select
, I just set it back to :
$('#selectID').prop('disabled',false);
or
$('#selectID').attr('disabled',false);
when passing the request.
Just for the record, in C++, if you can use either (i.e.) you don't care about the ordering of operations (you just want to increment or decrement and use it later) the prefix operator is more efficient since it doesn't have to create a temporary copy of the object. Unfortunately, most people use posfix (var++) instead of prefix (++var), just because that is what we learned initially. (I was asked about this in an interview). Not sure if this is true in C#, but I assume it would be.
The 'framePartsList.contentWindow.print();' was not working in IE 11 ver11.0.43
Therefore I have used framePartsList.contentWindow.document.execCommand('print', false, null);
It really depends what you are going for, and specifically, what kind of performance you really need to offer.
I've seen admirable solutions for strongly-typed HTML development (complete control models, be it ASP.NET Web Controls, or similar to it) that just add amazing complexity to a project. In other situations, it is perfect.
In order of preference in the C# world,
Easiest way is use this way
my_var=`echo 2`
echo $my_var
output
: 2
note that is not simple single quote is back quote ( ` ).
if you want to access table cell
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]"));
If you want to access nested table cell -
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]"+//table/tbody/tr[1]/td[2]));
For more details visit this Tutorial
I used a proxy url to solve a similar problem when I want to post data to my apache solr hosted in another server. (This may not be the perfect answer but it solves my problem.)
Follow this URL: Using Mode-Rewrite for proxying, I add this line to my httpd.conf:
RewriteRule ^solr/(.*)$ http://ip:8983/solr$1 [P]
Therefore, I can just post data to /solr instead of posting data to http://ip:8983/solr/*. Then it will be posting data in the same origin.
editText
is a part of alertDialog
layout so Just access editText
with reference of alertDialog
EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);
Update:
Because in code line dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));
inflater
is Null.
update your code like below, and try to understand the each code line
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
Update 2:
As you are using View object created by Inflater to update UI components else you can directly use setView(int layourResId)
method of AlertDialog.Builder
class, which is available from API 21 and onwards.
After debugging and spending a lot of time, in my case, the issue was with the access_key_id and secret_access_key, just double check your credentials or generate new one if possible and make sure you are passing the credentials in params.
You may run into such problem while dealing with scraped data stored as Pandas DataFrame.
This solution works like charm if the list of values is present as text.
def textToList(hashtags):
return hashtags.strip('[]').replace('\'', '').replace(' ', '').split(',')
hashtags = "[ 'A','B','C' , ' D']"
hashtags = textToList(hashtags)
Output: ['A', 'B', 'C', 'D']
No external library required.
Basically, in tensorflow when you create a tensor of any sort they are created and stored inside which can be accessed only when you run a tensorflow session. Say you have created a constant tensor
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Without running a session, you can get
- op
: An Operation. Operation that computes this tensor.
- value_index
: An int. Index of the operation's endpoint that produces this tensor.
- dtype
: A DType. Type of elements stored in this tensor.
To get the values you can run a session with the tensor you require as:
with tf.Session() as sess:
print(sess.run(c))
sess.close()
The output will be something like this:
array([[1., 2., 3.], [4., 5., 6.]], dtype=float32)
Just in case if you can use yarn
which is recommended for React apps,
you can do,
yarn add [email protected] // this is to add bootstrap with a specific version
This will add the bootstrap as a dependency to your package.json
as well.
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"bootstrap": "4.1.1", // it will add an entry here
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-scripts": "1.1.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
After that just import bootstrap
in your index.js
file.
import 'bootstrap/dist/css/bootstrap.css';
You can also put the conditional expression in brackets inside the list comprehension:
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
print [[x+5,x+1][x >= 45] for x in l]
[false,true][condition] is the syntax
The subquery option has already been answered, but note that in many cases a LEFT JOIN
can be a faster way to do this:
SELECT table1.*
FROM table1 LEFT JOIN table2 ON table2.principal=table1.principal
WHERE table2.principal IS NULL
If you want to check multiple tables to make sure it's not present in any of the tables (like in SRKR's comment), you can use this:
SELECT table1.*
FROM table1
LEFT JOIN table2 ON table2.name=table1.name
LEFT JOIN table3 ON table3.name=table1.name
WHERE table2.name IS NULL AND table3.name IS NULL
def valid = pointAddress.findAll { a ->
validPointTypes.any { a.contains(it) }
}
Should do it
If none of this did not help, then try to swap ^ in "^version" to ~ "~version".
svn checkout --force svn://repo website.dir
then
svn revert -R website.dir
Will check out on top of existing files in website.dir, but not overwrite them. Then the revert will overwrite them. This way you do not need to take the site down to complete it.
If you want to find a specific user's home directory, I don't believe you can do it directly.
When I've needed to do this before from Java I had to write some JNI native code that wrapped the UNIX getpwXXX()
family of calls.
You're a little confused about how objects work in JavaScript. The object's reference is the value of the variable. There is no unserialized value. When you create an object, its structure is stored in memory and the variable it was assigned to holds a reference to that structure.
Even if what you're asking was provided in some sort of easy, native language construct it would still technically be cloning.
JavaScript is really just pass-by-value... it's just that the value passed might be a reference to something.
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
I have been working on this for some time now. Tough to get right, and I don't claim I do, but I'm happy with it so far. My code and several demos can be found at
Its use is very similar to the TouchInterceptor (on which the code is based), although significant implementation changes have been made.
DragSortListView has smooth and predictable scrolling while dragging and shuffling items. Item shuffles are much more consistent with the position of the dragging/floating item. Heterogeneous-height list items are supported. Drag-scrolling is customizable (I demonstrate rapid drag scrolling through a long list---not that an application comes to mind). Headers/Footers are respected. etc.?? Take a look.
If you don't want to use pickle, you can store the list as text and then evaluate it:
data = [0,1,2,3,4,5]
with open("test.txt", "w") as file:
file.write(str(data))
with open("test.txt", "r") as file:
data2 = eval(file.readline())
# Let's see if data and types are same.
print(data, type(data), type(data[0]))
print(data2, type(data2), type(data2[0]))
[0, 1, 2, 3, 4, 5] class 'list' class 'int'
[0, 1, 2, 3, 4, 5] class 'list' class 'int'
The urls are different.
http://localhost/AccountSvc/DataInquiry.asmx
vs.
/acctinqsvc/portfolioinquiry.asmx
Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.
You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx
, and specify the desired method/operation in the SOAPAction header.
The SOAPAction header values are different.
http://localhost/AccountSvc/DataInquiry.asmx/ + methodName
vs.
http://tempuri.org/GetMyName
You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl
There should be a <soap:operation>
tag underneath the <wsdl:operation>
tag that matches the operation you are attempting to execute, which appears to be GetMyName
.
There is no XML declaration in the request body that includes your SOAP XML.
You specify text/xml
in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii
, but there's no telling if you aren't specifying them!
The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8
Hope that helps!
At the risk of sowing more confusion, I had this issue when updating to XC8.
None of these suggestions, nor from any other thread, solved it. What DID work, was removing EVERYTHING from the "Link Binary with Libraries" build phase, the "Target Dependencies" build phase, and the "Linked Frameworks and Libraries" General setting.
FYI, I'm using Carthage and had added $(PROJECT_DIR)/Carthage/Build/tvOS
to the FRAMEWORK_SEARCH_PATHS
build setting, so that my frameworks could be found.
FYI 2, this projects and the frameworks, are 100% swift and the frameworks are building DEFINES_MODULE = YES
.
For those how are interested, here are some times for the suggested solutions...
Rounding
Java Formatter: Elapsed Time: 105
Scala Formatter: Elapsed Time: 167
BigDecimal Formatter: Elapsed Time: 27
Truncation
Scala custom Formatter: Elapsed Time: 3
Truncation is the fastest, followed by BigDecimal. Keep in mind these test were done running norma scala execution, not using any benchmarking tools.
object TestFormatters {
val r = scala.util.Random
def textFormatter(x: Double) = new java.text.DecimalFormat("0.##").format(x)
def scalaFormatter(x: Double) = "$pi%1.2f".format(x)
def bigDecimalFormatter(x: Double) = BigDecimal(x).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble
def scalaCustom(x: Double) = {
val roundBy = 2
val w = math.pow(10, roundBy)
(x * w).toLong.toDouble / w
}
def timed(f: => Unit) = {
val start = System.currentTimeMillis()
f
val end = System.currentTimeMillis()
println("Elapsed Time: " + (end - start))
}
def main(args: Array[String]): Unit = {
print("Java Formatter: ")
val iters = 10000
timed {
(0 until iters) foreach { _ =>
textFormatter(r.nextDouble())
}
}
print("Scala Formatter: ")
timed {
(0 until iters) foreach { _ =>
scalaFormatter(r.nextDouble())
}
}
print("BigDecimal Formatter: ")
timed {
(0 until iters) foreach { _ =>
bigDecimalFormatter(r.nextDouble())
}
}
print("Scala custom Formatter (truncation): ")
timed {
(0 until iters) foreach { _ =>
scalaCustom(r.nextDouble())
}
}
}
}
Using width/height on inline elements is not always a good idea.
You can use display: inline-block
instead
Here you can find a nice tutorial for calling a NuSOAP-based web-service from a .NET client application. But IMO, you should also consider the WSO2 Web Services Framework for PHP (WSO2 WSF/PHP) for servicing. See WSO2 Web Services Framework for PHP 2.0 Significantly Enhances Industry’s Only PHP Library for Creating Both SOAP and REST Services. There is also a webminar about it.
Now, in .NET world I also encourage the use of WCF, taking into account the interoperability issues. An interoperability example can be found here, but this example uses a PHP-client + WCF-service instead of the opposite. Feel free to implement the PHP-service & WFC-client.
There are some WCF's related open source projects on codeplex.com that I found very productive. These projects are very useful to design & implement Win Forms and Windows Presentation Foundation applications: Smart Client, Web Client and Mobile Client. They can be used in combination with WCF to wisely call any kind of Web services.
Generally speaking, the patterns & practices team summarize good practices & designs in various open source projects that dealing with the .NET platform, specially for the web. So I think it's a good starting point for any design decision related to .NET clients.
url-pattern
is used in web.xml
to map your servlet
to specific URL. Please see below xml code, similar code you may find in your web.xml
configuration file.
<servlet>
<servlet-name>AddPhotoServlet</servlet-name> //servlet name
<servlet-class>upload.AddPhotoServlet</servlet-class> //servlet class
</servlet>
<servlet-mapping>
<servlet-name>AddPhotoServlet</servlet-name> //servlet name
<url-pattern>/AddPhotoServlet</url-pattern> //how it should appear
</servlet-mapping>
If you change url-pattern
of AddPhotoServlet
from /AddPhotoServlet
to /MyUrl
. Then, AddPhotoServlet
servlet can be accessible by using /MyUrl
. Good for the security reason, where you want to hide your actual page URL.
Java Servlet url-pattern
Specification:
- A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
- A string beginning with a '*.' prefix is used as an extension mapping.
- A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
- All other strings are used for exact matches only.
Reference : Java Servlet Specification
You may also read this Basics of Java Servlet
Important: Unless you have a very particular use-case, do not encrypt passwords, use a password hashing algorithm instead. When someone says they encrypt their passwords in a server-side application, they're either uninformed or they're describing a dangerous system design. Safely storing passwords is a totally separate problem from encryption.
Be informed. Design safe systems.
If you're using PHP 5.4 or newer and don't want to write a cryptography module yourself, I recommend using an existing library that provides authenticated encryption. The library I linked relies only on what PHP provides and is under periodic review by a handful of security researchers. (Myself included.)
If your portability goals do not prevent requiring PECL extensions, libsodium is highly recommended over anything you or I can write in PHP.
Update (2016-06-12): You can now use sodium_compat and use the same crypto libsodium offers without installing PECL extensions.
If you want to try your hand at cryptography engineering, read on.
First, you should take the time to learn the dangers of unauthenticated encryption and the Cryptographic Doom Principle.
Encryption in PHP is actually simple (we're going to use openssl_encrypt()
and openssl_decrypt()
once you have made some decisions about how to encrypt your information. Consult openssl_get_cipher_methods()
for a list of the methods supported on your system. The best choice is AES in CTR mode:
aes-128-ctr
aes-192-ctr
aes-256-ctr
There is currently no reason to believe that the AES key size is a significant issue to worry about (bigger is probably not better, due to bad key-scheduling in the 256-bit mode).
Note: We are not using mcrypt
because it is abandonware and has unpatched bugs that might be security-affecting. Because of these reasons, I encourage other PHP developers to avoid it as well.
class UnsafeCrypto
{
const METHOD = 'aes-256-ctr';
/**
* Encrypts (but does not authenticate) a message
*
* @param string $message - plaintext message
* @param string $key - encryption key (raw binary expected)
* @param boolean $encode - set to TRUE to return a base64-encoded
* @return string (raw binary)
*/
public static function encrypt($message, $key, $encode = false)
{
$nonceSize = openssl_cipher_iv_length(self::METHOD);
$nonce = openssl_random_pseudo_bytes($nonceSize);
$ciphertext = openssl_encrypt(
$message,
self::METHOD,
$key,
OPENSSL_RAW_DATA,
$nonce
);
// Now let's pack the IV and the ciphertext together
// Naively, we can just concatenate
if ($encode) {
return base64_encode($nonce.$ciphertext);
}
return $nonce.$ciphertext;
}
/**
* Decrypts (but does not verify) a message
*
* @param string $message - ciphertext message
* @param string $key - encryption key (raw binary expected)
* @param boolean $encoded - are we expecting an encoded string?
* @return string
*/
public static function decrypt($message, $key, $encoded = false)
{
if ($encoded) {
$message = base64_decode($message, true);
if ($message === false) {
throw new Exception('Encryption failure');
}
}
$nonceSize = openssl_cipher_iv_length(self::METHOD);
$nonce = mb_substr($message, 0, $nonceSize, '8bit');
$ciphertext = mb_substr($message, $nonceSize, null, '8bit');
$plaintext = openssl_decrypt(
$ciphertext,
self::METHOD,
$key,
OPENSSL_RAW_DATA,
$nonce
);
return $plaintext;
}
}
$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
$encrypted = UnsafeCrypto::encrypt($message, $key);
$decrypted = UnsafeCrypto::decrypt($encrypted, $key);
var_dump($encrypted, $decrypted);
Demo: https://3v4l.org/jl7qR
The above simple crypto library still is not safe to use. We need to authenticate ciphertexts and verify them before we decrypt.
Note: By default, UnsafeCrypto::encrypt()
will return a raw binary string. Call it like this if you need to store it in a binary-safe format (base64-encoded):
$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
$encrypted = UnsafeCrypto::encrypt($message, $key, true);
$decrypted = UnsafeCrypto::decrypt($encrypted, $key, true);
var_dump($encrypted, $decrypted);
Demo: http://3v4l.org/f5K93
class SaferCrypto extends UnsafeCrypto
{
const HASH_ALGO = 'sha256';
/**
* Encrypts then MACs a message
*
* @param string $message - plaintext message
* @param string $key - encryption key (raw binary expected)
* @param boolean $encode - set to TRUE to return a base64-encoded string
* @return string (raw binary)
*/
public static function encrypt($message, $key, $encode = false)
{
list($encKey, $authKey) = self::splitKeys($key);
// Pass to UnsafeCrypto::encrypt
$ciphertext = parent::encrypt($message, $encKey);
// Calculate a MAC of the IV and ciphertext
$mac = hash_hmac(self::HASH_ALGO, $ciphertext, $authKey, true);
if ($encode) {
return base64_encode($mac.$ciphertext);
}
// Prepend MAC to the ciphertext and return to caller
return $mac.$ciphertext;
}
/**
* Decrypts a message (after verifying integrity)
*
* @param string $message - ciphertext message
* @param string $key - encryption key (raw binary expected)
* @param boolean $encoded - are we expecting an encoded string?
* @return string (raw binary)
*/
public static function decrypt($message, $key, $encoded = false)
{
list($encKey, $authKey) = self::splitKeys($key);
if ($encoded) {
$message = base64_decode($message, true);
if ($message === false) {
throw new Exception('Encryption failure');
}
}
// Hash Size -- in case HASH_ALGO is changed
$hs = mb_strlen(hash(self::HASH_ALGO, '', true), '8bit');
$mac = mb_substr($message, 0, $hs, '8bit');
$ciphertext = mb_substr($message, $hs, null, '8bit');
$calculated = hash_hmac(
self::HASH_ALGO,
$ciphertext,
$authKey,
true
);
if (!self::hashEquals($mac, $calculated)) {
throw new Exception('Encryption failure');
}
// Pass to UnsafeCrypto::decrypt
$plaintext = parent::decrypt($ciphertext, $encKey);
return $plaintext;
}
/**
* Splits a key into two separate keys; one for encryption
* and the other for authenticaiton
*
* @param string $masterKey (raw binary)
* @return array (two raw binary strings)
*/
protected static function splitKeys($masterKey)
{
// You really want to implement HKDF here instead!
return [
hash_hmac(self::HASH_ALGO, 'ENCRYPTION', $masterKey, true),
hash_hmac(self::HASH_ALGO, 'AUTHENTICATION', $masterKey, true)
];
}
/**
* Compare two strings without leaking timing information
*
* @param string $a
* @param string $b
* @ref https://paragonie.com/b/WS1DLx6BnpsdaVQW
* @return boolean
*/
protected static function hashEquals($a, $b)
{
if (function_exists('hash_equals')) {
return hash_equals($a, $b);
}
$nonce = openssl_random_pseudo_bytes(32);
return hash_hmac(self::HASH_ALGO, $a, $nonce) === hash_hmac(self::HASH_ALGO, $b, $nonce);
}
}
$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
$encrypted = SaferCrypto::encrypt($message, $key);
$decrypted = SaferCrypto::decrypt($encrypted, $key);
var_dump($encrypted, $decrypted);
Demos: raw binary, base64-encoded
If anyone wishes to use this SaferCrypto
library in a production environment, or your own implementation of the same concepts, I strongly recommend reaching out to your resident cryptographers for a second opinion before you do. They'll be able tell you about mistakes that I might not even be aware of.
You will be much better off using a reputable cryptography library.
In my case it works with a little change. Simply by putting :$PATH at the end.
# andorid paths
export ANDROID_HOME=$HOME/Android/Sdk
export PATH="$ANDROID_HOME/tools:$PATH"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
export PATH="$ANDROID_HOME/emulator:$PATH"
In addition to what's been said already:
optimistic
locking tends to improve concurrency at the expense of predictability.Pessimistic
locking tends to reduce concurrency, but is more predictable. You pay your money, etc ...Moving to local folder is the quickest solution, nothing else worked for me esp because I was not admin on my system (can't edit registery etc), which is a typical case in a work environment.
Create a folder in C:\help drive, lets call it help and copy the files there and open.
Do not copy to mydocuments or anywhere else, those locations are usually on network drive in office setup and will not work.
Removes all whitespace characters such as tabs and line breaks (C++11):
string str = " \n AB cd \t efg\v\n";
str = regex_replace(str,regex("\\s"),"");
(Note: this method doesn't play nice with difference locales, but is slightly faster than a NSNumberFormatter
)
NSNumber *num1 = @([@"42" intValue]);
NSNumber *num2 = @([@"42.42" floatValue]);
Simple but dirty way
// Swift 1.2
if let intValue = "42".toInt() {
let number1 = NSNumber(integer:intValue)
}
// Swift 2.0
let number2 = Int("42')
// Swift 3.0
NSDecimalNumber(string: "42.42")
// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)
The extension-way This is better, really, because it'll play nicely with locales and decimals.
extension String {
var numberValue:NSNumber? {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
return formatter.number(from: self)
}
}
Now you can simply do:
let someFloat = "42.42".numberValue
let someInt = "42".numberValue
You can use the pseudo-selector :checkbox
with a call to jQuery's is
function:
$('#myinput').is(':checkbox')
If you really just have lock-step iteration over a range, you can do it one of several ways:
for i in range(x):
j = i
…
# or
for i, j in enumerate(range(x)):
…
# or
for i, j in ((i,i) for i in range(x)):
…
All of the above are equivalent to for i, j in zip(range(x), range(y))
if x <= y
.
If you want a nested loop and you only have two iterables, just use a nested loop:
for i in range(x):
for i in range(y):
…
If you have more than two iterables, use itertools.product
.
Finally, if you want lock-step iteration up to x
and then to continue to y
, you have to decide what the rest of the x
values should be.
for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')):
…
# or
for i in range(min(x,y)):
j = i
…
for i in range(min(x,y), max(x,y)):
j = float('nan')
…
you can use my script. paste code lines to notepad and save as vbs(for example switch_hypervisor.vbs)
Option Explicit
Dim backupfile
Dim record
Dim myshell
Dim appmyshell
Dim myresult
Dim myline
Dim makeactive
Dim makepassive
Dim reboot
record=""
Set myshell = WScript.CreateObject("WScript.Shell")
If WScript.Arguments.Length = 0 Then
Set appmyshell = CreateObject("Shell.Application")
appmyshell.ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ RunAsAdministrator", , "runas", 1
WScript.Quit
End if
Set backupfile = CreateObject("Scripting.FileSystemObject")
If Not (backupfile.FileExists("C:\bcdedit.bak")) Then
Set myresult = myshell.Exec("cmd /c bcdedit /export c:\bcdedit.bak")
End If
Set myresult = myshell.Exec("cmd /c bcdedit")
Do While Not myresult.StdOut.AtEndOfStream
myline = myresult.StdOut.ReadLine()
If myline="The boot configuration data store could not be opened." Then
record=""
exit do
End If
If Instr(myline, "identifier") > 0 Then
record=""
If Instr(myline, "{current}") > 0 Then
record="current"
End If
End If
If Instr(myline, "hypervisorlaunchtype") > 0 And record = "current" Then
If Instr(myline, "Auto") > 0 Then
record="1"
Exit Do
End If
If Instr(myline, "On") > 0 Then
record="1"
Exit Do
End If
If Instr(myline, "Off") > 0 Then
record="0"
Exit Do
End If
End If
Loop
If record="1" Then
makepassive = MsgBox ("Hypervisor status is active, do you want set to passive? ", vbYesNo, "Hypervisor")
Select Case makepassive
Case vbYes
myshell.run "cmd.exe /C bcdedit /set hypervisorlaunchtype off"
reboot = MsgBox ("Hypervisor chenged to passive; Computer must reboot. Reboot now? ", vbYesNo, "Hypervisor")
Select Case reboot
Case vbYes
myshell.run "cmd.exe /C shutdown /r /t 0"
End Select
Case vbNo
MsgBox("Not Changed")
End Select
End If
If record="0" Then
makeactive = MsgBox ("Hypervisor status is passive, do you want set active? ", vbYesNo, "Hypervisor")
Select Case makeactive
Case vbYes
myshell.run "cmd.exe /C bcdedit /set hypervisorlaunchtype auto"
reboot = MsgBox ("Hypervisor changed to active; Computer must reboot. Reboot now?", vbYesNo, "Hypervisor")
Select Case reboot
Case vbYes
myshell.run "cmd.exe /C shutdown /r /t 0"
End Select
Case vbNo
MsgBox("Not Changed")
End Select
End If
If record="" Then
MsgBox("Error: record can't find")
End If
You can use
$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);
or define auto-size:
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
I have the problem anyway with -lm added
gcc -Wall -lm mtest.c -o mtest.o
mtest.c: In function 'f1':
mtest.c:6:12: warning: unused variable 'res' [-Wunused-variable]
/tmp/cc925Nmf.o: In function `f1':
mtest.c:(.text+0x19): undefined reference to `sin'
collect2: ld returned 1 exit status
I discovered recently that it does not work if you first specify -lm. The order matters:
gcc mtest.c -o mtest.o -lm
Just link without problems
So you must specify the libraries after.
In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:
var ListView = React.createClass({
render: function() {
var items = this.props.data.map(function(item) {
return this.props.delegate({data:item});
}.bind(this));
return <ul>{items}</ul>;
}
});
var ItemDelegate = React.createClass({
render: function() {
return <li>{this.props.data}</li>
}
});
var Wrapper = React.createClass({
render: function() {
return <ListView delegate={ItemDelegate} data={someListOfData} />
}
});
SetTimeout is used to make your set of code to execute after a specified time period so for your requirements its better to use setInterval because that will call your function every time at a specified time interval.
return results == null ? 0 : (results[1] || 0);
decimal d = // your number..
decimal t = d - Math.Floor(d);
if(t >= 0.3d && t <= 0.7d)
{
return Math.Floor(d) + 0.5d;
}
else if(t>0.7d)
return Math.Ceil(d);
return Math.Floor(d);
with many functions in matlab, you don't need to iterate at all.
for example, to multiply by it's position in the list:
m = [1:numel(list)]';
elm = list.*m;
vectorized algorithms in matlab are in general much faster.
In your storyboard go to the Attributes inspector and set the view controller's Identifier. You can then present that view controller using the following code.
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"myViewController"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];
Single bash line:
sed -n $((1+$RANDOM%`wc -l test.txt | cut -f 1 -d ' '`))p test.txt
Slight problem: duplicate filename.
Here's how to use a Jet OLEDB or Ace OLEDB Access DB:
using System.Data;
using System.Data.OleDb;
string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\myPath\myFile.mdb;" +
"Persist Security Info=True;" +
"Jet OLEDB:Database Password=myPassword;";
try
{
// Open OleDb Connection
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
// Execute Queries
OleDbCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM `myTable`";
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete
// Load the result into a DataTable
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
}
catch (Exception ex)
{
Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}
To run another Python environment according to the official Virtualenv documentation, in the command line you can specify the full path to the executable Python binary, just that (no need to active the virtualenv before):
/path/to/virtualenv/bin/python
The same applies if you want to invoke a script from the command line with your virtualenv. You don't need to activate it before:
me$ /path/to/virtualenv/bin/python myscript.py
The same for a Windows environment (whether it is from the command line or from a script):
> \path\to\env\Scripts\python.exe myscript.py
I would recommend checking out Gabor Grothendieck's sqldf package, which allows you to express these operations in SQL.
library(sqldf)
## inner join
df3 <- sqldf("SELECT CustomerId, Product, State
FROM df1
JOIN df2 USING(CustomerID)")
## left join (substitute 'right' for right join)
df4 <- sqldf("SELECT CustomerId, Product, State
FROM df1
LEFT JOIN df2 USING(CustomerID)")
I find the SQL syntax to be simpler and more natural than its R equivalent (but this may just reflect my RDBMS bias).
See Gabor's sqldf GitHub for more information on joins.
const promise = new Promise(resolve => {
setTimeout(() => {
resolve("Hello from a Promise!");
}, 2000);
});
promise.then(value => console.log(value));
Observable example now. Here also we pass a function to observable, an observer to handle the async task. Unlike resolve in the promise it has the following method and subscribes in place of then.
So both handles async tasks. Now let's see the difference.
const observable = new Observable(observer => {
setTimeout(() => {
observer.next('Hello from a Observable!');
}, 2000);
});
observable.subscribe(value => console.log(value));
Promise
Observable
other method
INSERT INTO tableName (col1, col2, col3, col4, col5)
select * from table(
values
(val1, val2, val3, val4, val5),
(val1, val2, val3, val4, val5),
(val1, val2, val3, val4, val5),
(val1, val2, val3, val4, val5)
) tmp
You have to set "secondary okay" mode to let the mongo shell know that you're allowing reads from a secondary. This is to protect you and your applications from performing eventually consistent reads by accident. You can do this in the shell with:
rs.secondaryOk()
After that you can query normally from secondaries.
A note about "eventual consistency": under normal circumstances, replica set secondaries have all the same data as primaries within a second or less. Under very high load, data that you've written to the primary may take a while to replicate to the secondaries. This is known as "replica lag", and reading from a lagging secondary is known as an "eventually consistent" read, because, while the newly written data will show up at some point (barring network failures, etc), it may not be immediately available.
Edit: You only need to set secondaryOk
when querying from secondaries, and only once per session.
Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!
function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if (node == null)
node = document;
if (tag == null)
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
This can be achieved in .htaccess
provided your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named *
and specifying a folder called subdomains as the document root for wildcard subdomains. Add this to your .htaccess
file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]
Finally, create a folder for your subdomain and place the subdomains files.
It seems, that the simple way
-Dmaven.javadoc.skip=true
does not work with the release-plugin. in this case you have to pass the parameter as an "argument"
mvn release:perform -Darguments="-Dmaven.javadoc.skip=true"
Use the time package to work with time information in Go.
Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.
Play example:
package main
import (
"fmt"
"time"
)
func inTimeSpan(start, end, check time.Time) bool {
return check.After(start) && check.Before(end)
}
func main() {
start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")
in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")
if inTimeSpan(start, end, in) {
fmt.Println(in, "is between", start, "and", end, ".")
}
if !inTimeSpan(start, end, out) {
fmt.Println(out, "is not between", start, "and", end, ".")
}
}
5 step to do what you want if you made the pull request from a forked repository:
And everything is done, good luck!
For the sake of future 'newbies' tackling this problem, I think a quick answer would be fitting to this thread.
Like bgporter said: Python strings are immutable, and so, in order to modify a string you have to make use of the pieces you already have.
In the following example I insert 'Fu'
in to 'Kong Panda'
, to create 'Kong Fu Panda'
>>> line = 'Kong Panda'
>>> index = line.find('Panda')
>>> output_line = line[:index] + 'Fu ' + line[index:]
>>> output_line
'Kong Fu Panda'
In the example above, I used the index value to 'slice' the string in to 2 substrings: 1 containing the substring before the insertion index, and the other containing the rest. Then I simply add the desired string between the two and voilà, we have inserted a string inside another.
Python's slice notation has a great answer explaining the subject of string slicing.
Do you mean something like this:
HTML
<div class="row">
<div class="container">
<div class="col-md-4">
left content
</div>
<div class="col-md-4 col-md-offset-4">
<div class="yellow-background">
text
<div class="pull-right">right content</div>
</div>
</div>
</div>
</div>
CSS
.yellow-background {
background: blue;
}
.pull-right {
background: yellow;
}
A full example can be found on Codepen.
In Swift you would do it like this:
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0
(Note that the way the lineBreakMode constant works is different to in ObjC)
Here is a starting point for developing Android apps with HTML5. The HTML code will be stored in the "assets/www" folder in your Android project.
In Python 3, print
became a function. This means that you need to include parenthesis now like mentioned below:
print("Hello World")
In your HTML it is a good pratice to provide the encoding like using the following meta like this for example:
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
But your warning that you see may be trigged by one of multiple files. it might not be your HTML document. It might be something in a javascript file or css file. if you page is made of up multiples php files included together it may be only 1 of those files.
I dont think this error has anything to do with mootools. you see this message in your firefox console window. not mootools script.
maybe you simply need to re-save your html pages using a code editor that lets you specify the correct character encoding.
How about:
table {_x000D_
table-layout: fixed; _x000D_
width: 100%;_x000D_
*margin-left: -100px; /*ie7*/_x000D_
}_x000D_
td, th {_x000D_
vertical-align: top;_x000D_
border-top: 1px solid #ccc;_x000D_
padding: 10px;_x000D_
width: 100px;_x000D_
}_x000D_
.fix {_x000D_
position: absolute;_x000D_
*position: relative; /*ie7*/_x000D_
margin-left: -100px;_x000D_
width: 100px;_x000D_
}_x000D_
.outer {_x000D_
position: relative;_x000D_
}_x000D_
.inner {_x000D_
overflow-x: scroll;_x000D_
overflow-y: visible;_x000D_
width: 400px; _x000D_
margin-left: 100px;_x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="inner">_x000D_
<table>_x000D_
<tr>_x000D_
<th class=fix></th>_x000D_
<th>Col 1</th>_x000D_
<th>Col 2</th>_x000D_
<th>Col 3</th>_x000D_
<th>Col 4</th>_x000D_
<th class="fix">Col 5</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class=fix>Header A</th>_x000D_
<td>col 1 - A</td>_x000D_
<td>col 2 - A (WITH LONGER CONTENT)</td>_x000D_
<td>col 3 - A</td>_x000D_
<td>col 4 - A</td>_x000D_
<td class=fix>col 5 - A</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class=fix>Header B</th>_x000D_
<td>col 1 - B</td>_x000D_
<td>col 2 - B</td>_x000D_
<td>col 3 - B</td>_x000D_
<td>col 4 - B</td>_x000D_
<td class=fix>col 5 - B</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class=fix>Header C</th>_x000D_
<td>col 1 - C</td>_x000D_
<td>col 2 - C</td>_x000D_
<td>col 3 - C</td>_x000D_
<td>col 4 - C</td>_x000D_
<td class=fix>col 5 - C</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
You can test it out in this jsbin: http://jsbin.com/uxecel/4/edit
You should take care with readLines(...)
and big files. Reading all lines at memory can be risky. Below is a example of how to read file and process just one line at time:
processFile = function(filepath) {
con = file(filepath, "r")
while ( TRUE ) {
line = readLines(con, n = 1)
if ( length(line) == 0 ) {
break
}
print(line)
}
close(con)
}
Understand the risk of reading a line at memory too. Big files without line breaks can fill your memory too.
No, there is no option in crontab to modify the cron files.
You have to: take the current cron file (crontab -l > newfile), change it and put the new file in place (crontab newfile).
If you are familiar with perl, you can use this module Config::Crontab.
LLP, Andrea
The "usual" solution is make a function that return an empty formGroup or a fullfilled formGroup
createFormGroup(data:any)
{
return this.fb.group({
user: [data?data.user:null],
questioning: [data?data.questioning:null, Validators.required],
questionType: [data?data.questionType, Validators.required],
options: new FormArray([this.createArray(data?data.options:null])
})
}
//return an array of formGroup
createArray(data:any[]|null):FormGroup[]
{
return data.map(x=>this.fb.group({
....
})
}
then, in SUBSCRIBE, you call the function
this.qService.editQue([params["id"]]).subscribe(res => {
this.editqueForm = this.createFormGroup(res);
});
be carefull!, your form must include an *ngIf to avoid initial error
<form *ngIf="editqueForm" [formGroup]="editqueForm">
....
</form>
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
This was an interesting solution for the safe navigation operator using some mixin..
http://jsfiddle.net/avernet/npcmv/
// Assume you have the following data structure
var companies = {
orbeon: {
cfo: "Erik",
cto: "Alex"
}
};
// Extend Underscore.js
_.mixin({
// Safe navigation
attr: function(obj, name) { return obj == null ? obj : obj[name]; },
// So we can chain console.log
log: function(obj) { console.log(obj); }
});
// Shortcut, 'cause I'm lazy
var C = _(companies).chain();
// Simple case: returns Erik
C.attr("orbeon").attr("cfo").log();
// Simple case too, no CEO in Orbeon, returns undefined
C.attr("orbeon").attr("ceo").log();
// IBM unknown, but doesn't lead to an error, returns undefined
C.attr("ibm").attr("ceo").log();