Here is a simple class that handles both raw
and asset
files :
public class ReadFromFile {
public static String raw(Context context, @RawRes int id) {
InputStream is = context.getResources().openRawResource(id);
int size = 0;
try {
size = is.available();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return readFile(size, is);
}
public static String asset(Context context, String fileName) {
InputStream is = null;
int size = 0;
try {
is = context.getAssets().open(fileName);
AssetFileDescriptor fd = null;
fd = context.getAssets().openFd(fileName);
size = (int) fd.getLength();
fd.close();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return readFile(size, is);
}
private static String readFile(int size, InputStream is) {
try {
byte buffer[] = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
For example :
ReadFromFile.raw(context, R.raw.textfile);
And for asset files :
ReadFromFile.asset(context, "file.txt");
A jar file is just a zip file with a structured manifest. You can open the jar file with the usual java zip tools and scan the file contents that way, inflate streams, etc. Then use that in a getResourceAsStream call, and it should be all hunky dory.
EDIT / after clarification
It took me a minute to remember all the bits and pieces and I'm sure there are cleaner ways to do it, but I wanted to see that I wasn't crazy. In my project image.jpg is a file in some part of the main jar file. I get the class loader of the main class (SomeClass is the entry point) and use it to discover the image.jpg resource. Then some stream magic to get it into this ImageInputStream thing and everything is fine.
InputStream inputStream = SomeClass.class.getClassLoader().getResourceAsStream("image.jpg");
JPEGImageReaderSpi imageReaderSpi = new JPEGImageReaderSpi();
ImageReader ir = imageReaderSpi.createReaderInstance();
ImageInputStream iis = new MemoryCacheImageInputStream(inputStream);
ir.setInput(iis);
....
ir.read(0); //will hand us a buffered image
If you are using Kotlin + Retrofit + Coroutines then just use try
and catch
for network operations like,
viewModelScope.launch(Dispatchers.IO) {
try {
val userListResponseModel = apiEndPointsInterface.usersList()
returnusersList(userListResponseModel)
} catch (e: Exception) {
e.printStackTrace()
}
}
Where, Exception is type of kotlin
and not of java.lang
This will handle every exception like,
Here is my usersList()
function
@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel
Note:
Your RetrofitClient Classs must have this as client
OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
File f = new File("C:/aaa/bbb/ccc/ddd/test.java");
System.out.println(f.getParentFile().getName())
f.getParentFile()
can be null, so you should check it.
Trying to make this as short and simple as possible. Creates directory if it doesn't exist, and then returns the desired file:
/** Creates parent directories if necessary. Then returns file */
private static File fileWithDirectoryAssurance(String directory, String filename) {
File dir = new File(directory);
if (!dir.exists()) dir.mkdirs();
return new File(directory + "/" + filename);
}
Try something like this I know I am late for the answer but this obvious thing happened in java8 a new version from where this question is asked but..
The code
import java.io.File;
public class Find_this_dir {
public static void main(String[] args) {
//some sort of a bug in java path is correct but file dose not exist
File this_dir = new File("");
//but these both commands work too to get current dir
// File this_dir_2 = new File(this_dir.getAbsolutePath());
File this_dir_2 = new File(new File("").getAbsolutePath());
System.out.println("new File(" + "\"\"" + ")");
System.out.println(this_dir.getAbsolutePath());
System.out.println(this_dir.exists());
System.out.println("");
System.out.println("new File(" + "new File(" + "\"\"" + ").getAbsolutePath()" + ")");
System.out.println(this_dir_2.getAbsolutePath());
System.out.println(this_dir_2.exists());
}
}
This will work and show you the current path but I don't now why java fails to find current dir in new File("");
besides I am using Java8 compiler...
This works just fine I even tested it new File(new File("").getAbsolutePath());
Now you have current directory in a File object so (Example file object is f then),
f.getAbsolutePath()
will give you the path in a String varaible type...
Tested in another directory that is not drive C works fine
Recently I have read a Java SE 8 Programmer Guide ii Book.
I found something about the difference between AutoCloseable
vs Closeable
.
The AutoCloseable
interface was introduced in Java 7. Before that, another interface
existed called Closeable
. It was similar to what the language designers wanted, with the
following exceptions:
Closeable
restricts the type of exception thrown to IOException
.Closeable
requires implementations to be idempotent.The language designers emphasize backward compatibility. Since changing the existing
interface was undesirable, they made a new one called AutoCloseable
. This new
interface is less strict than Closeable
. Since Closeable
meets the requirements for
AutoCloseable
, it started implementing AutoCloseable
when the latter was introduced.
The listFiles
method, with or without a filter does not guarantee any order.
It does, however, return an array, which you can sort with Arrays.sort()
.
File[] files = XMLDirectory.listFiles(filter_xml_files);
Arrays.sort(files);
for(File _xml_file : files) {
...
}
This works because File
is a comparable class, which by default sorts pathnames lexicographically. If you want to sort them differently, you can define your own comparator.
If you prefer using Streams:
A more modern approach is the following. To print the names of all files in a given directory, in alphabetical order, do:
Files.list(Paths.get(dirName)).sorted().forEach(System.out::println)
Replace the System.out::println
with whatever you want to do with the file names. If you want only filenames that end with "xml"
just do:
Files.list(Paths.get(dirName))
.filter(s -> s.toString().endsWith(".xml"))
.sorted()
.forEach(System.out::println)
Again, replace the printing with whichever processing operation you would like.
You are right. Here is how write()
method of BufferedWriter
looks:
public void write(int c) throws IOException {
synchronized (lock) {
ensureOpen();
if (nextChar >= nChars)
flushBuffer();
cb[nextChar++] = (char) c;
}
}
As you can see it indeed checks whether the buffer is full (if (nextChar >= nChars)
) and flushes the buffer. Then it adds new character to buffer (cb[nextChar++] = (char) c;
).
The method newLine()
ensures a platform-compatible new line is added (0Dh 0Ah
for DOS, 0Dh
for older Macs, 0Ah
for Unix/Linux). Java has no way of knowing on which platform you are going to send the text. This conversion should be taken care of by the mail sending entities.
It's also used in regular expressions, meaning "at most one repetition of the preceding character"
for example the regular expression /hey?/
matches with the strings "he
" and "hey
".
Plain JavaScript:
You don't need jQuery to do something trivial like this. Just use the .removeAttribute()
method.
Assuming you are just targeting a single element, you can easily use the following: (example)
document.querySelector('#target').removeAttribute('style');
If you are targeting multiple elements, just loop through the selected collection of elements: (example)
var target = document.querySelectorAll('div');
Array.prototype.forEach.call(target, function(element){
element.removeAttribute('style');
});
Array.prototype.forEach()
- IE9 and above / .querySelectorAll()
- IE 8 (partial) IE9 and above.
One can rename indexes the same way:
alter index owner.index_name rename to new_name;
Since above code do not cover procedures for extracting list of sheet name for Excel 2007,following code will be applicable for both Excel(97-2003) and Excel 2007 too:
public List<string> ListSheetInExcel(string filePath)
{
OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
String strExtendedProperties = String.Empty;
sbConnection.DataSource = filePath;
if (Path.GetExtension(filePath).Equals(".xls"))//for 97-03 Excel file
{
sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
}
else if (Path.GetExtension(filePath).Equals(".xlsx")) //for 2007 Excel file
{
sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
}
sbConnection.Add("Extended Properties",strExtendedProperties);
List<string> listSheet = new List<string>();
using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
{
conn.Open();
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
{
listSheet.Add(drSheet["TABLE_NAME"].ToString());
}
}
}
return listSheet;
}
Above function returns list of sheet in particular excel file for both excel type(97,2003,2007).
>>> mylist = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head, tail = mylist[0], mylist[1:]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
This is a bit of a Unix vs Linux battle. Most if not all Linux distributions have bash installed and ksh optional. Most Unix systems, like Solaris, AIX and HPUX have ksh as default.
Personally I always use ksh, I love the vi completion and I pretty much use Solaris for everything.
And in Kotlin:
tailrec fun Context.activity(): Activity? = when {
this is Activity -> this
else -> (this as? ContextWrapper)?.baseContext?.activity()
}
You can do it also in more 'object way' and still easy-to-read:
$('#content ul').append(
$('<li>').append(
$('<a>').attr('href','/user/messages').append(
$('<span>').attr('class', 'tab').append("Message center")
)));
You don't have to fight with quotes then, but must keep trace of braces :)
You usually want to use NSInteger
when you don't know what kind of processor architecture your code might run on, so you may for some reason want the largest possible integer type, which on 32 bit systems is just an int
, while on a 64-bit system it's a long
.
I'd stick with using NSInteger
instead of int
/long
unless you specifically require them.
NSInteger
/NSUInteger
are defined as *dynamic typedef
*s to one of these types, and they are defined like this:
#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
With regard to the correct format specifier you should use for each of these types, see the String Programming Guide's section on Platform Dependencies
Close all browsers and tabs to ensure that the ActiveX control is not reside in memory. Open a fresh IE9 browser. Select Tools->Manage Add-ons. Change the drop down to "All add-ons" since the default only shows ones that are loaded.
Now select the add-on you wish to remove. There will be a link displayed on the lower left that says "More information". Click it.
This opens a further dialog that allows you to safely un-install the ActiveX control.
If you follow the direction of manually running the 'regsvr32' to remove the OCX it is not sufficient. ActiveX controls are wrapped up as signed CAB files and they extract to multiple DLLs and OCXs potentially. You wish to use IE to safely and correctly unregister every COM DLL and OCX.
There you have it! The problem is that in IE 9 it is somewhat hidden since you have to click the "More information" whereas IE8 you could do it from the same UI.
"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.
The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.
Below can be the required mapping,
<class name="com.example.CompanyEntity" table="COMPANY">
<id name="id" column="COMPANY_ID"/>
<set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
<key column="COMPANY_ID" not-null="true"/>
<one-to-many entity-name="vendorName"/>
</set>
</class>
You can use texts as a md viewer and md editor, its lightweight and neat.
This fixed version of code above remember the last element of CVS row ;-)
(tested with a CSV file with 5400 rows and 26 elements by row)
public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"') {
bool bolQuote = false;
StringBuilder bld = new StringBuilder();
List<string> retAry = new List<string>();
foreach (char c in r.ToCharArray())
if ((c == fieldSep && !bolQuote))
{
retAry.Add(bld.ToString());
bld.Clear();
}
else
if (c == stringSep)
bolQuote = !bolQuote;
else
bld.Append(c);
/* to solve the last element problem */
retAry.Add(bld.ToString()); /* added this line */
return retAry.ToArray();
}
Personally I like the navigationDrawer
in Google Drive official app. It just works and works great. I agree that the navigation drawer shouldn't move the action bar because is the key point to open and close the navigation drawer.
If you are still trying to get that behavior I recently create a project Called SherlockNavigationDrawer
and as you may expect is the implementation of the Navigation Drawer with ActionBarSherlock
and works for pre Honeycomb devices. Check it:
There are really two separate issues. The first is keeping the elements of the array in proper order so that there are no "holes" after removing an element. The second is actually resizing the array itself.
Arrays in C are allocated as a fixed number of contiguous elements. There is no way to actually remove the memory used by an individual element in the array but the elements can be shifted to fill the hole made by removing an element. For example:
void remove_element(array_type *array, int index, int array_length)
{
int i;
for(i = index; i < array_length - 1; i++) array[i] = array[i + 1];
}
Statically allocated arrays can not be resized. Dynamically allocated arrays can be resized with realloc(). This will potentially move the entire array to another location in memory, so all pointers to the array or to its elements will have to be updated. For example:
remove_element(array, index, array_length); /* First shift the elements, then reallocate */
array_type *tmp = realloc(array, (array_length - 1) * sizeof(array_type) );
if (tmp == NULL && array_length > 1) {
/* No memory available */
exit(EXIT_FAILURE);
}
array_length = array_length - 1;
array = tmp;
realloc will return a NULL pointer if the requested size is 0, or if there is an error. Otherwise it returns a pointer to the reallocated array. The temporary pointer is used to detect errors when calling realloc because instead of exiting it is also possible to just leave the original array as it was. When realloc fails to reallocate an array it does not alter the original array.
Note that both of these operations will be fairly slow if the array is large or if a lot of elements are removed. There are other data structures like linked lists and hashes that can be used if efficient insertion and deletion is a priority.
just simple replace your class with this.
.ui-page
{
background: transparent url(images/EarthIcon.jpg) no-repeat center center;
}
I have same issue and i solved it.
Here are the different ways in which you can create an array of booleans in typescript:
let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();
let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();
let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];
let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();
let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();
You can access them using the index:
console.log(arr[5]);
and you add elements using push:
arr.push(true);
When creating the array you can supply the initial values:
let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);
I'd advise against a simple regular expression approach to this problem. There are too many words that are substrings of other unrelated words, and you'll probably drive yourself crazy trying to overadapt the simpler solutions already provided.
You'll want at least a naive stemming algorithm (try the Porter stemmer; there's available, free code in most languages) to process text first. Keep this processed text and the preprocessed text in two separate space-split arrays. Make sure each non-alphabetical character also gets its own index in this array. Whatever list of words you're filtering, stem them also.
The next step would be to find the array indices which match to your list of stemmed 'stop' words. Remove those from the unprocessed array, and then rejoin on spaces.
This is only slightly more complicated, but will be much more reliable an approach. If you've got any doubts on the value of a more NLP-oriented approach, you might want to do some research into clbuttic mistakes.
check out my js lib for caching: https://github.com/hoangnd25/cacheJS
My blog post: New way to cache your data with Javascript
Saving cache:
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});
Retrieving cache:
cacheJS.get({blogId: 1,type: 'view'});
Flushing cache
cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});
cacheJS.removeByContext({author:'hoangnd'});
Switching provider
cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};
Yes I use gocr at http://jocr.sourceforge.net/ its a commandline application which you could execute from your application. I use it in a couple of my applications.
How malloc() and free() works depends on the runtime library used. Generally, malloc() allocates a heap (a block of memory) from the operating system. Each request to malloc() then allocates a small chunk of this memory be returning a pointer to the caller. The memory allocation routines will have to store some extra information about the block of memory allocated to be able to keep track of used and free memory on the heap. This information is often stored in a few bytes just before the pointer returned by malloc() and it can be a linked list of memory blocks.
By writing past the block of memory allocated by malloc() you will most likely destroy some of the book-keeping information of the next block which may be the remaining unused block of memory.
One place where you program may also crash is when copying too many characters into the buffer. If the extra characters are located outside the heap you may get an access violation as you are trying to write to non-existing memory.
we can use recursive function for find gcd
public class Test
{
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0 || b == 0)
return 0;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// Driver method
public static void main(String[] args)
{
int a = 98, b = 56;
System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
}
}
The following solution bypasses the automatic exponentional formatting for very big and very small numbers. This is outis's solution with a bugfix: It was not working for very small negative numbers.
function numberToString(num)_x000D_
{_x000D_
let numStr = String(num);_x000D_
_x000D_
if (Math.abs(num) < 1.0)_x000D_
{_x000D_
let e = parseInt(num.toString().split('e-')[1]);_x000D_
if (e)_x000D_
{_x000D_
let negative = num < 0;_x000D_
if (negative) num *= -1_x000D_
num *= Math.pow(10, e - 1);_x000D_
numStr = '0.' + (new Array(e)).join('0') + num.toString().substring(2);_x000D_
if (negative) numStr = "-" + numStr;_x000D_
}_x000D_
}_x000D_
else_x000D_
{_x000D_
let e = parseInt(num.toString().split('+')[1]);_x000D_
if (e > 20)_x000D_
{_x000D_
e -= 20;_x000D_
num /= Math.pow(10, e);_x000D_
numStr = num.toString() + (new Array(e + 1)).join('0');_x000D_
}_x000D_
}_x000D_
_x000D_
return numStr;_x000D_
}_x000D_
_x000D_
// testing ..._x000D_
console.log(numberToString(+0.0000000000000000001));_x000D_
console.log(numberToString(-0.0000000000000000001));_x000D_
console.log(numberToString(+314564649798762418795));_x000D_
console.log(numberToString(-314564649798762418795));
_x000D_
You can just specify the generic octet-stream MIME type:
public FileResult Download()
{
byte[] fileBytes = System.IO.File.ReadAllBytes(@"c:\folder\myfile.ext");
string fileName = "myfile.ext";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
For docker-compose
. In the docker-compose.yml
:
version: '3'
services:
app:
image: ...
user: ${UID:-0}
...
In .env
:
UID=1000
I hope this one might help you.
let data = [];
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
let tempData = [];
tempData= data.filter((item)=>item.Status!='Invalid')
console.log(tempData)
_x000D_
Another simpler way seems to be:
new = pd.DataFrame([old.A, old.B, old.C]).transpose()
where old.column_name
will give you a series.
Make a list of all the column-series you want to retain and pass it to the DataFrame constructor. We need to do a transpose to adjust the shape.
In [14]:pd.DataFrame([old.A, old.B, old.C]).transpose()
Out[14]:
A B C
0 4 10 100
1 5 20 50
2020 Answer
With the release of node v14.14.0
you can now do.
fs.rmSync("path/to/file", {
force: true,
});
Just subtract the two dates:
select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;
The result will be the difference in days.
More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042
Typically you model the enum itself as a class with the enum
stereotype
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
Try this code,
.tooltip-inner {
max-width:350px !important;
}
By executing the following command, it will save a jenkins-ci.org.key file in the current working directory:
curl -O http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key
Then use the following command to add the key file:
apt-key add jenkins-ci.org.key
If the system returns OK, then the key file has been successfully added.
In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.
The key here is the name
attribute of the f
object representing the opened file. You get it like that:
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> f.name
'/Users/Desktop/febROSTER2012.xls'
Does it help?
cleaned solution :
$.fn.donetyping = function(callback, delay){
delay || (delay = 1000);
var timeoutReference;
var doneTyping = function(elt){
if (!timeoutReference) return;
timeoutReference = null;
callback(elt);
};
this.each(function(){
var self = $(this);
self.on('keyup',function(){
if(timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function(){
doneTyping(self);
}, delay);
}).on('blur',function(){
doneTyping(self);
});
});
return this;
};
What about
Form1.textBox1.text = "change text";
note: 1. you have to "include" Form1 to your second form source file by using Form1;
Query to achieve your requirment
SELECT id,GROUP_CONCAT(text SEPARATOR ' ') AS text FROM table_name group by id;
Here is some code to apply binary mask on a video frame sequence acquired from a webcam. comment and uncomment the "bitwise_not(Mon_mask,Mon_mask);"line and see the effect.
bests, Ahmed.
#include "cv.h" // include it to used Main OpenCV functions.
#include "highgui.h" //include it to use GUI functions.
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
int c;
int radius=100;
CvPoint2D32f center;
//IplImage* color_img;
Mat image, image0,image1;
IplImage *tmp;
CvCapture* cv_cap = cvCaptureFromCAM(0);
while(1) {
tmp = cvQueryFrame(cv_cap); // get frame
// IplImage to Mat
Mat imgMat(tmp);
image =tmp;
center.x = tmp->width/2;
center.y = tmp->height/2;
Mat Mon_mask(image.size(), CV_8UC1, Scalar(0,0,0));
circle(Mon_mask, center, radius, Scalar(255,255,255), -1, 8, 0 ); //-1 means filled
bitwise_not(Mon_mask,Mon_mask);// commenté ou pas = RP ou DMLA
if(tmp != 0)
imshow("Glaucom", image); // show frame
c = cvWaitKey(10); // wait 10 ms or for key stroke
if(c == 27)
break; // if ESC, break and quit
}
/* clean up */
cvReleaseCapture( &cv_cap );
cvDestroyWindow("Glaucom");
}
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
I was able to get all errors via the below code:
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
Here Web Supportive Application is an example of website. Website and Web Application both can be dynamic/static its depends upon requirements, here is an example to understand working of website's and web application.
From the Java language spec:
It is a compile time error to import a type from the unnamed package.
You'll have to access the class via reflection or some other indirect method.
char originalString[] = "THESTRINGHASNOSPACES";
char aux[5];
int j=0;
for(int i=0;i<strlen(originalString);i++){
aux[j] = originalString[i];
if(j==3){
aux[j+1]='\0';
printf("%s\n",aux);
j=0;
}else{
j++;
}
}
Make a
class PassMeByRef { public int theValue; }
then pass a reference to an instance of it. Note that a method that mutates state through its arguments is best avoided, especially in parallel code.
I had the same problem. My error was the packaging. So I would suggest you first check the package name and if the class is in the correct package.
echo Off
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup"
set VALUE_NAME=release
REG QUERY %KEY_NAME% /S /v %VALUE_NAME%
endlocal
dot put \ at the end of KEY_NAME
Create a class in your CSS file:
.active {
z-index: 20;
background: rgb(23,55,94)
color: #fff;
}
Then in your jQuery
$(this).addClass("active");
edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).
As simple as:
JSON.stringify(yourData)
You should encode you data in JSON before sending it, you can't just send an object like this as POST data.
I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:
$.post(_saveDeviceUrl, {
data : $.toJSON(postData)
}, function(response){
//Process your response here
}
);
Use the code below. It works every time.
<button onclick="self.close()">Close</button>
It works every time in Chrome and also works on Firefox.
You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec
Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
I had the exact same issue. The cause could be different but in my case, after trying several different things like changing the connection string on the Data Source setup, I found that this was the infamous 'double hop' issue (more info here).
To solve the problem, the following two options are available (as per one of the responses from the hyperlink):
Change the Report Server service to run under a domain user account, and register a SPN for the account.
Map Built-in accounts HTTP SPN to a Host SPN.
Using option 1, you need to select 'Windows' credentials instead of database credentials to overcome the double hop that happens while authentication.
Second approach is object initializer in C#
Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
The first approach
var albumData = new Album("Albumius", "Artistus", 2013);
explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:
var albumData = new Album
{
Name = "Albumius",
};
Object initializer would translate into something like:
var albumData;
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;
Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.
As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.
You can create an array containing the numbers 0 to 5 and shuffle those. Then use the result as a mapping of "oldIndex -> newIndex" and apply this mapping to both your original arrays.
You can use do it like this:
import matplotlib.pyplot as plt
import pandas as pd
plt.figure()
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'],
index=['Index 1', 'Index 2'])
df2.plot(lw=2, colormap='jet', marker='.', markersize=10,
title='Video streaming dropout by category')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.show()
Obviously you have to replace the strings 'xlabel' and 'ylabel' with what you want them to be.
The strings that contain \xF0
are simply characters encoded as multiple bytes using UTF-8.
Although your collation is set to utf8_general_ci, I suspect that the character encoding of the database, table or even column may be different. They are independent settings. Try:
ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255)
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
Substitute whatever your actual data type is for VARCHAR(255)
You need to add the "global" flag to your regex:
s.replace(new RegExp("[0-9]", "g"), "X")
or, perhaps prettier, using the built-in literal regexp syntax:
.replace(/[0-9]/g, "X")
I have had this issue before, you need more than the standard 755
or 644
permission to store the $_SESSION
information. You need to be able to write to that file as that is how it remembers.
For a more cross-browser solution you could style all inputs the way you want the non-typed, text, and password then another style the overrides that style for radios, checkboxes, etc.
input { border:solid 1px red; }
input[type=radio],
input[type=checkbox],
input[type=submit],
input[type=reset],
input[type=file]
{ border:none; }
- Or -
could whatever part of your code that is generating the non-typed inputs give them a class like .no-type
or simply not output at all? Additionally this type of selection could be done with jQuery.
In Swift 4 and latter
let count = 50//For example
for i in (1...count).reversed() {
print(i)
}
function start() {_x000D_
document.getElementById("textBox1").scrollTop +=5;_x000D_
scrolldelay = setTimeout(function() {start();}, 40);_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
clearTimeout(scrolldelay);_x000D_
}_x000D_
_x000D_
function reset(){_x000D_
var loc = document.getElementById("textBox1").scrollTop;_x000D_
document.getElementById("textBox1").scrollTop -= loc;_x000D_
clearTimeout(scrolldelay);_x000D_
}_x000D_
//adjust height of paragraph in css_x000D_
//element textbox in div_x000D_
//adjust speed at scrolltop and start
_x000D_
my css
TR.gray-t {background:#949494;}
h3{
padding-top:3px;
font:bold 12px/2px Arial;
}
my html
<TR class='gray-t'>
<TD colspan='3'><h3>KAJANG</h3>
I decrease the 2nd size in font.
padding-top
is used to fix the size in IE7.
If you want to only download dependencies without doing anything else, then it's:
mvn dependency:resolve
Or to download a single dependency:
mvn dependency:get -Dartifact=groupId:artifactId:version
If you need to download from a specific repository, you can specify that with -DrepoUrl=...
One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.
But this is very hectic method
To over come this you need to create your own ActionFilterAttribute
which will do this, you just need to add this attribute in every action method.
Here is the Class which overrides ActionFilterAttribute.
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
CurrentCustomer objCurrentCustomer = new CurrentCustomer();
objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
if (objCurrentCustomer == null)
{
// check if a new session id was generated
filterContext.Result = new RedirectResult("~/Users/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
Then in action just add this attribute like so:
[SessionExpire]
public ActionResult Index()
{
return Index();
}
This will do you work.
If you want to generate random numbers in range including '0' , use the following while 'max' is the maximum number in the range.
Random rand = new Random()
random_num = rand.nextInt(max+1)
To index on any criteria, you can so something like the following:
In [1]: from numpy import *
In [2]: x = arange(125).reshape((5,5,5))
In [3]: y = indices(x.shape)
In [4]: locs = y[:,x >= 120] # put whatever you want in place of x >= 120
In [5]: pts = hsplit(locs, len(locs[0]))
In [6]: for pt in pts:
.....: print(', '.join(str(p[0]) for p in pt))
4, 4, 0
4, 4, 1
4, 4, 2
4, 4, 3
4, 4, 4
And here's a quick function to do what list.index() does, except doesn't raise an exception if it's not found. Beware -- this is probably very slow on large arrays. You can probably monkey patch this on to arrays if you'd rather use it as a method.
def ndindex(ndarray, item):
if len(ndarray.shape) == 1:
try:
return [ndarray.tolist().index(item)]
except:
pass
else:
for i, subarray in enumerate(ndarray):
try:
return [i] + ndindex(subarray, item)
except:
pass
In [1]: ndindex(x, 103)
Out[1]: [4, 0, 3]
I think this is pretty obvious :
Keep in mind : both the function has two arguments,
$observe/$watch(value : string, callback : function);
function (oldValue, newValue)
I have made a plunker, so you can actually get a grasp on both their utilization. I have used the Chameleon analogy as to make it easier to picture.
Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.
You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:
function nextImage() {
return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
}));
}
You can then call it like this:
window.location.href = nextImage();
Demo here: http://jsfiddle.net/jfriend00/3VPEq/
This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.
No fancy tricks needed:
for i in *.java; do
[ -f "$i" ] || break
...
done
The guard ensures that if there are no matching files, the loop will exit without trying to process a non-existent file name *.java
. In bash
(or shells supporting something similar), you can use the nullglob
option
to simply ignore a failed match and not enter the body of the loop.
shopt -s nullglob
for i in *.java; do
...
done
Another simple way I found for using in LAN is
ssh [username@ip] uname -n
If you need to login command line will be
sshpass -p "[password]" ssh [username@ip] uname -n
declare @OrderByCmd nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd
your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms
in my case I added such cyclic resource:
<drawable name="above_shadow">@drawable/above_shadow</drawable>
then changed to
<drawable name="some_name">@drawable/other_name</drawable>
and it worked
One hackish way to define an exit
method in context:
class Bar; def exit; end; end
This works because exit
in the initializer will be resolved as self.exit
1. In addition, this approach allows using the object after it has been created, as in: b = B.new
.
But really, one shouldn't be doing this: don't have exit
(or even puts
) there to begin with.
(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)
1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit
normally resolves to Object#exit
. However, this can be changed by introducing an overridden method as shown - nothing fancy.
When you have custom logging logic, it is rather annoying to be forced either not to log application_start or to have to let an exception occurs in the logger (even if handled).
It appears that rather than testing for Request
availability, you can test for Handler
availability: when there is no Request
, it would be strange to still have a request handler. And testing for Handler
does not raise that dreaded Request is not available in this context
exception.
So you may change your code to:
var currContext = HttpContext.Current;
if (currContext != null && currContext.Handler != null)
Beware, in the context of a http module, Handler
may not be defined though Request
and Response
are defined (I have seen that in BeginRequest event). So if you need request/response logging in a custom http module, my answer may not be suitable.
Taken from the ReactKonvaCore.d.ts file:
onClick?(evt: Konva.KonvaEventObject<MouseEvent>): void;
So, I'd say your event type is Konva.KonvaEventObject<MouseEvent>
There is one more hint that not in this conversation. for asp.net core 3.1 first add the key that you need to put it in the header, something like this:
Response.Headers.Add("your-key-to-use-it-axios", "your-value");
where you define the cors policy (normaly is in Startup.cs
) you should add this key to WithExposedHeaders like this.
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.WithExposedHeaders("your-key-to-use-it-axios"));
});
}
you can add all the keys here. now in your client side you can easily access to the your-key-to-use-it-axios by using the response result.
localStorage.setItem("your-key", response.headers["your-key-to-use-it-axios"]);
you can after use it in all the client side by accessing to it like this:
const jwt = localStorage.getItem("your-key")
I know this is old, but maybe this will help someone else.
Do not log "new" values. Your existing table, GUESTS, has the new values. You'll have double entry of data, plus your DB size will grow way too fast that way.
I cleaned this up and minimized it for this example, but here is the tables you'd need for logging off changes:
CREATE TABLE GUESTS (
GuestID INT IDENTITY(1,1) PRIMARY KEY,
GuestName VARCHAR(50),
ModifiedBy INT,
ModifiedOn DATETIME
)
CREATE TABLE GUESTS_LOG (
GuestLogID INT IDENTITY(1,1) PRIMARY KEY,
GuestID INT,
GuestName VARCHAR(50),
ModifiedBy INT,
ModifiedOn DATETIME
)
When a value changes in the GUESTS table (ex: Guest name), simply log off that entire row of data, as-is, to your Log/Audit table using the Trigger. Your GUESTS table has current data, the Log/Audit table has the old data.
Then use a select statement to get data from both tables:
SELECT 0 AS 'GuestLogID', GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS] WHERE GuestID = 1
UNION
SELECT GuestLogID, GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS_LOG] WHERE GuestID = 1
ORDER BY ModifiedOn ASC
Your data will come out with what the table looked like, from Oldest to Newest, with the first row being what was created & the last row being the current data. You can see exactly what changed, who changed it, and when they changed it.
Optionally, I used to have a function that looped through the RecordSet (in Classic ASP), and only displayed what values had changed on the web page. It made for a GREAT audit trail so that users could see what had changed over time.
You may use as following to get Height and Weight of an Numpy array:
int height = arr.shape[0]
int weight = arr.shape[1]
If your array has multiple dimensions, you can increase the index to access them.
I've implemented a Kotlin + Rx version.
It's for brazilian's currency (e.g. 1,500.00 - 5,21 - 192,90) but you can easily adapt for other formats.
Hope someone else finds it helpful.
RxTextView
.textChangeEvents(fuel_price) // Observe text event changes
.filter { it.text().isNotEmpty() } // do not accept empty text when event first fires
.flatMap {
val onlyNumbers = Regex("\\d+").findAll(it.text()).fold(""){ acc:String,it:MatchResult -> acc.plus(it.value)}
Observable.just(onlyNumbers)
}
.distinctUntilChanged()
.map { it.trimStart('0') }
.map { when (it.length) {
1-> "00"+it
2-> "0"+it
else -> it }
}
.subscribe {
val digitList = it.reversed().mapIndexed { i, c ->
if ( i == 2 ) "${c},"
else if ( i < 2 ) c
else if ( (i-2)%3==0 ) "${c}." else c
}
val currency = digitList.reversed().fold(""){ acc,it -> acc.toString().plus(it) }
fuel_price.text = SpannableStringBuilder(currency)
fuel_price.setSelection(currency.length)
}
This is a very old question, but my answer may help someone.
Below is the working code
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionDecryptionUtil {
public static String encrypt(final String secret, final String data) {
byte[] decodedKey = Base64.getDecoder().decode(secret);
try {
Cipher cipher = Cipher.getInstance("AES");
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
cipher.init(Cipher.ENCRYPT_MODE, originalKey);
byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(cipherText);
} catch (Exception e) {
throw new RuntimeException(
"Error occured while encrypting data", e);
}
}
public static String decrypt(final String secret,
final String encryptedString) {
byte[] decodedKey = Base64.getDecoder().decode(secret);
try {
Cipher cipher = Cipher.getInstance("AES");
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
cipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
return new String(cipherText);
} catch (Exception e) {
throw new RuntimeException(
"Error occured while decrypting data", e);
}
}
public static void main(String[] args) {
String data = "This is not easy as you think";
String key = "---------------------------------";
String encrypted = encrypt(key, data);
System.out.println(encrypted);
System.out.println(decrypt(key, encrypted));
}
}
For Generating Key you can use below class
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class SecretKeyGenerator {
public static void main(String[] args) throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
int keyBitSize = 256;
keyGenerator.init(keyBitSize, secureRandom);
SecretKey secretKey = keyGenerator.generateKey();
System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
}
}
If you are programming a game perhaps you would like to change the background color and use only spaces? For example:
print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"
No, the standard way to serialize to JSON is to use an existing JSON serialization library. If you don't wish to do this, then you're going to have to write your own serialization methods.
If you want guidance on how to do this, I'd suggest examining the source of some of the available libraries.
EDIT: I'm not going to come out and say that writing your own serliazation methods is bad, but you must consider that if it's important to your application to use well-formed JSON, then you have to weigh the overhead of "one more dependency" against the possibility that your custom methods may one day encounter a failure case that you hadn't anticipated. Whether that risk is acceptable is your call.
This is due to locking of Mongodb
sudo rm /var/lib/mongodb/mongod.lock
sudo service mongodb restart
Like this :
jQuery(document).ready(function () {
var title = jQuery(this).attr('title');
});
works for IE, Firefox and Chrome.
A binary tree is a tree whose children are never more than two. A binary search tree follows the invariant that the left child should have a smaller value than the root node's key, while the right child should have a greater value than the root node's key.
Static methods are not instantiated as such, they're just available without an object reference.
A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used.
Let me show an example.
With the following code:
public class A
{
public static void Test()
{
}
}
public class B : A
{
}
If you call B.Test, like this:
class Program
{
static void Main(string[] args)
{
B.Test();
}
}
Then the actual code inside the Main method is as follows:
.entrypoint
.maxstack 8
L0000: nop
L0001: call void ConsoleApplication1.A::Test()
L0006: nop
L0007: ret
As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way.
If you had class types, like in Delphi, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in .NET.
I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there.
Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change.
Thus, virtual/abstract static methods are not available in .NET.
In case someone else stumbles onto this topic - here's a more "one size fits all" solution.
If you are using .git
or .svn
, you can use the --exclude-vcs
option for tar. This will ignore many different files/folders required by different version control systems.
If you want to read more about it, check out: http://www.gnu.org/software/tar/manual/html_section/exclude.html
Replace the following code in this path
Path :
App_Start => WebApiConfig.cs
Code:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}/{Param}",
defaults: new { id = RouteParameter.Optional,
Param = RouteParameter.Optional }
);
According to JVM specification, fields and methods in a Interface can have only Public, Static, Final and Abstract. Ref from Inside Java VM
By default, all the methods in interface is abstract even tough you didn't mention it explicitly.
Interfaces are meant to give only specification. It can not contain any implementations. So To avoid implementing classes to change the specification, it is made final. Since Interface cannot be instantiated, they are made static to access the field using interface name.
Importing a whole library seems inefficient when all you need is essentially two lines of code...
$ldap = ldap_connect("ldap.example.com");
if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) {
// log them in!
} else {
// error message
}
Probably not exactly your issue..
Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments
sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /
May be you have ftped the file in ascii mode instead of binary mode ? If not, this might help.
$ gunzip myarchive.tar.gz
And then untar the resulting tar file using
$ tar xvf myarchive.tar
Hope this helps.
If you want it combined it all in only one control and one command
<PasswordBox Name="PasswordBoxPin" PasswordChar="*">
<PasswordBox.InputBindings>
<KeyBinding Key="Return" Command="{Binding AuthentifyEmpCommand}" CommandParameter="{Binding ElementName=PasswordBoxPin}"/>
</PasswordBox.InputBindings>
</PasswordBox>
And on your Vm (like Konamiman showed)
public void AuthentifyEmp(object obj)
{
var passwordBox = obj as PasswordBox;
var password = passwordBox.Password;
}
private RelayCommand _authentifyEmpCommand;
public RelayCommand AuthentifyEmpCommand => _authentifyEmpCommand ?? (_authentifyEmpCommand = new RelayCommand(AuthentifyEmp, null));
EDIT: Based on comments I feel the need to specify that this is a violation of MVVM pattern, use it only if that is not one of your primary concerns.
try this
IEnumberable<string> aa;
string a = (from t in aa where t.Equals("") select t.Value).ToArray()[0];
If you want to change the external terminal to the new windows terminal, here's how.
By default, Visual Studio Code auto-detects the indentation of the current open file. If you want to switch this feature off and make all indentation, for example, two spaces, you'd do the following in your User Settings or Workspace settings.
{
"editor.tabSize": 2,
"editor.detectIndentation": false
}
string trackPathTemp = track.trackPath;
//The File Path
var videoFilePath = HttpContext.Current.Server.MapPath("~/" + trackPathTemp);
var stream = new FileStream(videoFilePath, FileMode.Open, FileAccess.Read);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4");
result.Content.Headers.ContentRange = new ContentRangeHeaderValue(0, stream.Length);
// result.Content.Headers.Add("filename", "Video.mp4");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Video.mp4"
};
return result;
If you want to forgo MVC entirely, thereby avoiding all the HttpContext mess...
using RazorEngine;
using RazorEngine.Templating; // For extension methods.
string razorText = System.IO.File.ReadAllText(razorTemplateFileLocation);
string emailBody = Engine.Razor.RunCompile(razorText, "templateKey", typeof(Model), model);
This uses the awesome open source Razor Engine here: https://github.com/Antaris/RazorEngine
I think you could do something like this:
for ii in range(200):
restart = False
for jj in range(200, 400):
...block0...
if something:
restart = True
break
if restart:
continue
...block1...
You would expect that this is easily possible but that seems not be the case. The only way I see at the moment is to create a user defined JQL function. I never tried this but here is a plug-in:
http://confluence.atlassian.com/display/DEVNET/Plugin+Tutorial+-+Adding+a+JQL+Function+to+JIRA
First, add it to .gitignore
, so it is not accidentally committed by you (or someone else) again:
.idea
Second, remove the directory only from the repository, but do not delete it locally. To achieve that, do what is listed here:
Remove a file from a Git repository without deleting it from the local filesystem
Third, commit the .gitignore
file and the removal of .idea
from the repository. After that push it to the remote(s).
The full process would look like this:
$ echo '.idea' >> .gitignore
$ git rm -r --cached .idea
$ git add .gitignore
$ git commit -m '(some message stating you added .idea to ignored entries)'
$ git push
(optionally you can replace last line with git push some_remote
, where some_remote
is the name of the remote you want to push to)
I recently set up a script that does this.
As David Brabant pointed out, you can use the System.Net.WebRequest
class to do an HTTP request.
To check whether it is operational, you should use the following example code:
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
# Finally, we clean up the http request by closing it.
If ($HTTP_Response -eq $null) { }
Else { $HTTP_Response.Close() }
<http pattern="/resources/**" security="none"/>
Or with Java configuration:
web.ignoring().antMatchers("/resources/**");
Instead of the old:
<intercept-url pattern="/resources/**" filters="none"/>
for exp . disable security for a login page :
<intercept-url pattern="/login*" filters="none" />
_.groupBy([{tipo: 'A' },{tipo: 'A'}, {tipo: 'B'}], 'tipo');
>> Object {A: Array[2], B: Array[1]}
Change the order in which you are doing things just a bit. You seem to be dividing by 2 for no particular reason at all.
While your application does not guarantee an input string of semi colon delimited variables you could easily make it do so:
package com;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// Good practice to initialize before use
Scanner keyboard = new Scanner(System.in);
String input = "";
// it's also a good idea to prompt the user as to what is going on
keyboardScanner : for (;;) {
input = keyboard.next();
if (input.indexOf(",") >= 0) { // Realistically we would want to use a regex to ensure [0-9],...etc groupings
break keyboardScanner; // break out of the loop
} else {
keyboard = new Scanner(System.in);
continue keyboardScanner; // recreate the scanner in the event we have to start over, just some cleanup
}
}
String strarray[] = input.split(","); // move this up here
int intarray[] = new int[strarray.length];
int count = 0; // Declare variables when they are needed not at the top of methods as there is no reason to allocate memory before it is ready to be used
for (count = 0; count < intarray.length; count++) {
intarray[count] = Integer.parseInt(strarray[count]);
}
for (int s : intarray) {
System.out.println(s);
}
}
}
The problem is on this line:
oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"
Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:
oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
You also have a typo in S:Claims\Sound.wav
, should be S:\Claims\Sound.wav
.
I also assume the apostrophe before Dim oShell
and after Set oShell = Nothing
are typos as well.
Is not necessary to pass the data as JSON string, you can pass the object directly, without defining contentType
or dataType
, like this:
$.ajax({
type: "POST",
url: "TelephoneNumbers.aspx/DeleteNumber",
data: data0,
success: function(data)
{
alert('Done');
}
});
How about using tkinter?
from Tkinter import Tk # from tkinter import Tk for Python 3.x
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)
Done!
The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.
Also, I didn't understand when the accepted answer said "it defaults to node server.js
". I think the documentation clarifies the default behavior:
npm-start
Start a package
Synopsis
npm start [-- <args>]
Description
This runs an arbitrary command specified in the package's "
start
" property of its "scripts
" object. If no "start
" property is specified on the "scripts
" object, it will runnode server.js
.
In summary, running npm start
could do one of two things:
npm start {command_name}
: Run an arbitrary command (i.e. if such command is specified in the start
property of package.json's scripts
object)npm start
: Else if no start
property exists (or no command_name
is passed): Run node server.js
, (which may not be appropriate, for example the OP doesn't have server.js
; the OP runs node
app.js
)package.json
in the directory where you run npm start
, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'
Here's a method I wrote to check if an URL exists or not. I had a requirement to add a request header. It's Groovy but should be fairly simple to adapt to Java. Essentially I'm using the org.springframework.web.client.RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor<T>, java.lang.Object...)
API method. I guess the solution you arrive at depends at least in part on the HTTP method you want to execute. The key take away from example below is that I'm passing a Groovy closure (The third parameter to method restTemplate.execute()
, which is more or less, loosely speaking a Lambda in Java world) that is executed by the Spring API as a callback to be able to manipulate the request object before Spring executes the command,
boolean isUrlExists(String url) {
try {
return (restTemplate.execute(url, HttpMethod.HEAD,
{ ClientHttpRequest request -> request.headers.add('header-name', 'header-value') },
{ ClientHttpResponse response -> response.headers }) as HttpHeaders)?.get('some-response-header-name')?.contains('some-response-header-value')
} catch (Exception e) {
log.warn("Problem checking if $url exists", e)
}
false
}
I'm new to python but I ended up doing something similar to @mouad
unmatched_item = set(dict_1.items()) ^ set(dict_2.items())
len(unmatched_item) # should be 0
The XOR operator (^
) should eliminate all elements of the dict when they are the same in both dicts.
Use
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED.
Version 5.0 Docs are here.
Version 5.1 Docs are here.
I used this code so I still could support older Android versions and use recreate()
on newer Android versions.
Code:
public static void restartActivity(Activity activity){
if (Build.VERSION.SDK_INT >= 11) {
activity.recreate();
} else {
activity.finish();
activity.startActivity(activity.getIntent());
}
}
Sample:
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActivity = MainActivity.this;
Button button = (Button) findViewById(R.id.restart_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
restartActivity(mActivity);
}
});
}
public static void restartActivity(Activity activity) {
if (Build.VERSION.SDK_INT >= 11) {
activity.recreate();
} else {
activity.finish();
activity.startActivity(activity.getIntent());
}
}
}
Have you tried simply selecting by Id?
$("#header").focus();
Seeing as Ids should be unique, there's no need to have a more specific selector.
UPDATE table1, table2 SET table1.col1='value', table2.col1='value' WHERE table1.col3='567' AND table2.col6='567'
This should work for ya.
There is a reference in the MySQL manual for multiple tables.
I modified K3N's code to work for my purpose, and I added some comments to help others figure out how sessionStorage works.
<script>
// Run on page load
window.onload = function() {
// If sessionStorage is storing default values (ex. name), exit the function and do not restore data
if (sessionStorage.getItem('name') == "name") {
return;
}
// If values are not blank, restore them to the fields
var name = sessionStorage.getItem('name');
if (name !== null) $('#inputName').val(name);
var email = sessionStorage.getItem('email');
if (email !== null) $('#inputEmail').val(email);
var subject= sessionStorage.getItem('subject');
if (subject!== null) $('#inputSubject').val(subject);
var message= sessionStorage.getItem('message');
if (message!== null) $('#inputMessage').val(message);
}
// Before refreshing the page, save the form data to sessionStorage
window.onbeforeunload = function() {
sessionStorage.setItem("name", $('#inputName').val());
sessionStorage.setItem("email", $('#inputEmail').val());
sessionStorage.setItem("subject", $('#inputSubject').val());
sessionStorage.setItem("message", $('#inputMessage').val());
}
</script>
I think I encountered the same problem as you. I addressed this problem with the following steps:
1) Go to Google Developers Console
2) Set JavaScript origins:
3) Set Redirect URIs:
To get the new id, all you have to do is flush
the entity manager. See getNext()
method below:
@Entity
@SequenceGenerator(name = "sequence", sequenceName = "mySequence")
public class SequenceFetcher
{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
private long id;
public long getId() {
return id;
}
public static long getNext(EntityManager em) {
SequenceFetcher sf = new SequenceFetcher();
em.persist(sf);
em.flush();
return sf.getId();
}
}
The answers provided by Bohzo and Brabster will obviously work, but you could also just use:
rs3.getInt(1);
to get the value in the first, and in your case, only column.
If you are doing complex, async input validation it might be worth it to abstract ng-model
up one level as part of a custom class with its own validation methods.
https://plnkr.co/edit/gUnUjs0qHQwkq2vPZlpO?p=preview
html
<div>
<label for="a">input a</label>
<input
ng-class="{'is-valid': vm.store.a.isValid == true, 'is-invalid': vm.store.a.isValid == false}"
ng-keyup="vm.store.a.validate(['isEmpty'])"
ng-model="vm.store.a.model"
placeholder="{{vm.store.a.isValid === false ? vm.store.a.warning : ''}}"
id="a" />
<label for="b">input b</label>
<input
ng-class="{'is-valid': vm.store.b.isValid == true, 'is-invalid': vm.store.b.isValid == false}"
ng-keyup="vm.store.b.validate(['isEmpty'])"
ng-model="vm.store.b.model"
placeholder="{{vm.store.b.isValid === false ? vm.store.b.warning : ''}}"
id="b" />
</div>
code
(function() {
const _ = window._;
angular
.module('app', [])
.directive('componentLayout', layout)
.controller('Layout', ['Validator', Layout])
.factory('Validator', function() { return Validator; });
/** Layout controller */
function Layout(Validator) {
this.store = {
a: new Validator({title: 'input a'}),
b: new Validator({title: 'input b'})
};
}
/** layout directive */
function layout() {
return {
restrict: 'EA',
templateUrl: 'layout.html',
controller: 'Layout',
controllerAs: 'vm',
bindToController: true
};
}
/** Validator factory */
function Validator(config) {
this.model = null;
this.isValid = null;
this.title = config.title;
}
Validator.prototype.isEmpty = function(checkName) {
return new Promise((resolve, reject) => {
if (/^\s+$/.test(this.model) || this.model.length === 0) {
this.isValid = false;
this.warning = `${this.title} cannot be empty`;
reject(_.merge(this, {test: checkName}));
}
else {
this.isValid = true;
resolve(_.merge(this, {test: checkName}));
}
});
};
/**
* @memberof Validator
* @param {array} checks - array of strings, must match defined Validator class methods
*/
Validator.prototype.validate = function(checks) {
Promise
.all(checks.map(check => this[check](check)))
.then(res => { console.log('pass', res) })
.catch(e => { console.log('fail', e) })
};
})();
Here is the simple solution with StreamEx
EntryStream.of(countByType).sortedBy(e -> e.getValue()).keys().toList();
Suppose
a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]
and the list of indexes is stored in
b= [0, 1, 2, 4, 6, 7, 8]
then a simple one-line solution will be
c = [a[i] for i in b]
(cross-posting from an answer I gave to a similar question - Does Android support near real time push notification? )
I recently started playing with MQTT http://mqtt.org for Android as a way of doing this sort of thing (i.e. push notification that is not SMS but data driven, almost immediate message delivery, not polling, etc.)
I have a blog post with background information on this in case it's helpful
http://dalelane.co.uk/blog/?p=938
(Note: MQTT is an IBM technology, and I should point out that I work for IBM.)
It sounds like you're doing property checking on an object! If you want to check a property exists (but can be values such as null or 0 in addition to truthy values), the in operator can make for some nice syntax.
var foo = { bar: 1234, baz: null };
console.log("bar in foo:", "bar" in foo); // true
console.log("baz in foo:", "baz" in foo); // true
console.log("otherProp in foo:", "otherProp" in foo) // false
console.log("__proto__ in foo:", "__proto__" in foo) // true
As you can see, the __proto__ property is going to be thrown here. This is true for all inherited properties. For further reading, I'd recommend the MDN page:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Initially, it can be represented graphically as follow:
Then, the sort is applied myList.Sort();
Finally, when you did: myList' = myList2
, you lost the one of the reference but not the original and the collection stayed sorted.
If you use by reference (ref
) then myList'
and myList
will become the same (only one reference).
Note: I use myList'
to represent the parameter that you use in ChangeList
(because you gave the same name as the original)
Could you provide a whole makefile? But right now I can tell - you should check that "install" target already exists. So, check Makefile whether it contains a
install: (anything there)
line. If not, there is no such target and so make has right. Probably you should use just "make" command to compile and then use it as is or install yourself, manually.
Install is not any standard of make, it is just a common target, that could exists, but not necessary.
You need a git client to upload your project to git servers. For eclipse EGIT is a nice plugin to use GIT.
to learn the basic of git , see here // i think you should have the basic first
function showStuff(id, text, btn) {_x000D_
document.getElementById(id).style.display = 'block';_x000D_
// hide the lorem ipsum text_x000D_
document.getElementById(text).style.display = 'none';_x000D_
// hide the link_x000D_
btn.style.display = 'none';_x000D_
}
_x000D_
<td class="post">_x000D_
_x000D_
<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>_x000D_
<span id="answer1" style="display: none;">_x000D_
<textarea rows="10" cols="115"></textarea>_x000D_
</span>_x000D_
_x000D_
<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>_x000D_
</td>
_x000D_
Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/
and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1
.
See this link for the official GlassFish documentation about logging.
You can use these options as well, either use \footnotesize
or \tiny
. This would really help in fitting big tables.
\begin{table}[htbp]
\footnotesize
\caption{Information on making the table size small}
\label{table:table1}
\begin{tabular}{ll}
\toprule
S.No & HMD \\
\midrule
1 & HTC Vive \\
2 & HTC Vive Pro \\
\bottomrule
\end{tabular}
\end{table}
You will find Python's string literal documentation here:
http://docs.python.org/tutorial/introduction.html#strings
and here:
http://docs.python.org/reference/lexical_analysis.html#literals
The simplest example would be using the 'r' prefix:
ss = r'Hello\nWorld'
print(ss)
Hello\nWorld
For me, the problem came from the fact that I was importing an app in INSTALLED_APPS
which was itself importing a model in its __init__.py
file
I had :
settings.py
INSTALLED_APPS = [
...
'myapp',
...
]
myapp.__init__.py
from django.contrib.sites.models import Site
commenting out import models
in myapp.__init__.py
made it work :
# from django.contrib.sites.models import Site
You need to understand java generics. You have a list of ClientThread
but trying to get String
. You have other errors, but this one is very basic.
If you want to check quietly via $? without the hassle of grep'ing wget's output you can use:
wget -q "http://blah.meh.com/my/path" -O /dev/null
Works even on URLs with just a path but has the disadvantage that something's really downloaded so this is not recommended when checking big files for existence.
Another reason why you might get errors like "relation already exists" is if the DROP
command did not execute correctly.
One reason this can happen is if there are other sessions connected to the database which you need to close first.
When I faced with a similar problem, I finished with the following code:
public bool IsFileLocked(string filePath)
{
try
{
using (File.Open(filePath, FileMode.Open)){}
}
catch (IOException e)
{
var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
return errorCode == 32 || errorCode == 33;
}
return false;
}
Create new Js function
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
Call the function when you want to delay execution. Use milliseconds in int for delay value.
####Some code
sleep(1000);
####Next line
When testing for directories remember that every directory contains two special files.
One is called '.' and the other '..'
. is the directory's own name while .. is the name of it's parent directory.
To avoid trailing backslash problems just test to see if the directory knows it's own name.
eg:
if not exist %temp%\buffer\. mkdir %temp%\buffer
The shield icon that is being mentioned was not in the sidebar for me either, however I solved it doing the following:
Find the shield icon located in the far right of the URL input bar,
Once clicked, the following popup should appear wherein you can click Load unsafe scripts,
That should result in a page refresh and the scripts should start working. What used to be an error,
is now merely a warning,
OS: Windows 10
Chrome Version: 76.0.3809.132 (Official Build) (64-bit)
Edit #1
On version 66.0.3359.117, the shield icon is still available:
Notice how the popup design has changed, so this is Chrome on version 66.0.3359.117.
Note: The shield icon will only appear when you try to load insecure content (content from http
) while on https
.
To reference a commit, simply write its SHA-hash, and it'll automatically get turned into a link.
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
Check your php error log which might be a separate file from your apache error log.
Find it by going to phpinfo()
and check for error_log attribute.
If it is not set. Set it: https://stackoverflow.com/a/12835262/445131
Maybe your post_max_size is too small for what you're trying to post, or one of the other max memory settings is too low.
Another understated reason for not using a singleton DbContext, even in a single threaded single user application, is because of the identity map pattern it uses. It means that every time you retrieve data using query or by id, it will keep the retrieved entity instances in cache. The next time you retrieve the same entity, it will give you the cached instance of the entity, if available, with any modifications you have done in the same session. This is necessary so the SaveChanges method does not end up with multiple different entity instances of the same database record(s); otherwise, the context would have to somehow merge the data from all those entity instances.
The reason that is a problem is a singleton DbContext can become a time bomb that could eventually cache the whole database + the overhead of .NET objects in memory.
There are ways around this behavior by only using Linq queries with the .NoTracking()
extension method. Also these days PCs have a lot of RAM. But usually that is not the desired behavior.
There are a few important informations missing from your question:
$ vim --version
?If your Vim was built with clipboard support, you are supposed to use the clipboard register like this, in normal mode:
gg"+yG
If your Vim doesn't have clipboard support, you can manage to copy text from Vim to your OS clipboard via other programs. This pretty much depends on your OS but you didn't say what it is so we can't really help.
However, if your Vim is crippled, the best thing to do is to install a proper build with clipboard support but I can't tell you how either because I don't know what OS you use.
edit
On debian based systems, the following command will install a proper Vim with clipboard, ruby, python… support.
$ sudo apt-get install vim-gnome
this way worked for me
ng-disabled="(user.Role.ID != 1) && (user.Role.ID != 2)"
If you have
varname <- c("a", "b", "d")
you can do
get(varname[1]) + 2
for
a + 2
or
assign(varname[1], 2 + 2)
for
a <- 2 + 2
So it looks like you use GET when you want to evaluate a formula that uses a variable (such as a concatenate), and ASSIGN when you want to assign a value to a pre-declared variable.
Syntax for assign: assign(x, value)
x: a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.
value: value to be assigned to x.
The other answers all use Arrays.asList()
, which returns an unmodifiable list (an UnsupportedOperationException
is thrown if you try to add or remove an element). To get a mutable list you can wrap the returned list in a new ArrayList
as a couple of answers point out, but a cleaner solution is to use Guava's Lists.newArrayList() (available since at least Guava 10, released in 2011).
For example:
Lists.newArrayList("Blargle!");
Unity added JsonUtility to their API after 5.3.3 Update. Forget about all the 3rd party libraries unless you are doing something more complicated. JsonUtility is faster than other Json libraries. Update to Unity 5.3.3 version or above then try the solution below.
JsonUtility
is a lightweight API. Only simple types are supported. It does not support collections such as Dictionary. One exception is List
. It supports List
and List
array!
If you need to serialize a Dictionary
or do something other than simply serializing and deserializing simple datatypes, use a third-party API. Otherwise, continue reading.
Example class to serialize:
[Serializable]
public class Player
{
public string playerId;
public string playerLoc;
public string playerNick;
}
1. ONE DATA OBJECT (NON-ARRAY JSON)
Serializing Part A:
Serialize to Json with the public static string ToJson(object obj);
method.
Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";
//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance);
Debug.Log(playerToJson);
Output:
{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}
Serializing Part B:
Serialize to Json with the public static string ToJson(object obj, bool prettyPrint);
method overload. Simply passing true
to the JsonUtility.ToJson
function will format the data. Compare the output below to the output above.
Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";
//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance, true);
Debug.Log(playerToJson);
Output:
{
"playerId": "8484239823",
"playerLoc": "Powai",
"playerNick": "Random Nick"
}
Deserializing Part A:
Deserialize json with the public static T FromJson(string json);
method overload.
string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = JsonUtility.FromJson<Player>(jsonString);
Debug.Log(player.playerLoc);
Deserializing Part B:
Deserialize json with the public static object FromJson(string json, Type type);
method overload.
string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = (Player)JsonUtility.FromJson(jsonString, typeof(Player));
Debug.Log(player.playerLoc);
Deserializing Part C:
Deserialize json with the public static void FromJsonOverwrite(string json, object objectToOverwrite);
method. When JsonUtility.FromJsonOverwrite
is used, no new instance of that Object you are deserializing to will be created. It will simply re-use the instance you pass in and overwrite its values.
This is efficient and should be used if possible.
Player playerInstance;
void Start()
{
//Must create instance once
playerInstance = new Player();
deserialize();
}
void deserialize()
{
string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
//Overwrite the values in the existing class instance "playerInstance". Less memory Allocation
JsonUtility.FromJsonOverwrite(jsonString, playerInstance);
Debug.Log(playerInstance.playerLoc);
}
2. MULTIPLE DATA(ARRAY JSON)
Your Json contains multiple data objects. For example playerId
appeared more than once. Unity's JsonUtility
does not support array as it is still new but you can use a helper class from this person to get array working with JsonUtility
.
Create a class called JsonHelper
. Copy the JsonHelper directly from below.
public static class JsonHelper
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.Items;
}
public static string ToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper);
}
public static string ToJson<T>(T[] array, bool prettyPrint)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper, prettyPrint);
}
[Serializable]
private class Wrapper<T>
{
public T[] Items;
}
}
Serializing Json Array:
Player[] playerInstance = new Player[2];
playerInstance[0] = new Player();
playerInstance[0].playerId = "8484239823";
playerInstance[0].playerLoc = "Powai";
playerInstance[0].playerNick = "Random Nick";
playerInstance[1] = new Player();
playerInstance[1].playerId = "512343283";
playerInstance[1].playerLoc = "User2";
playerInstance[1].playerNick = "Rand Nick 2";
//Convert to JSON
string playerToJson = JsonHelper.ToJson(playerInstance, true);
Debug.Log(playerToJson);
Output:
{
"Items": [
{
"playerId": "8484239823",
"playerLoc": "Powai",
"playerNick": "Random Nick"
},
{
"playerId": "512343283",
"playerLoc": "User2",
"playerNick": "Rand Nick 2"
}
]
}
Deserializing Json Array:
string jsonString = "{\r\n \"Items\": [\r\n {\r\n \"playerId\": \"8484239823\",\r\n \"playerLoc\": \"Powai\",\r\n \"playerNick\": \"Random Nick\"\r\n },\r\n {\r\n \"playerId\": \"512343283\",\r\n \"playerLoc\": \"User2\",\r\n \"playerNick\": \"Rand Nick 2\"\r\n }\r\n ]\r\n}";
Player[] player = JsonHelper.FromJson<Player>(jsonString);
Debug.Log(player[0].playerLoc);
Debug.Log(player[1].playerLoc);
Output:
Powai
User2
If this is a Json array from the server and you did not create it by hand:
You may have to Add {"Items":
in front of the received string then add }
at the end of it.
I made a simple function for this:
string fixJson(string value)
{
value = "{\"Items\":" + value + "}";
return value;
}
then you can use it:
string jsonString = fixJson(yourJsonFromServer);
Player[] player = JsonHelper.FromJson<Player>(jsonString);
3.Deserialize json string without class && De-serializing Json with numeric properties
This is a Json that starts with a number or numeric properties.
For example:
{
"USD" : {"15m" : 1740.01, "last" : 1740.01, "buy" : 1740.01, "sell" : 1744.74, "symbol" : "$"},
"ISK" : {"15m" : 179479.11, "last" : 179479.11, "buy" : 179479.11, "sell" : 179967, "symbol" : "kr"},
"NZD" : {"15m" : 2522.84, "last" : 2522.84, "buy" : 2522.84, "sell" : 2529.69, "symbol" : "$"}
}
Unity's JsonUtility
does not support this because the "15m" property starts with a number. A class variable cannot start with an integer.
Download SimpleJSON.cs
from Unity's wiki.
To get the "15m" property of USD:
var N = JSON.Parse(yourJsonString);
string price = N["USD"]["15m"].Value;
Debug.Log(price);
To get the "15m" property of ISK:
var N = JSON.Parse(yourJsonString);
string price = N["ISK"]["15m"].Value;
Debug.Log(price);
To get the "15m" property of NZD:
var N = JSON.Parse(yourJsonString);
string price = N["NZD"]["15m"].Value;
Debug.Log(price);
The rest of the Json properties that doesn't start with a numeric digit can be handled by Unity's JsonUtility.
4.TROUBLESHOOTING JsonUtility:
Problems when serializing with JsonUtility.ToJson
?
Getting empty string or "{}
" with JsonUtility.ToJson
?
A. Make sure that the class is not an array. If it is, use the helper class above with JsonHelper.ToJson
instead of JsonUtility.ToJson
.
B. Add [Serializable]
to the top of the class you are serializing.
C. Remove property from the class. For example, in the variable, public string playerId { get; set; }
remove { get; set; }
. Unity cannot serialize this.
Problems when deserializing with JsonUtility.FromJson
?
A. If you get Null
, make sure that the Json is not a Json array. If it is, use the helper class above with JsonHelper.FromJson
instead of JsonUtility.FromJson
.
B. If you get NullReferenceException
while deserializing, add [Serializable]
to the top of the class.
C.Any other problems, verify that your json is valid. Go to this site here and paste the json. It should show you if the json is valid. It should also generate the proper class with the Json. Just make sure to remove remove { get; set; }
from each variable and also add [Serializable]
to the top of each class generated.
Newtonsoft.Json:
If for some reason Newtonsoft.Json must be used then check out the forked version for Unity here. Note that you may experience crash if certain feature is used. Be careful.
To answer your question:
Your original data is
[{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]
Add {"Items":
in front of it then add }
at the end of it.
Code to do this:
serviceData = "{\"Items\":" + serviceData + "}";
Now you have:
{"Items":[{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]}
To serialize the multiple data from php as arrays, you can now do
public player[] playerInstance;
playerInstance = JsonHelper.FromJson<player>(serviceData);
playerInstance[0]
is your first data
playerInstance[1]
is your second data
playerInstance[2]
is your third data
or data inside the class with playerInstance[0].playerLoc
, playerInstance[1].playerLoc
, playerInstance[2].playerLoc
......
You can use playerInstance.Length
to check the length before accessing it.
NOTE: Remove { get; set; }
from the player
class. If you have { get; set; }
, it won't work. Unity's JsonUtility
does NOT work with class members that are defined as properties.
Say you want Comic Sans for the title and Helvetica for the x label.
csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}
plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()
This question helped me a lot but didn't get me all the way in understanding what needs to happen. This blog post did an amazing job of walking me through it.
Here are the important bits all in one place:
I sympathize with all the headaches, so here's some code to wrap it all up:
$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'twitterapi',
'count' => '2'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_token' => $token,
'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
This one-liner works, for all types of objects, as long as they are in globals()
dict, which they should be:
def name_of_global_obj(xx):
return [objname for objname, oid in globals().items()
if id(oid)==id(xx)][0]
or, equivalently:
def name_of_global_obj(xx):
for objname, oid in globals().items():
if oid is xx:
return objname
This is a valid regex for validating e-mails. It's totally compliant with RFC822 and accepts IP address and server names (for intranet purposes).
public static boolean isEmailValid(String email) {
final Pattern EMAIL_REGEX = Pattern.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", Pattern.CASE_INSENSITIVE);
return EMAIL_REGEX.matcher(email).matches();
}
Here are some output examples, when you call isEmailValid(emailVariable)
:
[email protected] // valid
[email protected] // valid
[email protected] // valid (with +label - Gmail accepts it!)
[email protected] // valid (with IP addresses)
[email protected] // valid (with +label and IP address)
john.foo@someserver // valid (with no first domain level)
[email protected] // valid (case insensitive)
@someserver // invalid
@someserver.com // invalid
john@. // invalid
[email protected] // invalid
The best way to understand would be to have all the LifeCycle methods overridden in your activity and placing a breakpoint(if checking in emulator) or a Log in each one of them. You'll get to know which one gets called when.
Just as an spoiler, onCreate()
gets called first, then if you paused the activity by either going to home screen or by launching another activity, onPause()
gets called. If the OS destroys the activity in the meantime, onDestroy()
gets called. If you resume the app and the app already got destroyed, onCreate()
will get called, or else onResume()
will get called.
Edit: I forgot about onStop()
, it gets called before onDestroy()
.
Do the exercise I mentioned and you'll be having a better understanding.
Take a look also at How do I sort unicode strings alphabetically in Python? where the discussion is about sorting rules given by the Unicode Collation Algorithm (http://www.unicode.org/reports/tr10/).
To reply to the comment
What? How else can ordering be defined other than left-to-right?
by S.Lott, there is a famous counter-example when sorting French language. It involves accents: indeed, one could say that, in French, letters are sorted left-to-right and accents right-to-left. Here is the counter-example: we have e < é and o < ô, so you would expect the words cote, coté, côte, côté to be sorted as cote < coté < côte < côté. Well, this is not what happens, in fact you have: cote < côte < coté < côté, i.e., if we remove "c" and "t", we get oe < ôe < oé < ôé, which is exactly right-to-left ordering.
And a last remark: you shouldn't be talking about left-to-right and right-to-left sorting but rather about forward and backward sorting.
Indeed there are languages written from right to left and if you think Arabic and Hebrew are sorted right-to-left you may be right from a graphical point of view, but you are wrong on the logical level!
Indeed, Unicode considers character strings encoded in logical order, and writing direction is a phenomenon occurring on the glyph level. In other words, even if in the word ???? the letter shin appears on the right of the lamed, logically it occurs before it. To sort this word one will first consider the shin, then the lamed, then the vav, then the mem, and this is forward ordering (although Hebrew is written right-to-left), while French accents are sorted backwards (although French is written left-to-right).
<form (keydown)="someMethod($event)">
<input type="text">
</form>
someMethod(event:any){
if(event.keyCode == 13){
alert('Entered Click Event!');
}else{
}
}
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
Actually only Jon's answer (Sep 5 '11 at 9:37) with BaseStream.Seek worked for my case. Thanks Jon! I needed to append lines to a zip archived txt file.
using (FileStream zipFS = new FileStream(@"c:\Temp\SFImport\test.zip",FileMode.OpenOrCreate))
{
using (ZipArchive arch = new ZipArchive(zipFS,ZipArchiveMode.Update))
{
ZipArchiveEntry entry = arch.GetEntry("testfile.txt");
if (entry == null)
{
entry = arch.CreateEntry("testfile.txt");
}
using (StreamWriter sw = new StreamWriter(entry.Open()))
{
sw.BaseStream.Seek(0,SeekOrigin.End);
sw.WriteLine("text content");
}
}
}
Install firebug and use console.log
instead of alert
. Then you will see the exact element your accessing.
You cannot run an ipa file in the simulator because the ipa file is compiled for a phone's ARM architecture, not the simulator's x86 architecture.
However, you can extract an app installed in a local simulator, send it to someone else, and have them copy it to the simulator on their machine.
In terminal, type:
open ~/Library/Application\ Support/iPhone\ Simulator/*/Applications
This will open all the applications folders of all the simulators you have installed. Each of the applications will be in a folder with a random hexadecimal name. You can work out which is your application by looking inside each of them. Once you have found out which one you want, right click it and choose "Compress ..." and it will make a zip file that you can easily copy to another computer and unzip to a similar location.
I recorded a macro with 'Relative References' and this is what I got :
Range("F10").Select
ActiveCell.Offset(0, 3).Range("A1:D11").Select
Heres what I thought : If the range selection is in quotes, VBA really wants a STRING and interprets the cells out of it so tried the following:
Dim MyRange as String
MyRange = "A1:D11"
Range(MyRange).Select
And it worked :) ie.. just create a string using your variables, make sure to dimension it as a STRING variables and Excel will read right off of it ;)
Following tested and found working :
Sub Macro04()
Dim Copyrange As String
Startrow = 1
Lastrow = 11
Let Copyrange = "A" & Startrow & ":" & "D" & Lastrow
Range(Copyrange).Select
End Sub
function SingletonClass()
{
// demo variable
var names = [];
// instance of the singleton
this.singletonInstance = null;
// Get the instance of the SingletonClass
// If there is no instance in this.singletonInstance, instanciate one
var getInstance = function() {
if (!this.singletonInstance) {
// create a instance
this.singletonInstance = createInstance();
}
// return the instance of the singletonClass
return this.singletonInstance;
}
// function for the creation of the SingletonClass class
var createInstance = function() {
// public methodes
return {
add : function(name) {
names.push(name);
},
names : function() {
return names;
}
}
}
// wen constructed the getInstance is automaticly called and return the SingletonClass instance
return getInstance();
}
var obj1 = new SingletonClass();
obj1.add("Jim");
console.log(obj1.names());
// prints: ["Jim"]
var obj2 = new SingletonClass();
obj2.add("Ralph");
console.log(obj1.names());
// Ralph is added to the singleton instance and there for also acceseble by obj1
// prints: ["Jim", "Ralph"]
console.log(obj2.names());
// prints: ["Jim", "Ralph"]
obj1.add("Bart");
console.log(obj2.names());
// prints: ["Jim", "Ralph", "Bart"]
Exception in thread "main" java.lang.NoClassDefFoundError
One of the places java tries to find your .class
file is your current directory. So if your .class
file is in C:\java
, you should change your current directory to that.
To change your directory, type the following command at the prompt and press Enter:
cd c:\java
This .
tells java that your classpath is your local directory.
Executing your program using this command should correct the problem:
java -classpath . HelloWorld
Why can't it just use AND
in the ON
clause? For example:
SELECT *
FROM flights
INNER JOIN airports
ON ((airports.code = flights.fairport)
AND (airports.code = flights.tairport))
In case anybody else falls onto this page, you can also solve this by using the Ip address in the URL request instead of the domain:
NSURL *myURL = [NSURL URLWithString:@"http://10.0.0.2/mypage.php"];
Then you specify the Host manually:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];
[request setAllHTTPHeaderFields:[NSDictionary dictionaryWithObjectAndKeys:@"myserver",@"Host"]];
As far as the server is concerned, it will behave the exact same way as if you had used http://myserver/mypage.php
, except that the iPhone will not have to do a DNS lookup.
100% Public API.
I think you want to print the name of the person or both the name and email :
const renObjData = this.props.data.map(function(data, idx) {
return <p key={idx}>{data.name}</p>;
});
or :
const renObjData = this.props.data.map(function(data, idx) {
return ([
<p key={idx}>{data.name}</p>,
<p key={idx}>{data.email}</p>,
]);
});
Is there a more elegant way to write this code?
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)
There is another way to do this:
//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck
Are you aware of <button>
elements? <button>
elements can be styled just like <div>
elements and can have type="submit"
so they submit the form without javascript:
<form action="whatever.html" method="post">
<button name="mysubmitbutton" id="mysubmitbutton" type="submit" class="customButton">
Button Text
</button>
</form>
Using a <button>
is also more semantic, whereas <div>
is very generic. You get the following benefits for free:
<button type="submit">
becomes a "default" button, which means the return key will automatically submit the form. You can't do this with a <div>
, you'd have to add a separate keydown handler to the <form>
element.There's one (non-) caveat: a <button>
can only have phrasing content, though it's unlikely anyone would need any other type of content when using the element to submit a form.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse("file.xml");
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getChildNodes();
int length = nl.getLength();
for (int i = 0; i < length; i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("staff")) {
String name = el.getElementsByTagName("name").item(0).getTextContent();
String phone = el.getElementsByTagName("phone").item(0).getTextContent();
String email = el.getElementsByTagName("email").item(0).getTextContent();
String area = el.getElementsByTagName("area").item(0).getTextContent();
String city = el.getElementsByTagName("city").item(0).getTextContent();
}
}
}
Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE
is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.
For each node under stuff (name, phone, email, area, city)
el.getElementsByTagName("name").item(0).getTextContent();
el.getElementsByTagName("name")
will extract the "name" nodes under stuff,
.item(0)
will get you the first node
and .getTextContent()
will get the text content inside.
Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:
public class Staff {
private String name;
private String phone;
private String email;
private String area;
private String city;
...getters setters
}
Then using jackson:
JsonNode root = new XmlMapper().readTree(xml.getBytes());
ObjectMapper mapper = new ObjectMapper();
root.forEach(node -> consume(node, mapper));
private void consume(JsonNode node, ObjectMapper mapper) {
try {
Staff staff = mapper.treeToValue(node, Staff.class);
//TODO your job with staff
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
Just include "a" tag in "button" tag.
<button><a href="mailto:..."></a></button>
I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.
CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG
You can find details about the parameters at this link.
Hope it helps!
In order to uninstall miniconda, simply remove the miniconda
folder,
rm -r ~/miniconda/
As for avoiding conflicts between different Python environments, you can use virtual environments. In particular, with Miniconda, the following workflow could be used,
$ wget https://repo.continuum.io/miniconda/Miniconda3-3.7.0-Linux-x86_64.sh -O ~/miniconda.sh
$ bash miniconda
$ conda env remove --yes -n new_env # remove the environement new_env if it exists (optional)
$ conda create --yes -n new_env pip numpy pandas scipy matplotlib scikit-learn nltk ipython-notebook seaborn python=2
$ activate new_env
$ # pip install modules if needed, run python scripts, etc
# everything will be installed in the new_env
# located in ~/miniconda/envs/new_env
$ deactivate
Two years on, and this issue is still around...
In iOS 8 / XCode 6.1, I was sometimes finding that my UILabel
(created in a UITableViewCell
, with AutoLayout turned on, and flexible constraints so it had plenty of space) wouldn't resize itself to fit the text string.
The solution, as in previous years, was to set the text, and then call sizeToFit
.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
. . .
cell.lblCreatedAt.text = [note getCreatedDateAsString];
[cell.lblCreatedAt sizeToFit];
}
(Sigh.)
I was just playing around with this same subject, which is the fastest way to access the pixels. I currently know of two ways for doing this:
getRGB()
method as described in @tskuzzy's answer.By accessing the pixels array directly using:
byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
If you are working with large images and performance is an issue, the first method is absolutely not the way to go. The getRGB()
method combines the alpha, red, green and blue values into one int and then returns the result, which in most cases you'll do the reverse to get these values back.
The second method will return the red, green and blue values directly for each pixel, and if there is an alpha channel it will add the alpha value. Using this method is harder in terms of calculating indices, but is much faster than the first approach.
In my application I was able to reduce the time of processing the pixels by more than 90% by just switching from the first approach to the second!
Here is a comparison I've setup to compare the two approaches:
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import javax.imageio.ImageIO;
public class PerformanceTest {
public static void main(String[] args) throws IOException {
BufferedImage hugeImage = ImageIO.read(PerformanceTest.class.getResource("12000X12000.jpg"));
System.out.println("Testing convertTo2DUsingGetRGB:");
for (int i = 0; i < 10; i++) {
long startTime = System.nanoTime();
int[][] result = convertTo2DUsingGetRGB(hugeImage);
long endTime = System.nanoTime();
System.out.println(String.format("%-2d: %s", (i + 1), toString(endTime - startTime)));
}
System.out.println("");
System.out.println("Testing convertTo2DWithoutUsingGetRGB:");
for (int i = 0; i < 10; i++) {
long startTime = System.nanoTime();
int[][] result = convertTo2DWithoutUsingGetRGB(hugeImage);
long endTime = System.nanoTime();
System.out.println(String.format("%-2d: %s", (i + 1), toString(endTime - startTime)));
}
}
private static int[][] convertTo2DUsingGetRGB(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[][] result = new int[height][width];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
result[row][col] = image.getRGB(col, row);
}
}
return result;
}
private static int[][] convertTo2DWithoutUsingGetRGB(BufferedImage image) {
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel + 3 < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel + 2 < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
private static String toString(long nanoSecs) {
int minutes = (int) (nanoSecs / 60000000000.0);
int seconds = (int) (nanoSecs / 1000000000.0) - (minutes * 60);
int millisecs = (int) ( ((nanoSecs / 1000000000.0) - (seconds + minutes * 60)) * 1000);
if (minutes == 0 && seconds == 0)
return millisecs + "ms";
else if (minutes == 0 && millisecs == 0)
return seconds + "s";
else if (seconds == 0 && millisecs == 0)
return minutes + "min";
else if (minutes == 0)
return seconds + "s " + millisecs + "ms";
else if (seconds == 0)
return minutes + "min " + millisecs + "ms";
else if (millisecs == 0)
return minutes + "min " + seconds + "s";
return minutes + "min " + seconds + "s " + millisecs + "ms";
}
}
Can you guess the output? ;)
Testing convertTo2DUsingGetRGB:
1 : 16s 911ms
2 : 16s 730ms
3 : 16s 512ms
4 : 16s 476ms
5 : 16s 503ms
6 : 16s 683ms
7 : 16s 477ms
8 : 16s 373ms
9 : 16s 367ms
10: 16s 446ms
Testing convertTo2DWithoutUsingGetRGB:
1 : 1s 487ms
2 : 1s 940ms
3 : 1s 785ms
4 : 1s 848ms
5 : 1s 624ms
6 : 2s 13ms
7 : 1s 968ms
8 : 1s 864ms
9 : 1s 673ms
10: 2s 86ms
BUILD SUCCESSFUL (total time: 3 minutes 10 seconds)
It seems that you can use regexp too
WHERE NOT REGEXP_LIKE(field, '^Done|^Finished')
I'm not sure how well this will perform though ... see here
I am using Mac OS, and I was stuck with this bug even after uninstalling / removing all mysql and MAMP. Earlier, I installed brew install mysql
and also used MAMP
.
addling softlink didn't work for me.
It was only resolved by removing all existing mysql. and then install mysql through MySQL from here.
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".
And also it would require to run the docker in privileged mode, so the commands would be:
sudo chmod 757 /var/run/docker.sock
docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...
Not sure if your question was answered.
This will write the time & date every 20 seconds in the file ping_ip.txt. The second to last line just says run the same batch file again, and agan, and again,..........etc.
Does not seem to create multiple instances, so that's a good thing.
@echo %time% %date% >>ping_ip.txt
ping -n 20 -w 3 127.0.0.1 >>ping_ip.txt
This_Batch_FileName.bat
cls
You don't need arrays for this. Try something like:
ActiveSheet.Range("$A$1:$A$" & LastRow).RemoveDuplicates Columns:=1, Header:=xlYes
If there's no header, change accordingly.
EDIT: Here's the traditional method, which takes advantage of the fact that each item in a Collection
must have a unique key:
Sub test()
Dim ws As Excel.Worksheet
Dim LastRow As Long
Dim coll As Collection
Dim cell As Excel.Range
Dim arr() As String
Dim i As Long
Set ws = ActiveSheet
With ws
LastRow = .Range("C" & .Rows.Count).End(xlUp).Row
Set coll = New Collection
For Each cell In .Range("C4:C" & LastRow)
On Error Resume Next
coll.Add cell.Value, CStr(cell.Value)
On Error GoTo 0
Next cell
ReDim arr(1 To coll.Count)
For i = LBound(arr) To UBound(arr)
arr(i) = coll(i)
'to show in Immediate Window
Debug.Print arr(i)
Next i
End With
End Sub
Try adding the following to your head-tag:
<meta name="viewport" content="width=device-width, initial-scale=1.0,
minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
additionally
<meta name="HandheldFriendly" content="true">
Finally, either as a style-attribute or in your css file, add the following text for webkit-based Browsers:
html {
-webkit-text-size-adjust: none
}
Windows Task scheduler (Windows server 2008r2)
Same error for me (last run result: 0x1)
Tabs
program/script
and
start in
even if there is spaces in the path name...
Run with highest privileges
and
configure for your OS...
Now it work!
last run result: The operation completed successfully
• Debug: fine-grained statements concerning program state, typically used for debugging;
• Info: informational statements concerning program state, representing program events or behavior tracking;
• Warn: statements that describe potentially harmful events or states in the program;
• Error: statements that describe non-fatal errors in the application; this level is used quite often for logging handled exceptions;
• Fatal: statements representing the most severe of error conditions, assumedly resulting in program termination.
Found on http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx
You can (should) use CROSS JOIN
. Following query will be equivalent to yours:
SELECT
table1.columnA
, table2.columnA
FROM table1
CROSS JOIN table2
WHERE table1.columnA = 'Some value'
or you can even use INNER JOIN with some always true conditon:
FROM table1
INNER JOIN table2 ON 1=1
I was also facing same error when I was inserting the data into HIVE external table which was pointing to Elastic search cluster.
I replaced the older JAR elasticsearch-hadoop-2.0.0.RC1.jar
to elasticsearch-hadoop-5.6.0.jar
, and everything worked fine.
My Suggestion is please use the specific JAR as per the elastic search version. Don't use older JARs if you are using newer version of elastic search.
Thanks to this post Hive- Elasticsearch Write Operation #409
set the below property:
"npm config set strict-ssl false"
You can create different python development environments graphically from Anaconda Navigator. I had same problem while working with different python versions so I used anaconda navigator to create different python development environments and used different python versions in each environments.
Here is the help documentation for this.
https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/
[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]
Here's a complete example using Java 8:
import java.util.*;
public class Test {
public static void main(String args[]) {
int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };
Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
.reversed());
System.out.println(Arrays.deepToString(twoDim));
}
}
Output:
[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]
For Java 7 you can do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
If you unfortunate enough to work on Java 6 or older, you'd do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return ((Integer) o2[0]).compareTo(o1[0]);
}
});
I had the same problem, no possible connection at second login.
After solving the problem (useSecurity, etc., see above), I realized that admin/admin worked (with Synology, it that's relevant).
Using print
without parentheses in Python 3 code is not a good idea. Nor is creating aliases, etc. If that's a deal breaker, use Python 2.
However, print
without parentheses might be useful in the interactive shell. It's not really a matter of reducing the number of characters, but rather avoiding the need to press Shift twice every time you want to print something while you're debugging. IPython lets you call functions without using parentheses if you start the line with a slash:
Python 3.6.6 (default, Jun 28 2018, 05:43:53)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: var = 'Hello world'
In [2]: /print var
Hello world
And if you turn on autocall
, you won't even need to type the slash:
In [3]: %autocall
Automatic calling is: Smart
In [4]: print var
------> print(var)
Hello world
Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:
<script type="text/javascript">
$(function() {
$('form').submit(function(){
$.post('http://example.com/upload', function() {
window.location = 'http://google.com';
});
return false;
});
});
</script>
You can simply use this bootstrap helper to dialogs (only 5 kB)
it has support for ajax request, iframes, common dialogs, confirm and prompt!
you can use it as:
eModal.iframe('http://someUrl.com', 'This is a tile for iframe', callbackIfNeeded);
eModal.alert('The message', 'This title');
eModal.ajax('/mypage.html', 'This is a ajax', callbackIfNeeded);
eModal.confirm('the question', 'The title', theMandatoryCallback);
eModal.prompt('Form question', 'This is a ajax', theMandatoryCallback);
this provide a loading progress while loading the iframe!
No html required.
You can use a object literal as parameter to extra options.
Check the site form more details.
best,
switch(position) {
case 0:
setContentView(R.layout.xml0);
break;
case 1:
setContentView(R.layout.xml1);
break;
default:
setContentView(R.layout.default);
break;
}
i hope this will do the job!
Yes, ./
means the current working directory. You can just reference the file directly by name, without it.
I had the same problem, maven was complaining about a missing artifact, even though it existed in .m2/repository/[...]. In my case the problem was that I forgot to specify the correct repository in the pom.xml from which the package was downloaded originally (download by another project).
Adding the package repository to the pom.xml solved the problem.
<repositories>
<repository>
<id>SomeName</id>
<name>SomeName</name>
<url>http://url.to.repo</url>
</repository>
</repositories>
Thanks Maximilianus for the hint to those "*.repositories" files in the package directory.