for ($s=65; $s<=90; $s++) {
//echo chr($s);
$objPHPExcel->getActiveSheet()->getColumnDimension(chr($s))->setAutoSize(true);
}
You can use
$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);
or define auto-size:
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
I don't have much experience working with php but from a logic standpoint this is what I would do.
Below is some pseudocode illustrating this technique:
for (int i = 0; i < MySQLResults.count; i++){
$objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name);
// Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
$objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
$objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
}
Try this
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");
Try this
$objPHPExcel->getActiveSheet()->getStyle('A1:D1')->getFont()->setBold(true);
hi i got the same problem.. add 0.71 to excel cell width value and give that value to the
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
eg: A Column width = 3.71 (excel value)
give column width = 4.42
will give the output file with same cell width.
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(4.42);
hope this help
Try the below complete example for the same
<?php
$objPHPExcel = new PHPExcel();
$query1 = "SELECT * FROM employee";
$exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
$serialnumber=0;
//Set header with temp array
$tmparray =array("Sr.Number","Employee Login","Employee Name");
//take new main array and set header array in it.
$sheet =array($tmparray);
while ($res1 = mysql_fetch_array($exec1))
{
$tmparray =array();
$serialnumber = $serialnumber + 1;
array_push($tmparray,$serialnumber);
$employeelogin = $res1['employeelogin'];
array_push($tmparray,$employeelogin);
$employeename = $res1['employeename'];
array_push($tmparray,$employeename);
array_push($sheet,$tmparray);
}
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="name.xlsx"');
$worksheet = $objPHPExcel->getActiveSheet();
foreach($sheet as $row => $columns) {
foreach($columns as $column => $data) {
$worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
}
}
//make first row bold
$objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>
I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.
Instead of saving it to a file, save it to php://output
Docs:
$objWriter->save('php://output');
This will send it AS-IS to the browser.
You want to add some headersDocs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xls"');
// Write file to the browser
$objWriter->save('php://output');
First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.
If you need to do that on multiple sheets, and multiple columns in each sheet, here is how you can iterate through all of them:
// Auto size columns for each worksheet
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$objPHPExcel->setActiveSheetIndex($objPHPExcel->getIndex($worksheet));
$sheet = $objPHPExcel->getActiveSheet();
$cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
/** @var PHPExcel_Cell $cell */
foreach ($cellIterator as $cell) {
$sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
}
}
The same way as you'd set the type (number format mask) after writing a value to it:
$objPHPExcel->getActiveSheet()
->getStyle('A1')
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_GENERAL
);
or
$objPHPExcel->getActiveSheet()
->getStyle('A1')
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_TEXT
);
Though "Number" isn't a valid format mask.
You can find a list of pre-defined format masks in Classes/PHPExcel/Style/NumberFormat.php or set the value to any valid Excel number format masking string.
Seems like there's a bug with applyFromArray
right now that won't accept color, but this worked for me:
$objPHPExcel
->getActiveSheet()
->getStyle('A1')
->getFill()
->getStartColor()
->setRGB('FF0000');
The solution is to set the cell style through this function:
$sheet->getStyle('A1')->getAlignment()->applyFromArray(
array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,)
);
<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, 1, "test");
$sheet->mergeCells('A1:B1');
$sheet->getStyle('A1')->getAlignment()->applyFromArray(
array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,)
);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("test.xlsx");
if($this->mng_auth->get_language()=='en')
{
$excel->getActiveSheet()->setRightToLeft(false);
}
else
{
$excel->getActiveSheet()->setRightToLeft(true);
}
$styleArray = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN,
'color' => array('argb' => '00000000'),
),
),
);
//SET property
$objPHPExcel->getActiveSheet()->getStyle('A1:M10001')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('A1:M10001')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('A1:'.chr(65+count($fields)-1).$query->num_rows())->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('A1:'.chr(65+count($fields)-1).$query->num_rows())->getAlignment()->setWrapText(true);
Complementing the coment of @Mark Baker.
Do as follow:
$titles = array('title 1', 'title 2');
$sheet = 0;
foreach($array as $value){
if($sheet > 0){
$objPHPExcel->createSheet();
$sheet = $objPHPExcel->setActiveSheetIndex($sheet);
$sheet->setTitle("$value");
//Do you want something more here
}else{
$objPHPExcel->setActiveSheetIndex(0)->setTitle("$value");
}
$sheet++;
}
This worked for me. And hope it works for those who need! :)
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
Following on from Naresh's answer, dynamic polymorphism is only 'dynamic' in Java because of the presence of the virtual machine and its ability to interpret the code at run time rather than the code running natively.
In C++ it must be resolved at compile time if it is being compiled to a native binary using gcc, obviously; however, the runtime jump and thunk in the virtual table is still referred to as a 'lookup' or 'dynamic'. If C inherits B, and you declare B* b = new C(); b->method1();
, b will be resolved by the compiler to point to a B object inside C (for a simple class inherits a class situation, the B object inside C and C will start at the same memory address so nothing is required to be done; it will be pointing at the vptr that they both use). If C inherits B and A, the virtual function table of the A object inside C entry for method1 will have a thunk which will offset the pointer to the start of the encapsulating C object and then pass it to the real A::method1() in the text segment which C has overridden. For C* c = new C(); c->method1()
, c will be pointing to the outer C object already and the pointer will be passed to C::method1() in the text segment. Refer to: http://www.programmersought.com/article/2572545946/
In java, for B b = new C(); b.method1();
, the virtual machine is able to dynamically check the type of the object paired with b and can pass the correct pointer and call the correct method. The extra step of the virtual machine eliminates the need for virtual function tables or the type being resolved at compile time, even when it could be known at compile time. It's just a different way of doing it which makes sense when a virtual machine is involved and code is only compiled to bytecode.
As Kristian has pointed out, good control over z-values will often solve your problems.
If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.
I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:
box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;
This will give you some control over the "amount" of shadow in each direction.
Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.
Hope this was what you were looking for!
I personally use the Jackson module for Kotlin that you can find here: jackson-module-kotlin.
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:$version"
As an example, here is the code to parse the JSON of the Path of Exile skilltree which is quite heavy (84k lines when formatted) :
Kotlin code:
package util
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.*
import java.io.File
data class SkillTreeData( val characterData: Map<String, CharacterData>, val groups: Map<String, Group>, val root: Root,
val nodes: List<Node>, val extraImages: Map<String, ExtraImage>, val min_x: Double,
val min_y: Double, val max_x: Double, val max_y: Double,
val assets: Map<String, Map<String, String>>, val constants: Constants, val imageRoot: String,
val skillSprites: SkillSprites, val imageZoomLevels: List<Int> )
data class CharacterData( val base_str: Int, val base_dex: Int, val base_int: Int )
data class Group( val x: Double, val y: Double, val oo: Map<String, Boolean>?, val n: List<Int> )
data class Root( val g: Int, val o: Int, val oidx: Int, val sa: Int, val da: Int, val ia: Int, val out: List<Int> )
data class Node( val id: Int, val icon: String, val ks: Boolean, val not: Boolean, val dn: String, val m: Boolean,
val isJewelSocket: Boolean, val isMultipleChoice: Boolean, val isMultipleChoiceOption: Boolean,
val passivePointsGranted: Int, val flavourText: List<String>?, val ascendancyName: String?,
val isAscendancyStart: Boolean?, val reminderText: List<String>?, val spc: List<Int>, val sd: List<String>,
val g: Int, val o: Int, val oidx: Int, val sa: Int, val da: Int, val ia: Int, val out: List<Int> )
data class ExtraImage( val x: Double, val y: Double, val image: String )
data class Constants( val classes: Map<String, Int>, val characterAttributes: Map<String, Int>,
val PSSCentreInnerRadius: Int )
data class SubSpriteCoords( val x: Int, val y: Int, val w: Int, val h: Int )
data class Sprite( val filename: String, val coords: Map<String, SubSpriteCoords> )
data class SkillSprites( val normalActive: List<Sprite>, val notableActive: List<Sprite>,
val keystoneActive: List<Sprite>, val normalInactive: List<Sprite>,
val notableInactive: List<Sprite>, val keystoneInactive: List<Sprite>,
val mastery: List<Sprite> )
private fun convert( jsonFile: File ) {
val mapper = jacksonObjectMapper()
mapper.configure( DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true )
val skillTreeData = mapper.readValue<SkillTreeData>( jsonFile )
println("Conversion finished !")
}
fun main( args : Array<String> ) {
val jsonFile: File = File( """rawSkilltree.json""" )
convert( jsonFile )
JSON (not-formatted): http://filebin.ca/3B3reNQf3KXJ/rawSkilltree.json
Given your description, I believe it matches your needs.
How did you configure networking when you created the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc.
Check your .gitignore
file. You may find that the file, or extension of the file, or path to the file you are trying to work with matches an entry in .gitignore
, which would explain why that file is being ignored (and not recognized as a changed file).
This turned out to be the case for me when I had a similar problem.
Does this work for you?
string1.indexOf(string2) >= 0
Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.
Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.
You could try something like this in javascript:
var regex = /[^a-zA-Z]/g;
and have a keyup event.
$("#nameofInputbox").value.replace(regex, "");
Same happened to me after I changed computer name. To fix that, just locate listener.ora file and replace old computer name with the new one
Agreed with @Muhammad Saqib here: https://stackoverflow.com/a/46183706/2496464
And @Mumair give a good starting steps: https://stackoverflow.com/a/35411378/474330
It is always safe to assume that everything you distribute to your user's device, belong to the user. Plain and simple. You may be able to use the latest tools and procedure to encrypt your intellectual properties but there is no way to prevent a determined person from 'studying' your system. And even if the current technology may make it difficult for them to gain unwanted access, there might be some easy way tomorrow, or even just the next hour!
Thus, here comes the equation:
When it comes to money, we always assume that client is untrusted.
Even in as simple as an in-game economy. (Especially in games! There are more 'sophisticated' users there and loopholes spread in seconds!)
How do we stay safe?
Most, if not all, of our key processing systems (and database of course) located on the server side. And between the client and server, lies encrypted communications, validations, etc. That is the idea of thin client.
I have tried to rename the repository on the web page:
setting
, click it and then you can find the Repositories
under the Personal setting
. Repositories
and enter your directories of Repositories, choose the Repository that you want to rename. setting
is added to the top line, just click it and enter the new name then click Rename
. Done, so easy.
You can create folder using the following Java code:
File dir = new File("nameoffolder");
dir.mkdir();
By executing above you will have folder 'nameoffolder' in current folder.
For no InnoDB solution: you can use a procedure
don't forgot to set the delimiter for storing the procedure with ;
CREATE PROCEDURE myproc(OUT id INT, IN otherid INT, IN title VARCHAR(255))
BEGIN
LOCK TABLES `table1` WRITE;
INSERT INTO `table1` ( `title` ) VALUES ( @title );
SET @id = LAST_INSERT_ID();
UNLOCK TABLES;
INSERT INTO `table2` ( `parentid`, `otherid`, `userid` ) VALUES (@id, @otherid, 1);
END
And you can use it...
SET @myid;
CALL myproc( @myid, 1, "my title" );
SELECT @myid;
You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:
ErrorDocument 404 /index.php
An error page redirect must be relative to root so you cannot use www.mydomain.com.
If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.
Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
You can also use the day ordinal to make it simpler:
def date_range(start_date, end_date):
for ordinal in range(start_date.toordinal(), end_date.toordinal()):
yield datetime.date.fromordinal(ordinal)
Or as suggested in the comments you can create a list like this:
date_range = [
datetime.date.fromordinal(ordinal)
for ordinal in range(
start_date.toordinal(),
end_date.toordinal(),
)
]
I think intellij is the best option for android. i have used both eclipse and intellij and found intellij is much easier to use with android as compared to eclipse because of these reasons :-
Intellij provides a built-in support for android and you don't have to configure it as you need to do with eclipse. Intellij gives you auto-lookup feature which is really important for developer like us to increase our productivity. And if we talk about eclipse you have to type each and every method, classname etc on your own. (May be eclipse has this feature too but i never found it and trust me i tried to find it like anything) Its much more user friendly and easy to use than eclipse. I hope it will help you and other members of stack overflow to decide which IDE is best for Android development.
My personal choice is Intellij.
EDIT
But there is one thing i love about eclipse and that is visual layout creator. You can use drag and drop technique to create a layout and eclipse will automatically generate an XML file for you just like XCODE.
EDIT
Good News!! Intellij added a new feature which shows how your app's view is going to look like. It doesn't work exactly like Eclipse but it will give you a good idea about your layout.
My personal choice is still Intellij because it helps me to type faster than eclipse.
EDIT
Ok guys these days i am using eclipse juno and found its kind of buggy and slow. So if you still want to use eclipse better stick to some older version. And finally i am able to found how to enable auto-complete in eclipse. Below is a small tutorial.
Eclipse -> Preference - > Java -> Editor -> Content Assist -> Auto Activation
Now put following in the three given boxes
Auto Activation delay(ms) - 0
Auto activation triggers for java - .(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Auto activation triggers for javadoc - @#
You are now good to go. Happy coding.
EDIT
As now Google has adopted Intellij for their own Android dev tool, there is no question now about which one is better. Intellij is far far better than eclipse. And i switched back to Intellij and it feels like i am back home!! :D
The way to enable to switch from you regular to the root user (AKA “super user”) after authentificating with your Google Computer Engine (GCE) User in the local environment (your Linux server in GCE) is pretty straight forward, in fact it just involves just one command to enable it and another every time to use it:
$ sudo passwd
Enter the new UNIX password: <your new root password>
Retype the new UNIX password: <your new root password>
passwd: password updated successfully
After executing the previous command and once logged with your GCE User you will be able to switch to root anytime by just entering the following command:
$ su
Password: <your newly created root password>
root@intance:/#
As we say in economics “caveat emptor” or buyer be aware: Using the root user is far from a best practice in system’s administration. Using it can be the cause a lot of trouble, from wiping everything in your drives and boot disks without a hiccup to many other nasty stuff that would be laborious to backtrack, troubleshoot and rebuilt. On the other hand, I have never met a SysAdmin that doesn’t think he knows better and root more than he should.
REMEMBER: We humans are programmed in such a way that given enough time at one at some point or another are going to press enter without taking into account that we have escalated to root and I can assure you that it will great source of pain, regret and extra work. PLEASE USE ROOT PRIVILEGES SPARSELY AND WITH EXTREME CARE.
Having said all the boring stuff, Have fun, live on the edge, life is short, you only get to live it once, the more you break the more you learn.
I tried this command to display the list of files in the directory.
dir /s /b > List.txt
In the file it displays the list below.
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll
What is want to do is only to display sub-directory not the full directory path.
Just like this:
Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll
Cisco Jabber\accessories\JabraJabberPlugin.dll
Cisco Jabber\accessories\Logitech
Cisco Jabber\accessories\Plantronics
Cisco Jabber\accessories\SennheiserJabberPlugin.dll
If the table is already created in the database, then you can add a unique constraint later on by using this SQL query:
ALTER TABLE dbo.User
ADD CONSTRAINT ucCodes UNIQUE (fcode, scode, dcode)
Actually, I use both variants.
There are situations, where you first check for the validity of a pointer, and if it is NULL, you just return/exit out of a function. (I know this can lead to the discussion "should a function have only one exit point")
Most of the time, you check the pointer, then do what you want and then resolve the error case. The result can be the ugly x-times indented code with multiple if's.
If you have access to SRV Records, you can use them to get what you want :)
E.G
A Records
Name: mc1.domain.com
Value: <yourIP>
Name: mc2.domain.com
Value: <yourIP>
SRV Records
Name: _minecraft._tcp.mc1.domain.com
Priority: 5
Weight: 5
Port: 25565
Value: mc1.domain.com
Name: _minecraft._tcp.mc2.domain.com
Priority: 5
Weight: 5
Port: 25566
Value: mc2.domain.com
then in minecraft you can use
mc1.domain.com which will sign you into server 1 using port 25565
and
mc2.domain.com which will sign you into server 2 using port 25566
then on your router you can have it point 25565 and 25566 to the machine with both servers on and Voilà!
Source: This works for me running 2 minecraft servers on the same machine with ports 50500 and 50501
Same thing but in ANSI way
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME IN ( SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'CreateDate' )
Currently (July 2015), HTML escape sequences (• •
) do not work in browser version of Play Store, they're displayed as text. Though, Play Store app handles them as expected.
So, if you're after the unicode bullet point in your app/update description [that's what's got you here, most likely], just copy-paste the bullet character
PS You can also use unicode input combo to get the character
Linux: CtrlShiftu 2022
Enter or Space
Mac: Hold ? 2022
release ?
Windows: Hold Alt 2022
release Alt
Mac and Windows require some setup, read on Wikipedia
PPS If you're feeling creative, here's a good link with more copypastable symbols, but don't go too crazy, nobody likes clutter in what they read.
There are 3 sources of variables in Ansible:
Variables gathered from facts. You can get them by running command: ansible -m setup hostname
Built-in (pre-defined) Ansible variables (AKA 'magic' variables). They are documented in Ansible documentation: http://docs.ansible.com/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts
Here is the list extracted from Ansible 1.9 documentation:
You can fill it from XAML or from .cs. There are few ways to fill controls with data. It would be best for You to read more about WPF technology, it allows to do many things in many ways, depending on Your needs. It's more important to choose method based on Your project needs. You can start here. It's an easy article about creating combobox, and filling it with some data.
Not surprisingly, this error can arise when another process is listening on the desired port. This happened today when I started an instance of the Apache Web server, listening on its default port (80), having forgotten that I already had IIS 7 running, and listening on that port. This is well explained in Port 80 is being used by SYSTEM (PID 4), what is that? Better yet, that article points to Stop http.sys from listening on port 80 in Windows, which explains a very simple way to resolve it, with just a tad of help from an elevated command prompt and a one-line edit of my hosts file.
The solution we came to having a state that took 2 parameters was changing:
.state('somestate', {
url: '/somestate',
views: {...}
}
to
.state('somestate', {
url: '/somestate?id=:&sub=:',
views: {...}
}
Looking at my system's menu.vim (look for 'Color Scheme submenu') and @chappar's answer, I came up with the following function:
" Returns the list of available color schemes
function! GetColorSchemes()
return uniq(sort(map(
\ globpath(&runtimepath, "colors/*.vim", 0, 1),
\ 'fnamemodify(v:val, ":t:r")'
\)))
endfunction
It does the following:
Then to use the function I do something like this:
let s:schemes = GetColorSchemes()
if index(s:schemes, 'solarized') >= 0
colorscheme solarized
elseif index(s:schemes, 'darkblue') >= 0
colorscheme darkblue
endif
Which means I prefer the 'solarized' and then the 'darkblue' schemes; if none of them is available, do nothing.
I've written a fairly comprehensive article about this very topic and also developed a pop-in library for MVVM Dialogs. Strict adherence to MVVM is not only possible but very clean when implemented properly, and it can be easily extended to third-party libraries that don't adhere to it themselves:
https://www.codeproject.com/Articles/820324/Implementing-Dialog-Boxes-in-MVVM
I had the same issue and unloading and reloading problematic project helped me to clear out this issue for ReSharper. Hope this helps.
Int to byte and vice versa.
unsigned char bytes[4];
unsigned long n = 1024;
bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;
printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);
int num = 0;
for(int i = 0; i < 4; i++)
{
num <<= 8;
num |= bytes[i];
}
printf("number %d",num);
Make sure you have Internet Connection then:
1.For Window Users Go to > C:\Users\username\.gradle\wrapper\dists
2.For Linux users
Go to $HOME/.gradle (~/.gradle)
and/or (Under Specific project)
<PROJECT_DIR>/.gradle
3.Delete the gradle file(s) with the problem(i.e the zipped folders with missing with no its extracted file )
4.Sync the project with gradle files.
From the firebug site http://getfirebug.com/logging/
Calling console.dir(object) will log an interactive listing of an object's properties, like > a miniature version of the DOM tab.
Here is a fairly straightforward message that uses the split
method from pandas str
accessor and then uses NumPy to flatten each row into a single array.
The corresponding values are retrieved by repeating the non-split column the correct number of times with np.repeat
.
var1 = df.var1.str.split(',', expand=True).values.ravel()
var2 = np.repeat(df.var2.values, len(var1) / len(df))
pd.DataFrame({'var1': var1,
'var2': var2})
var1 var2
0 a 1
1 b 1
2 c 1
3 d 2
4 e 2
5 f 2
@Shoban It looks like the question is tagged c# so here is the appropriate snipped http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx
public MyClass()
{
// Create a new DateTimePicker
DateTimePicker dateTimePicker1 = new DateTimePicker();
Controls.Add(dateTimePicker1);
MessageBox.Show(dateTimePicker1.Value.ToString());
dateTimePicker1.Value = DateTime.Now.AddDays(1);
MessageBox.Show(dateTimePicker1.Value.ToString());
}
I've reformulated the great routine proposed by Bill to make it more universal:
void printMe ()
{
int i = 1;
startPrintMe:
printf ("%d\n", i);
void *labelPtr = &&startPrintMe + (&&exitPrintMe - &&startPrintMe) * (i++ / 1000);
goto *labelPtr;
exitPrintMe:
}
UPDATE: The second approach needs 2 functions:
void exitMe(){}
void printMe ()
{
static int i = 1; // or 1001
i = i * !!(1001 - i) + !(1001 - i); // makes function reusable
printf ("%d\n", i);
(typeof(void (*)())[]){printMe, exitMe} [!(1000-i++)](); // :)
}
For both cases you can initiate printing by simply calling
printMe();
Has been tested for GCC 4.2.
Yes its possible! and you can use as many colors and images as you desire, here is the right way:
body{_x000D_
/* Its, very important to set the background repeat to: no-repeat */_x000D_
background-repeat:no-repeat; _x000D_
_x000D_
background-image: _x000D_
/* 1) An image */ url(http://lorempixel.com/640/100/nature/John3-16/), _x000D_
/* 2) Gradient */ linear-gradient(to right, RGB(0, 0, 0), RGB(255, 255, 255)), _x000D_
/* 3) Color(using gradient) */ linear-gradient(to right, RGB(110, 175, 233), RGB(110, 175, 233));_x000D_
_x000D_
background-position:_x000D_
/* 1) Image position */ 0 0, _x000D_
/* 2) Gradient position */ 0 100px,_x000D_
/* 3) Color position */ 0 130px;_x000D_
_x000D_
background-size: _x000D_
/* 1) Image size */ 640px 100px,_x000D_
/* 2) Gradient size */ 100% 30px, _x000D_
/* 3) Color size */ 100% 30px;_x000D_
}
_x000D_
In case anyone needed the above in swift :
SWIFT 3.0 and above :
this will capitalize your string, make the first letter capital :
viewNoteDateMonth.text = yourString.capitalized
this will uppercase your string, make all the string upper case :
viewNoteDateMonth.text = yourString.uppercased()
NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];
I make a (sub)folder named "hide", move the file I don't want committed to there. Then do my commit, ignoring complaint about the missing file. Then move the hidden file from hide back to ./
I know of no downside to this tactic.
Short answer: I think tgbaggio is right. You hit HDFS throughput limits on your executors.
I think the answer here may be a little simpler than some of the recommendations here.
The clue for me is in the cluster network graph. For run 1 the utilization is steady at ~50 M bytes/s. For run 3 the steady utilization is doubled, around 100 M bytes/s.
From the cloudera blog post shared by DzOrd, you can see this important quote:
I’ve noticed that the HDFS client has trouble with tons of concurrent threads. A rough guess is that at most five tasks per executor can achieve full write throughput, so it’s good to keep the number of cores per executor below that number.
So, let's do a few calculations see what performance we expect if that is true.
If the job is 100% limited by concurrency (the number of threads). We would expect runtime to be perfectly inversely correlated with the number of threads.
ratio_num_threads = nthread_job1 / nthread_job3 = 15/24 = 0.625
inv_ratio_runtime = 1/(duration_job1 / duration_job3) = 1/(50/31) = 31/50 = 0.62
So ratio_num_threads ~= inv_ratio_runtime
, and it looks like we are network limited.
This same effect explains the difference between Run 1 and Run 2.
Comparing the number of effective threads and the runtime:
ratio_num_threads = nthread_job2 / nthread_job1 = 12/15 = 0.8
inv_ratio_runtime = 1/(duration_job2 / duration_job1) = 1/(55/50) = 50/55 = 0.91
It's not as perfect as the last comparison, but we still see a similar drop in performance when we lose threads.
Now for the last bit: why is it the case that we get better performance with more threads, esp. more threads than the number of CPUs?
A good explanation of the difference between parallelism (what we get by dividing up data onto multiple CPUs) and concurrency (what we get when we use multiple threads to do work on a single CPU) is provided in this great post by Rob Pike: Concurrency is not parallelism.
The short explanation is that if a Spark job is interacting with a file system or network the CPU spends a lot of time waiting on communication with those interfaces and not spending a lot of time actually "doing work". By giving those CPUs more than 1 task to work on at a time, they are spending less time waiting and more time working, and you see better performance.
In the version 3.2.4 of the XAMPP Control Panel, there is button that can open a command line prompt (red rectangle in the next figure)
After pressing the button, you will see the command prompt window.
From this window you can navigate through the different folders and start the different services available.
Your results will not be helpful unless the arrays are first sorted. To sort an array, run it through Sort-Object.
$x = @(5,1,4,2,3)
$y = @(2,4,6,1,3,5)
Compare-Object -ReferenceObject ($x | Sort-Object) -DifferenceObject ($y | Sort-Object)
As delnan pointed out, the match
keyword in Scala has nothing to do with regexes. To find out whether a string matches a regex, you can use the String.matches
method. To find out whether a string starts with an a, b or c in lower or upper case, the regex would look like this:
word.matches("[a-cA-C].*")
You can read this regex as "one of the characters a, b, c, A, B or C followed by anything" (.
means "any character" and *
means "zero or more times", so ".*" is any string).
as per docs:
The current thread must own this object's monitor. The thread releases ownership of this monitor.
wait()
method simply means it releases the lock on the object. So the object will be locked only within the synchronized block/method. If thread is outside the sync block means it's not locked, if it's not locked then what would you release on the object?
You also can locate all features inside a FeatureGroup or all the featureGroups, see how it works!
//Group1_x000D_
m1=L.marker([7.11, -70.11]);_x000D_
m2=L.marker([7.33, -70.33]);_x000D_
m3=L.marker([7.55, -70.55]);_x000D_
fg1=L.featureGroup([m1,m2,m3]);_x000D_
_x000D_
//Group2_x000D_
m4=L.marker([3.11, -75.11]);_x000D_
m5=L.marker([3.33, -75.33]);_x000D_
m6=L.marker([3.55, -75.55]);_x000D_
fg2=L.featureGroup([m4,m5,m6]);_x000D_
_x000D_
//BaseMap_x000D_
baseLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');_x000D_
var map = L.map('map', {_x000D_
center: [3, -70],_x000D_
zoom: 4,_x000D_
layers: [baseLayer, fg1, fg2]_x000D_
});_x000D_
_x000D_
//locate group 1_x000D_
function LocateOne() {_x000D_
LocateAllFeatures(map, fg1);_x000D_
}_x000D_
_x000D_
function LocateAll() {_x000D_
LocateAllFeatures(map, [fg1,fg2]);_x000D_
}_x000D_
_x000D_
//Locate the features_x000D_
function LocateAllFeatures(iobMap, iobFeatureGroup) {_x000D_
if(Array.isArray(iobFeatureGroup)){ _x000D_
var obBounds = L.latLngBounds();_x000D_
for (var i = 0; i < iobFeatureGroup.length; i++) {_x000D_
obBounds.extend(iobFeatureGroup[i].getBounds());_x000D_
}_x000D_
iobMap.fitBounds(obBounds); _x000D_
} else {_x000D_
iobMap.fitBounds(iobFeatureGroup.getBounds());_x000D_
}_x000D_
}
_x000D_
.mymap{_x000D_
height: 300px;_x000D_
width: 100%;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>_x000D_
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>_x000D_
_x000D_
<div id="map" class="mymap"></div>_x000D_
<button onclick="LocateOne()">locate group 1</button>_x000D_
<button onclick="LocateAll()">locate All</button>
_x000D_
PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn
which will show the process names (but must be run under an administrator account).
Having said that, I would expect the find "8080"
to find it...
Another thing to do is just visit http://localhost:8080
- on that port, chances are it's a web server of some description.
If you have changed data directory (the path to the database root in my.ini) to an external hard drive, make sure that the hard drive is connected.
Because string
is defined in the namespace std
. Replace string
with std::string
, or add
using std::string;
below your include
lines.
It probably works in main.cpp
because some other header has this using
line in it (or something similar).
Configuration
The styles and scripts options in your angular.json configuration now allow to reference a package directly:
before: "styles": ["../node_modules/bootstrap/dist/css/bootstrap.css"]
after: "styles": ["bootstrap/dist/css/bootstrap.css"]
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ng6",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css","bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"jquery/dist/jquery.min.js",
"bootstrap/dist/js/bootstrap.min.js"
]
},
Angular v6 Onwards
CLI projects in angular 6 onwards will be using angular.json
instead of .angular-cli.json
for build and project configuration.
Each CLI workspace has projects, each project has targets, and each target can have configurations.Docs
. {
"projects": {
"my-project-name": {
"projectType": "application",
"architect": {
"build": {
"configurations": {
"production": {},
"demo": {},
"staging": {},
}
},
"serve": {},
"extract-i18n": {},
"test": {},
}
},
"my-project-name-e2e": {}
},
}
OPTION-1
execute npm install bootstrap@4 jquery --save
The JavaScript parts of Bootstrap
are dependent on jQuery
. So you need the jQuery
JavaScript
library file too.
In your angular.json add the file paths to the styles and scripts array in under build
target
NOTE:
Before v6 the Angular CLI project configuration was stored in <PATH_TO_PROJECT>/.angular-cli.json.
As of v6 the location of the file changed to angular.json.
Since there is no longer a leading dot, the file is no longer hidden by default and is on the same level.
which also means that file paths in angular.json should not contain leading dots and slash
i.e you can provide an absolute path instead of a relative path
In .angular-cli.json
file Path was "../node_modules/"
In angular.json
it is "node_modules/"
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ng6",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css","node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": ["node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"]
},
OPTION 2
Add files from CDN (Content Delivery Network) to your project CDN LINK
Open file src/index.html and insert
the <link>
element at the end of the head section to include the Bootstrap CSS file
a <script>
element to include jQuery at the bottom of the body section
a <script>
element to include Popper.js at the bottom of the body section
a <script>
element to include the Bootstrap JavaScript file at the bottom of the body section
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<app-root>Loading...</app-root>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
OPTION 3
Execute npm install bootstrap
In src/styles.css
add the following line:
@import "~bootstrap/dist/css/bootstrap.css";
OPTION-4
ng-bootstrap It contains a set of native Angular directives based on Bootstrap’s markup and CSS. As a result, it's not dependent on jQuery or Bootstrap’s JavaScript
npm install --save @ng-bootstrap/ng-bootstrap
After Installation import it in your root module and register it in @NgModule
imports` array
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [AppComponent, ...],
imports: [NgbModule.forRoot(), ...],
bootstrap: [AppComponent]
})
NOTE
ng-bootstrap
requires Bootstrap's 4 css to be added in your project. you need to Install it explicitly via:
npm install bootstrap@4 --save
In your angular.json add the file paths to the styles array in under build
target
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
You cant set links to "disabled" just system elements like input, textfield etc.
But you can disable links with jQuery/JavaScript
$('.disabled').click(function(e){
e.preventDefault();
});
Just wrap the above code in whatever event you want to disable the links.
Other answers may have shorter code but this one should be the most efficient and is easy to understand.
/**
* Get key of the max value
*
* @var array $array
* @return mixed
*/
function array_key_max_value($array)
{
$max = null;
$result = null;
foreach ($array as $key => $value) {
if ($max === null || $value > $max) {
$result = $key;
$max = $value;
}
}
return $result;
}
According to maven's Guide to installing 3rd party JARs, the command is:
mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>
You need indeed the packaging option. This answers the original question.
Now, in your context, you are fighting with a jar provided by Sun. You should read the Coping with Sun JARs page too. There, you'll learn how to help maven to provide you better information about Sun jars location and how to add Java.net Maven 2 repository which contains jta-1.0.1B.jar
. Add this in your settings.xml
(not portable) orpom.xml
(portable):
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
I may have not got your answer correct, but you can try this:
public void MusicController(View view) throws IOException{
switch (view.getId()){
case R.id.play: mplayer.start();break;
case R.id.pause: mplayer.pause(); break;
case R.id.stop:
if(mplayer.isPlaying()) {
mplayer.stop();
mplayer.prepare();
}
break;
}// where mplayer is defined in onCreate method}
as there is just one thread handling all, so stop() makes it die so we have to again prepare it If your intent is to start it again when your press start button(it throws IO Exception) Or for better understanding of MediaPlayer you can refer to Android Media Player
</script>
has to be broken up because otherwise it would end the enclosing <script></script>
block too early. Really it should be split between the <
and the /
, because a script block is supposed (according to SGML) to be terminated by any end-tag open (ETAGO) sequence (i.e. </
):
Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "
</
" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.
However in practice browsers only end parsing a CDATA script block on an actual </script>
close-tag.
In XHTML there is no such special handling for script blocks, so any <
(or &
) character inside them must be &escaped;
like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:
<script type="text/javascript">
document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>
I can't imagine everyone uses all 20 different keypresses to navigate text, 10 or so keys to start adding text, and 18 ways to visually select an inner block. Or do you!?
I do.
In theory, once I have that and start becoming as proficient in VIM as I am in Textmate, then I can start learning the thousands of other VIM commands that will make me more efficient.
That's the right way to do it. Start with basic commands and then pick up ones that improve your productivity. I like following this blog for tips on how to improve my productivity with vim.
Ideally, Windows authentication must be used when working in an Intranet type of an environment.
Whereas, SQL Server authentication can be used in all the other type of cases.
Here is a link which might help.
In case anybody is looking for methods to convert from/to C# and SQL Server formats, here goes a simple implementation:
private readonly string[] SqlServerTypes = { "bigint", "binary", "bit", "char", "date", "datetime", "datetime2", "datetimeoffset", "decimal", "filestream", "float", "geography", "geometry", "hierarchyid", "image", "int", "money", "nchar", "ntext", "numeric", "nvarchar", "real", "rowversion", "smalldatetime", "smallint", "smallmoney", "sql_variant", "text", "time", "timestamp", "tinyint", "uniqueidentifier", "varbinary", "varchar", "xml" };
private readonly string[] CSharpTypes = { "long", "byte[]", "bool", "char", "DateTime", "DateTime", "DateTime", "DateTimeOffset", "decimal", "byte[]", "double", "Microsoft.SqlServer.Types.SqlGeography", "Microsoft.SqlServer.Types.SqlGeometry", "Microsoft.SqlServer.Types.SqlHierarchyId", "byte[]", "int", "decimal", "string", "string", "decimal", "string", "Single", "byte[]", "DateTime", "short", "decimal", "object", "string", "TimeSpan", "byte[]", "byte", "Guid", "byte[]", "string", "string" };
public string ConvertSqlServerFormatToCSharp(string typeName)
{
var index = Array.IndexOf(SqlServerTypes, typeName);
return index > -1
? CSharpTypes[index]
: "object";
}
public string ConvertCSharpFormatToSqlServer(string typeName)
{
var index = Array.IndexOf(CSharpTypes, typeName);
return index > -1
? SqlServerTypes[index]
: null;
}
Edit: fixed typo
Instead of explaining it with words, here's an example. This is a Scheme version of the factorial function:
(define (factorial x)
(if (= x 0) 1
(* x (factorial (- x 1)))))
Here is a version of factorial that is tail-recursive:
(define factorial
(letrec ((fact (lambda (x accum)
(if (= x 0) accum
(fact (- x 1) (* accum x))))))
(lambda (x)
(fact x 1))))
You will notice in the first version that the recursive call to fact is fed into the multiplication expression, and therefore the state has to be saved on the stack when making the recursive call. In the tail-recursive version there is no other S-expression waiting for the value of the recursive call, and since there is no further work to do, the state doesn't have to be saved on the stack. As a rule, Scheme tail-recursive functions use constant stack space.
The correct answer is THERE IS NO OVERLOADING IN JAVASCRIPT.
Checking / Switching inside the function is not OVERLOADING.
The concept of overloading: In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.
For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.
https://en.wikipedia.org/wiki/Function_overloading
All suggested implementations are great, but truth to be told, there is no native implementation for JavaScript.
Provide the :name
option to add_index
, e.g.:
add_index :studies,
["user_id", "university_id", "subject_name_id", "subject_type_id"],
unique: true,
name: 'my_index'
If using the :index
option on references
in a create_table
block, it takes the same options hash as add_index
as its value:
t.references :long_name, index: { name: :my_index }
In order to comply with boneheaded precedent, getYear()
returns the number of years since 1900.
Instead, you should call getFullYear()
, which returns the actual year.
If you want first 2 letters and last 2 letters of a string then you can use the following code:
name = "India"
name[0:2]="In"
names[-2:]="ia"
You can use this for your purpose.
In parent form:
private void addCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
CustomerPage f = new CustomerPage();
f.LoadType = 1;
f.MdiParent = this;
f.Show();
f.Focus();
}
In child form:
public int LoadType{get;set;}
private void CustomerPage_Load(object sender, EventArgs e)
{
if (LoadType == 1)
{
this.button1.Visible = false;
}
}
The find
command may help
find $PWD -name ex*
find $PWD -name example.log
Lists all the files in or below the current directory with names matching the pattern. You can simplify it if you will only get a few results (e.g. directory near bottom of tree containing few files), just
find $PWD
I use this on Solaris 10, which doesn't have the other utilities mentioned.
If a process has a lock on an SQLite DB and crashes, the DB stays locked permanently. That's the problem. It's not that some other process has a lock.
You need to load it from resource stream.
Bitmap bmp = new Bitmap(
System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceStream("MyProject.Resources.myimage.png"));
If you want to know all resource names in your assembly, go with:
string[] all = System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceNames();
foreach (string one in all) {
MessageBox.Show(one);
}
Use the TextBox's Exit
event handler:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Logincode_Click
End Sub
Answer from official website
https://datatables.net/reference/option/columns.width
$('#example').dataTable({
"columnDefs": [
{
"width": "20%",
"targets": 0
}
]
});
This error would occur if any of the following variables were actually strings or null instead of arrays, in which case accessing them with an array syntax $var[$i]
would be like trying to access a specific character in a string:
$catagory
$task
$fullText
$dueDate
$empId
In short, everything in your insert query.
Perhaps the $catagory
variable is misspelled?
For some reason, using a shared machine, I couldn`t figure out where this proxy properties is comming from.
So a workaround to fix this is add in you project gradle.properties the following (empty properties). So It will override top hierarchy configuration:
systemProp.http.proxyPort=
systemProp.http.proxyUser=
systemProp.http.proxyPassword=
systemProp.https.proxyPassword=
systemProp.https.proxyHost=
systemProp.http.proxyHost=
systemProp.https.proxyPort=
systemProp.https.proxyUser=
Non-inherited elements must have default styles set.
If parent class set color:white
and font-weight:bold
style then no inherited child must set 'color:black' and font-weight: normal
in their class. If style
is not set, elements get their style from their parents.
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Stopwatch {
static int interval;
static Timer timer;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input seconds => : ");
String secs = sc.nextLine();
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = Integer.parseInt(secs);
System.out.println(secs);
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
}
private static final int setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}
}
Try this.
You're looking for things like the haversine formula. See here as well.
There's other ones but this is the most commonly cited.
If you're looking for something even more robust, you might want to look at your databases GIS capabilities. They're capable of some cool things like telling you whether a point (City) appears within a given polygon (Region, Country, Continent).
Pure js alternative to window.open
let a= document.createElement('a');
a.target= '_blank';
a.href= 'https://support.wwf.org.uk/';
a.click();
here is working example (stackoverflow snippets not allow to opening)
one kind of join a query in mongoDB, is ask at one collection for id that match , put ids in a list (idlist) , and do find using on other (or same) collection with $in : idlist
u = db.friends.find({"friends": something }).toArray()
idlist= []
u.forEach(function(myDoc) { idlist.push(myDoc.id ); } )
db.family.find({"id": {$in : idlist} } )
There is no need to create a key and so forth if you just want to play around with it on your device.
With Eclipse:
To export an unsigned .apk from Eclipse, right-click the project in the Package Explorer and select Android Tools -> Export Unsigned Application Package. Then specify the file location for the unsigned .apk.
I had a batch of files that looked like this: be90-01.png and needed to change the dash to underscore. I used this, which worked well:
for f in *; do mv "$f" "`echo $f | tr '-' '_'`"; done
We had the same issue, in making a websocket connection to the Load Balancer. The issue is in LB, accepting http connection on port 80 and forwarding the request to node (tomcat app on port 8080). We have changed this to accept tcp (http has been changed as 'tcp') connection on port 80. So the first handshake request is forwarded to Node and a websocket connection is made successfully on some random( as far as i know, may be wrong) port.
below command has been used to test the websocket handshake process.
curl -v -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost" -H "Origin: http://LB URL:80" http://LB URL
GET / HTTP/1.1 Host: localhost User-Agent: curl/7.60.0 Accept: / Connection: Upgrade Upgrade: websocket Origin: http://LB URL:80
here's the best of both worlds.
I also "like" underscores, besides all your positive points about them, there is also a certain old-school style to them.
So what I do is use underscores and simply add a small rewrite rule to your Apache's .htaccess file to re-write all underscores to hyphens.
You can use the logical 'OR' operator in place of the Elvis operator:
For example displayname = user.name || "Anonymous"
.
But Javascript currently doesn't have the other functionality. I'd recommend looking at CoffeeScript if you want an alternative syntax. It has some shorthand that is similar to what you are looking for.
For example The Existential Operator
zip = lottery.drawWinner?().address?.zipcode
Function shortcuts
()-> // equivalent to function(){}
Sexy function calling
func 'arg1','arg2' // equivalent to func('arg1','arg2')
There is also multiline comments and classes. Obviously you have to compile this to javascript or insert into the page as <script type='text/coffeescript>'
but it adds a lot of functionality :) . Using <script type='text/coffeescript'>
is really only intended for development and not production.
If anyone wonders for the Array
version, it goes like this:
int i = Array.FindIndex(yourArray, x => x == itemYouWant);
Your web server isn't running! You need to find the XAMPP control panel and start the web server up.
Of course, you might find other problems after that, but this is the first step.
TLDR; Here's why:
The reason this works is because
gulp
tries to run yourgulpfile.js
using your locally installed version ofgulp
, see here. Hence the reason for a global and local install of gulp.
Essentially, when you install gulp
locally the script isn't in your PATH
and so you can't just type gulp
and expect the shell to find the command. By installing it globally the gulp
script gets into your PATH
because the global node/bin/
directory is most likely on your path.
To respect your local dependencies though, gulp
will use your locally installed version of itself to run the gulpfile.js
.
In the future (perhaps) you will be able to use :nth-child(an+b of s)
Actually, browser support for the “of” filter is very limited. Only Safari seems to support the syntax.
If you don't want to use external libs, then one solution is to recreate the reload method from python 2 for python 3 as below. Use this in the top of the module (assumes python 3.4+).
import sys
if(sys.version_info.major>=3):
def reload(MODULE):
import importlib
importlib.reload(MODULE)
BTW reload is very much required if you use python files as config files and want to avoid restarts of the application.....
You can now do this by including the sound when building a notification rather than calling the sound separately.
//Define Notification Manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(message)
.setSound(soundUri); //This sets the sound to play
//Display notification
notificationManager.notify(0, mBuilder.build());
Others have answered the question, but just for the fun of it, here is a visual dice throwing example, using the Math.random
javascript method, a background image and some recursive timeouts.
Sometimes, this error occurs when you're trying to target an element that is wrapped in a condition, for example:
<div *ngIf="canShow"> <p #target>Targeted Element</p></div>
In this code, if canShow
is false on render, Angular won't be able to get that element as it won't be rendered, hence the error that comes up.
One of the solutions is to use a display: hidden
on the element instead of the *ngIf
so the element gets rendered but is hidden until your condition is fulfilled.
Read More over at Github
We just experienced this in SQL 2012. A replication process jumped in when we killed the original session that set it to single user. But sp_who2 did not show that new process attached to the DB. Closing SSMS and re-opening then allowed us to see this process on the database and then we could kill it and switch to multi_user mode immediately and that worked.
I can't work out the logic behind this, but it does appear to be a bug in SSMS and is still manifesting itself in SQL 2012.
I had the same error. I tried and rechecked everything. I was so focused in the Stack trace that I didn't read the last lines of the build before the Reactor summary and the stack trace:
[DEBUG] Using connector AetherRepositoryConnector with priority 3.4028235E38 for http://www:8081/nexus/content/repositories/snapshots/
[INFO] Downloading: http://www:8081/nexus/content/repositories/snapshots/com/wdsuite/com.wdsuite.server.product/1.0.0-SNAPSHOT/maven-metadata.xml
[DEBUG] Could not find metadata com.group:artifact.product:version-SNAPSHOT/maven-metadata.xml in nexus (http://www:8081/nexus/content/repositories/snapshots/)
[DEBUG] Writing tracking file /home/me/.m2/repository/com/group/project/version-SNAPSHOT/resolver-status.properties
[INFO] Uploading: http://www:8081/nexus/content/repositories/snapshots/com/...-1.0.0-20141118.124526-1.zip
[INFO] Uploading: http://www:8081/nexus/content/repositories/snapshots/com/...-1.0.0-20141118.124526-1.pom
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
This was the key : "Could not find metadata". Although it said that it was an authentication error actually it got fixed doing a "rebuild metadata" in the nexus repository.
Hope it helps.
You can also see this error when selecting for a union where corresponding columns can be null.
select * from (select D.dept_no, D.nullable_comment
from dept D
union
select R.dept_no, NULL
from redundant_dept R
)
This apparently confuses the parser, a solution is to assign a column alias to the always null column.
select * from (select D.dept_no, D.comment
from dept D
union
select R.dept_no, NULL "nullable_comment"
from redundant_dept R
)
The alias does not have to be the same as the corresponding column, but the column heading in the result is driven by the first query from among the union members, so it's probably a good practice.
Use Checked = true
$("#checkbox1").prop('checked', true);
Note: I am not clear whether you want to onclick/onchange event on checkbox. is(":checked", function(){})
is a wrong in the question.
I'll add a map and filter version because why not.
sum(map(lambda x:x>5, j))
sum(1 for _ in filter(lambda x:x>5, j))
Try this
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
This happened to me when I created the virtualenv in the wrong location. I then thought I could move the dir to another location without it mattering. It mattered.
mkdir ~/projects
virtualenv myenv
cd myenv
git clone [my repository]
Oh crap, I forgot to cd into projects
before creating the virtualenv and cloning the rep. Oh well, I'm too lazy to destroy and recreate. I'll just move the dir with no issues.
cd ~
mv myenv projects
cd projects/myenv/myrepo
pip install -r requirements
Nope, wants more permissions, what the? I thought it was strange but SUDO AWAY! It then installed the packages into a global location.
The lesson I learned was, just delete the virtualenv dir. Don't move it.
Where did you put the code in?
I try your code in my demo, I found out, if you put the code in
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
will fail, because key window have been setting yet.
But I put your code in some view controller's
override func viewDidLoad() {
It just works.
Another way based on amadan:
SELECT * FROM [Purchasing].[Vendor] WHERE
( (@url IS null OR @url = '' OR @url = 'ALL') and PurchasingWebServiceURL LIKE '%')
or
( @url = 'blank' and PurchasingWebServiceURL = '')
or
(@url = 'fail' and PurchasingWebServiceURL NOT LIKE '%treyresearch%')
or( (@url not in ('fail','blank','','ALL') and @url is not null and
PurchasingWebServiceUrl Like '%'+@ur+'%')
END
It worked for me can try with this, hope it will be helpful . Let me know if any concern .
Date startDate = java.util.Calendar.getInstance().getTime(); //set your start time
Date endDate = java.util.Calendar.getInstance().getTime(); // set your end time
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
Toast.makeText(MainActivity.this, "Diff"
+ duration + diffInDays + diffInHours + diffInMinutes + diffInSeconds, Toast.LENGTH_SHORT).show(); **// Toast message for android .**
System.out.println("Diff" + duration + diffInDays + diffInHours + diffInMinutes + diffInSeconds); **// Print console message for Java .**
SELECT
COALESCE(listing.OfferText, 'company.OfferText') AS Offer_Text,
FROM
tbl_directorylisting listing
INNER JOIN tbl_companymaster company ON listing.company_id= company.company_id
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
Change column type to LONGTEXT
you have to float
your image container as follows:
HTML
<div id="container">
<div id="floated">...some other random text</div>
...
some random text
...
</div>
CSS
#container{
width: 400px;
background: yellow;
}
#floated{
float: left;
width: 150px;
background: red;
}
FIDDLE
for in
loops over enumerable property names of an object.
for of
(new in ES6) does use an object-specific iterator and loops over the values generated by that.
In your example, the array iterator does yield all the values in the array (ignoring non-index properties).
For people wanting to use the built-in .NET SmtpClient rather than the SendGrid client library (not sure if that was the OP's intent), I couldn't get it to work unless I used apikey
as my username and the api key itself as the password as outlined here.
<mailSettings>
<smtp>
<network host="smtp.sendgrid.net" port="587" userName="apikey" password="<your key goes here>" />
</smtp>
</mailSettings>
Simply call test2
from test1
like:
EXEC test2 @newId, @prod, @desc;
Make sure to get @id
using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:
SELECT @newId = SCOPE_IDENTITY()
For Windows... create a Chrome shortcut on your desktop.
Right-click > properties > Shortcut
Edit "target" path :
"C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security
(Change the 'C:....\chrome.exe' to where ever your chrome is located).
et voilà :)
For n
number of inputs declare the variable as an empty list and use the same syntax to proceed:
>>> x=input('Enter value of a and b').split(",")
Enter value of a and b
1,2,3,4
>>> x
['1', '2', '3', '4']
bootstrap.yml
or bootstrap.properties
It's only used/needed if you're using Spring Cloud and your application's configuration is stored on a remote configuration server (e.g. Spring Cloud Config Server).
From the documentation:
A Spring Cloud application operates by creating a "bootstrap" context, which is a parent context for the main application. Out of the box it is responsible for loading configuration properties from the external sources, and also decrypting properties in the local external configuration files.
Note that the bootstrap.yml
or bootstrap.properties
can contain additional configuration (e.g. defaults) but generally you only need to put bootstrap config here.
Typically it contains two properties:
spring.cloud.config.uri
)spring.application.name
)Upon startup, Spring Cloud makes an HTTP call to the config server with the name of the application and retrieves back that application's configuration.
application.yml
or application.properties
Contains standard application configuration - typically default configuration since any configuration retrieved during the bootstrap process will override configuration defined here.
It's called a shebang, and tells the parent shell which interpreter should be used to execute the script.
#!/bin/sh <--------- bourne shell compatible script
#!/usr/bin/perl <-- perl script
#!/usr/bin/php <--- php script
#!/bin/false <------ do-nothing script, because false returns immediately anyways.
Most scripting languages tend to interpret a line starting with #
as comment and will ignore the following !/usr/bin/whatever
portion, which might otherwise cause a syntax error in the interpreted language.
Given this piece of HTML code:
<a href='https://facebook.com/'>Facebook</a>
<a href='https://google.ca/'>Google</a>
<input type='text' placeholder='an input box'>
We can use this JavaScript:
function checkTabPress(e) {
'use strict';
var ele = document.activeElement;
if (e.keyCode === 9 && ele.nodeName.toLowerCase() === 'a') {
console.log(ele.href);
}
}
document.addEventListener('keyup', function (e) {
checkTabPress(e);
}, false);
I have bound an event listener to the document
element for the keyUp
event, which triggers a function to check if the Tab key was pressed (or technically, released).
The function checks the currently focused element and whether the NodeName
is a
. If so, it enters the if
block and, in my case, writes the value of the href
property to the JavaScript console.
Here's a jsFiddle
int i = 0;
Console.WriteLine(i++); // Prints 0. Then value of "i" becomes 1.
Console.WriteLine(--i); // Value of "i" becomes 0. Then prints 0.
Does this answer your question ?
As others have mentioned, app on Android can't write a file to any folder the internal storage but their own private storage (which is under /data/data/PACKAGE_NAME ).
You should use the API to get the correct path that is allowed for your app.
read this .
Repeat for Multiple aggregations like:
SELECT sum(AMOUNT) AS TOTAL_AMOUNT FROM (
SELECT AMOUNT FROM table_1
UNION ALL
SELECT AMOUNT FROM table_2
UNION ALL
SELECT ASSURED_SUM FROM table_3
)
Adding a point to this- I came across a problem that OpenQA.Selenium.Support.UI namespace was not available after installing Selenium.NET binding into the C# project. Later found out that we can easily install latest version of Selenium WebDriver Support Classes by running the command:
Install-Package Selenium.Support
in NuGet Package Manager Console, or install Selenium.Support from NuGet Manager.
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
CSS really doesn't have the ability to modify an object in the same manner as JavaScript, so in short - no.
HTML/CSS Approach
If you are looking for an option that does not require much JavaScript (and and all the problems that come with it, such as rapid scroll event calls), it is possible to gain the same behavior by adding a wrapper <div>
and a couple of styles. I noticed much smoother scrolling (no elements lagging behind) when I used the following approach:
HTML
<div id="wrapper">
<div id="fixed">
[Fixed Content]
</div><!-- /fixed -->
<div id="scroller">
[Scrolling Content]
</div><!-- /scroller -->
</div><!-- /wrapper -->
CSS
#wrapper { position: relative; }
#fixed { position: fixed; top: 0; right: 0; }
#scroller { height: 100px; overflow: auto; }
JS
//Compensate for the scrollbar (otherwise #fixed will be positioned over it).
$(function() {
//Determine the difference in widths between
//the wrapper and the scroller. This value is
//the width of the scroll bar (if any).
var offset = $('#wrapper').width() - $('#scroller').get(0).clientWidth;
//Set the right offset
$('#fixed').css('right', offset + 'px');?
});
Of course, this approach could be modified for scrolling regions that gain/lose content during runtime (which would result in addition/removal of scrollbars).
I had the same problem.
Also make sure you are using right python version and you are installing it with right pip version. in my case: I had both python 2.7 and 3.x. I have installed pyspark with
pip2.7 install pyspark
and it worked.
If you want a version that raises an error:
"string to search".index("needle")
If you want a version that returns -1:
"string to search".find("needle")
This is more efficient than the 'in' syntax
To fix this open up the IIS Express applicationhost.config. This file is stored at C:\Users[your user name]\Documents\IISExpress\config\applicationhost.config
Update for VS2015+: config file location is $(solutionDir).vs\config\applicationhost.config
Look for the following lines
<section name="windowsAuthentication" overrideModeDefault="Deny" />
<section name="anonymousAuthentication" overrideModeDefault="Deny" />
<add name="WindowsAuthenticationModule" lockItem="true" />
<add name="AnonymousAuthenticationModule" lockItem="true" />
Change those lines to
<section name="windowsAuthentication" overrideModeDefault="Allow" />
<section name="anonymousAuthentication" overrideModeDefault="Allow" />
<add name="WindowsAuthenticationModule" lockItem="false" />
<add name="AnonymousAuthenticationModule" lockItem="false" />
Save it and refresh Asp.net Page.
An output reg foo
is just shorthand for output foo_wire; reg foo; assign foo_wire = foo
. It's handy when you plan to register that output anyway. I don't think input reg
is meaningful for module
(perhaps task
). input wire
and output wire
are the same as input
and output
: it's just more explicit.
Starting with elif option == 2:
, you indented one time too many. In a decent text editor, you should be able to highlight these lines and press Shift+Tab to fix the issue.
Additionally, there is no statement after for x in range(x, 1, 1):
. Insert an indented pass
to do nothing in the for
loop.
Also, in the first line, you wrote option == 1
. ==
tests for equality, but you meant =
( a single equals sign), which assigns the right value to the left name, i.e.
option = 1
Here is the issue
$total_result = $result->num_rows;
try this
<?php
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
if ($result->num_rows > 0)
{
$total_result = $result->num_rows;
$total_pages = ceil($total_result / $per_page);
if(isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
}
else
{
$start = 0;
$end = $per_page;
}
}
else
{
$start = 0;
$end = $per_page;
}
//display paginations
echo "<p> View pages: ";
for ($i=1; $i < $total_pages; $i++)
{
if (isset($_GET['page']) && $_GET['page'] == $i)
{
echo $i . " ";
}
else
{
echo "<a href='view-pag.php?$i'>" . $i . "</a> | ";
}
}
echo "</p>";
}
else
{
echo "No result to display.";
}
}
else
{
echo "Error: " . $mysqli->error;
}
?>
I guess the answer you need is referenced here Python sets are not json serializable
Not all datatypes can be json serialized . I guess pickle module will serve your purpose.
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
With Java 9, we get access to jshell
, so one can write something like this:
import jdk.jshell.JShell;
import java.lang.StringBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Eval {
public static void main(String[] args) throws IOException {
try(JShell js = JShell.create(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
js.onSnippetEvent(snip -> {
if (snip.status() == jdk.jshell.Snippet.Status.VALID) {
System.out.println("? " + snip.value());
}
});
System.out.print("> ");
for (String line = br.readLine(); line != null; line = br.readLine()) {
js.eval(js.sourceCodeAnalysis().analyzeCompletion(line).source());
System.out.print("> ");
}
}
}
}
Sample run:
> 1 + 2 / 4 * 3
? 1
> 32 * 121
? 3872
> 4 * 5
? 20
> 121 * 51
? 6171
>
Slightly op, but that's what Java currently has to offer
In addition to @Zaph answer, you can create extension:
extension Double {
func toString() -> String {
return String(format: "%.1f",self)
}
}
Usage:
var a:Double = 1.5
println("output: \(a.toString())") // output: 1.5
The below are the methods to convert a Integer to String in JS
The methods are arranged in the decreasing order of performance.
(The performance test results are given by @DarckBlezzer in his answer)
var num = 1
Method 1:
num = `${num}`
Method 2:
num = num + ''
Method 3:
num = String(num)
Method 4:
num = num.toString()
Note: You can't directly call toString()
on a number. 2.toString()
will throw Uncaught SyntaxError: Invalid or unexpected token
.
A single liner, using find
:
find -type f -exec grep -lm1 "PATTERN" {} \; -a -quit
This is what I figured out:
var isHTMLElement = (function () {
if ("HTMLElement" in window) {
// Voilà. Quick and easy. And reliable.
return function (el) {return el instanceof HTMLElement;};
} else if ((document.createElement("a")).constructor) {
// We can access an element's constructor. So, this is not IE7
var ElementConstructors = {}, nodeName;
return function (el) {
return el && typeof el.nodeName === "string" &&
(el instanceof ((nodeName = el.nodeName.toLowerCase()) in ElementConstructors
? ElementConstructors[nodeName]
: (ElementConstructors[nodeName] = (document.createElement(nodeName)).constructor)))
}
} else {
// Not that reliable, but we don't seem to have another choice. Probably IE7
return function (el) {
return typeof el === "object" && el.nodeType === 1 && typeof el.nodeName === "string";
}
}
})();
To improve performance I created a self-invoking function that tests the browser's capabilities only once and assigns the appropriate function accordingly.
The first test should work in most modern browsers and was already discussed here. It just tests if the element is an instance of HTMLElement
. Very straightforward.
The second one is the most interesting one. This is its core-functionality:
return el instanceof (document.createElement(el.nodeName)).constructor
It tests whether el is an instance of the construcor it pretends to be. To do that, we need access to an element's contructor. That's why we're testing this in the if-Statement. IE7 for example fails this, because (document.createElement("a")).constructor
is undefined
in IE7.
The problem with this approach is that document.createElement
is really not the fastest function and could easily slow down your application if you're testing a lot of elements with it. To solve this, I decided to cache the constructors. The object ElementConstructors
has nodeNames as keys with its corresponding constructors as values. If a constructor is already cached, it uses it from the cache, otherwise it creates the Element, caches its constructor for future access and then tests against it.
The third test is the unpleasant fallback. It tests whether el is an object
, has a nodeType
property set to 1
and a string as nodeName
. This is not very reliable of course, yet the vast majority of users shouldn't even fall back so far.
This is the most reliable approach I came up with while still keeping performance as high as possible.
In addition to all the answers provided so far, another reason for causing this exception can happen when you are saving data from list to database using ADO.Net.
Many developers will mistakenly use for
loop or foreach
and leave the SqlCommand
to execute outside the loop, to avoid that make sure that you have like this code sample for example:
public static void Save(List<myClass> listMyClass)
{
using (var Scope = new System.Transactions.TransactionScope())
{
if (listMyClass.Count > 0)
{
for (int i = 0; i < listMyClass.Count; i++)
{
SqlCommand cmd = new SqlCommand("dbo.SP_SaveChanges", myConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@ID", listMyClass[i].ID);
cmd.Parameters.AddWithValue("@FirstName", listMyClass[i].FirstName);
cmd.Parameters.AddWithValue("@LastName", listMyClass[i].LastName);
try
{
myConnection.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException sqe)
{
throw new Exception(sqe.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
myConnection.Close();
}
}
}
else
{
throw new Exception("List is empty");
}
Scope.Complete();
}
}
Here's a modern solution that doesn't have the pitfalls of Object.assign()
(does not copy by reference):
const cloneObj = (obj) => {
return Object.keys(obj).reduce((dolly, key) => {
dolly[key] = (obj[key].constructor === Object) ?
cloneObj(obj[key]) :
obj[key];
return dolly;
}, {});
};
You can use any of the following methods for setting the Drawable on TextView:
1- setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)
2- setCompoundDrawables(Left_Drawable, Top_Drawable, Right_Drawable, Bottom_Drawable)
And to get drawable from resources you can use:
getResources().getDrawable(R.drawable.your_drawable_id);
I wrote quick test program to demonstrate one difference:
#include <stdio.h>
enum {ENUM_DEFINED=16};
enum {ENUM_DEFINED=32};
#define DEFINED_DEFINED 16
#define DEFINED_DEFINED 32
int main(int argc, char *argv[]) {
printf("%d, %d\n", DEFINED_DEFINED, ENUM_DEFINED);
return(0);
}
This compiles with these errors and warnings:
main.c:6:7: error: redefinition of enumerator 'ENUM_DEFINED'
enum {ENUM_DEFINED=32};
^
main.c:5:7: note: previous definition is here
enum {ENUM_DEFINED=16};
^
main.c:9:9: warning: 'DEFINED_DEFINED' macro redefined [-Wmacro-redefined]
#define DEFINED_DEFINED 32
^
main.c:8:9: note: previous definition is here
#define DEFINED_DEFINED 16
^
Note that enum gives an error when define gives a warning.
Add in the generated migration after creating the column the following (example)
add_index :photographers, :email, :unique => true
There are two problems:
Integer#set(i)
. You could otherwise just make use of it.To get it to work, you need to reassign the return value of the inc()
method.
integer = inc(integer);
To learn a bit more about passing by value, here's another example:
public static void main(String... args) {
String[] strings = new String[] { "foo", "bar" };
changeReference(strings);
System.out.println(Arrays.toString(strings)); // still [foo, bar]
changeValue(strings);
System.out.println(Arrays.toString(strings)); // [foo, foo]
}
public static void changeReference(String[] strings) {
strings = new String[] { "foo", "foo" };
}
public static void changeValue(String[] strings) {
strings[1] = "foo";
}
Another way would by to use another loc utility, like LocMetrics for instance.
It also lists many other loc tools.
The integration with Eclipse wouldn't be always there (as it would be with Metrics2, which you can check out because it is a more recent version than Metrics), but at least those tools can reason in term of logical lines (computed by summing the terminal semicolons and terminal curly braces).
You can also check with eclipse-metrics is more adapted to what you expect.
The short answer is yes, yes there is a way to get around mysql_real_escape_string()
.
#For Very OBSCURE EDGE CASES!!!
The long answer isn't so easy. It's based off an attack demonstrated here.
So, let's start off by showing the attack...
mysql_query('SET NAMES gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");
In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:
Selecting a Character Set
mysql_query('SET NAMES gbk');
For this attack to work, we need the encoding that the server's expecting on the connection both to encode '
as in ASCII i.e. 0x27
and to have some character whose final byte is an ASCII \
i.e. 0x5c
. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: big5
, cp932
, gb2312
, gbk
and sjis
. We'll select gbk
here.
Now, it's very important to note the use of SET NAMES
here. This sets the character set ON THE SERVER. If we used the call to the C API function mysql_set_charset()
, we'd be fine (on MySQL releases since 2006). But more on why in a minute...
The Payload
The payload we're going to use for this injection starts with the byte sequence 0xbf27
. In gbk
, that's an invalid multibyte character; in latin1
, it's the string ¿'
. Note that in latin1
and gbk
, 0x27
on its own is a literal '
character.
We have chosen this payload because, if we called addslashes()
on it, we'd insert an ASCII \
i.e. 0x5c
, before the '
character. So we'd wind up with 0xbf5c27
, which in gbk
is a two character sequence: 0xbf5c
followed by 0x27
. Or in other words, a valid character followed by an unescaped '
. But we're not using addslashes()
. So on to the next step...
mysql_real_escape_string()
The C API call to mysql_real_escape_string()
differs from addslashes()
in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1
for the connection, because we never told it otherwise. We did tell the server we're using gbk
, but the client still thinks it's latin1
.
Therefore the call to mysql_real_escape_string()
inserts the backslash, and we have a free hanging '
character in our "escaped" content! In fact, if we were to look at $var
in the gbk
character set, we'd see:
?' OR 1=1 /*
Which is exactly what the attack requires.
The Query
This part is just a formality, but here's the rendered query:
SELECT * FROM test WHERE name = '?' OR 1=1 /*' LIMIT 1
Congratulations, you just successfully attacked a program using mysql_real_escape_string()
...
It gets worse. PDO
defaults to emulating prepared statements with MySQL. That means that on the client side, it basically does a sprintf through mysql_real_escape_string()
(in the C library), which means the following will result in a successful injection:
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));
Now, it's worth noting that you can prevent this by disabling emulated prepared statements:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
This will usually result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently fallback to emulating statements that MySQL can't prepare natively: those that it can are listed in the manual, but beware to select the appropriate server version).
I said at the very beginning that we could have prevented all of this if we had used mysql_set_charset('gbk')
instead of SET NAMES gbk
. And that's true provided you are using a MySQL release since 2006.
If you're using an earlier MySQL release, then a bug in mysql_real_escape_string()
meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes even if the client had been correctly informed of the connection encoding and so this attack would still succeed. The bug was fixed in MySQL 4.1.20, 5.0.22 and 5.1.11.
But the worst part is that PDO
didn't expose the C API for mysql_set_charset()
until 5.3.6, so in prior versions it cannot prevent this attack for every possible command!
It's now exposed as a DSN parameter.
As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. utf8mb4
is not vulnerable and yet can support every Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is utf8
, which is also not vulnerable and can support the whole of the Unicode Basic Multilingual Plane.
Alternatively, you can enable the NO_BACKSLASH_ESCAPES
SQL mode, which (amongst other things) alters the operation of mysql_real_escape_string()
. With this mode enabled, 0x27
will be replaced with 0x2727
rather than 0x5c27
and thus the escaping process cannot create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. 0xbf27
is still 0xbf27
etc.)—so the server will still reject the string as invalid. However, see @eggyal's answer for a different vulnerability that can arise from using this SQL mode.
The following examples are safe:
mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");
Because the server's expecting utf8
...
mysql_set_charset('gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");
Because we've properly set the character set so the client and the server match.
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));
Because we've turned off emulated prepared statements.
$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));
Because we've set the character set properly.
$mysqli->query('SET NAMES gbk');
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "\xbf\x27 OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();
Because MySQLi does true prepared statements all the time.
If you:
mysql_set_charset()
/ $mysqli->set_charset()
/ PDO's DSN charset parameter (in PHP = 5.3.6)OR
utf8
/ latin1
/ ascii
/ etc)You're 100% safe.
Otherwise, you're vulnerable even though you're using mysql_real_escape_string()
...
First of all you should include ckeditor and jquery connector script in your page,
then create a textarea
<textarea name="content" class="editor" id="ms_editor"></textarea>
attach ckeditor to the text area, in my project I use something like this:
$('textarea.editor').ckeditor(function() {
}, { toolbar : [
['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
['Undo','Redo'],
['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
['Link','Unlink','Anchor', 'Image', 'Smiley'],
['Table','HorizontalRule','SpecialChar'],
['Styles','BGColor']
], toolbarCanCollapse:false, height: '300px', scayt_sLang: 'pt_PT', uiColor : '#EBEBEB' } );
on submit get the content using:
var content = $( 'textarea.editor' ).val();
That's it! :)
Cough cough
>>> a,b,c = (1,2,3)
>>> a
1
>>> b
2
>>> c
3
>>> a,b,c = ({'test':'a'},{'test':'b'},{'test':'c'})
>>> a
{'test': 'a'}
>>> b
{'test': 'b'}
>>> c
{'test': 'c'}
>>>
Some cloud solutions exist, such as macincloud (not free)
Here:
http://jsbin.com/urize4/edit
Live Preview
http://jsbin.com/urize4/
You should use "readonly
" instead like:
$("input[type='text']").attr("readonly", "true");
As @Vadzim said, in IntelliJ or Android Studio, you just have to do the following to get java code from kotlin:
Menu > Tools > Kotlin > Show Kotlin Bytecode
Decompile
buttonUpdate:
With a recent version (1.2+) of the Kotlin plugin you also can directly do Menu > Tools > Kotlin -> Decompile Kotlin to Java
.
If you're just looking for an actual regex that allows for various dots, underscores and dashes, it as follows: [a-zA-z0-9.-]+\@[a-zA-z0-9.-]+.[a-zA-Z]+
. That will allow a fairly stupid looking email like tom_anderson.1-neo@my-mail_matrix.com
to be validated.
I encountered this when setting up moodle. I added the following lines in the php.ini file.
zend_extension=C:\xampp\php\ext\php_opcache.dll
[opcache]
opcache.enable = 1
opcache.memory_consumption = 128
opcache.max_accelerated_files = 4000
opcache.revalidate_freq = 60
; Required for Moodle
opcache.use_cwd = 1
opcache.validate_timestamps = 1
opcache.save_comments = 1
opcache.enable_file_override = 0
; If something does not work in Moodle
;opcache.revalidate_path = 1 ; May fix problems with include paths
;opcache.mmap_base = 0x20000000 ; (Windows only) fix OPcache crashes with event id 487
; Experimental for Moodle 2.6 and later
;opcache.fast_shutdown = 1
;opcache.enable_cli = 1 ; Speeds up CLI cron
;opcache.load_comments = 0 ; May lower memory use, might not be compatible with add-ons and other apps
extension=C:\xampp\php\ext\php_intl.dll
[intl]
intl.default_locale = en_utf8
intl.error_level = E_WARNING
Late reading this, but.. The way I read your question, you only need to change two lines of code:
Accept user input, function writes back on screen.
<input type="text" id="userInput"=> give me input</input>
<button onclick="test()">Submit</button>
<!-- add this line for function to write into -->
<p id="demo"></p>
<script type="text/javascript">
function test(){
var userInput = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = userInput;
}
</script>
you can easily define setOnClickListener in your ViewHolder class as follow :
public class ViewHolder extends RecyclerView.ViewHolder {
TextView product_name;
ViewHolder(View itemView) {
super(itemView);
product_name = (TextView) itemView.findViewById(R.id.product_name);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int itemPosition = getLayoutPosition();
Toast.makeText(getApplicationContext(), itemPosition + ":" + String.valueOf(product_name.getText()), Toast.LENGTH_SHORT).show();
}
});
}
}
You can use backslash to quote "funny" characters in your jQuery selectors:
$('#input\\[23\\]')
For attribute values, you can use quotes:
$('input[name="weirdName[23]"]')
Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?
edit fixed bogosity; thanks @Dancrumb
Additional information about removing/uninstalling composer
Answers above did not help me, but what did help me is removing:
Hope this helps.
On a Mac with NetBeans 8.1,
rm -fr 8.1
In your case the version could be different; remove the right version folder.my combination looks like this. it fades out and fades in on each scroll down/up. otherwise you have to scroll up to the header, for fading the header in.
var header = $("#header");
$('#content-container').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
else{
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
}
});
the above one is not optimized for touch/mobile, I think this one does it better for all mobile:
var iScrollPos = 0;
var header = $("#header");
$('#content-container').scroll(function () {
var iCurScrollPos = $(this).scrollTop();
if (iCurScrollPos > iScrollPos) {
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
} else {
//Scrolling Up
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
iScrollPos = iCurScrollPos;
});
That's because $_POST
is pre-populated with form data.
To get JSON data (or any raw input), use php://input
.
$json = json_decode(file_get_contents("php://input"));
try this:
for (char c: string.toCharArray()){
if (((int)c)>127){
return false;
}
}
return true;
Reply from @Ib33X is awesome. If you want to remove every empty string, after stripped. you need to use the strip method too. Otherwise, it will return the empty string too if it has white spaces. Like, " " will be valid too for that answer. So, can be achieved by.
strings = ["first", "", "second ", " "]
[x.strip() for x in strings if x.strip()]
The answer for this will be ["first", "second"]
.
If you want to use filter
method instead, you can do like
list(filter(lambda item: item.strip(), strings))
. This is give the same result.
It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.
I suppose you want to commit the changes to one branch and then make those changes visible in the other branch. In git you should have no changes on top of HEAD when changing branches.
You commit only the changed files by:
git commit [some files]
Or if you are sure that you have a clean staging area you can
git add [some files] # add [some files] to staging area
git add [some more files] # add [some more files] to staging area
git commit # commit [some files] and [some more files]
If you want to make that commit available on both branches you do
git stash # remove all changes from HEAD and save them somewhere else
git checkout <other-project> # change branches
git cherry-pick <commit-id> # pick a commit from ANY branch and apply it to the current
git checkout <first-project> # change to the other branch
git stash pop # restore all changes again
In the right bottom edge there are information about NetBeans updates. Left to it, there's the tasks running (building, running application etc). Click on it, right click the process you want and select Show Output
.
If you're looking to do an "upsert" one of the most efficient ways currently in SQL Server for single rows is this:
UPDATE myTable ...
IF @@ROWCOUNT=0
INSERT INTO myTable ....
You can also use the MERGE
syntax if you're doing this with sets of data rather than single rows.
If you want to INSERT
and not UPDATE
then you can just write your single INSERT
statement and use WHERE NOT EXISTS (SELECT ...)
"Resource temporarily unavailable"
is the error message corresponding to EAGAIN
, which means that the operation would have blocked but nonblocking operation was requested. For send()
, that could be due to any of:
fcntl()
; orMSG_DONTWAIT
flag to send()
; orSO_SNDTIMEO
socket option.Quite old topic. But I want to give my 2 cents...
I've slightly modified tomasz86 solution, to look in the old style "Shell Folders" instead of "User Shell Folders", so i don't need to expand the envvar %userprofile%
Also there is no dependency from powershell/vbscript/etc....
for /f "usebackq tokens=2,3*" %%A in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "Desktop"`) do if %%A==REG_SZ set desktopdir=%%B
echo %desktopdir%
Hope it helps.
To see your key on Ubuntu, just enter the following command on your terminal:
ssh-add -l
You will get an output like this:
2568 0j:20:4b:88:a7:9t:wd:19:f0:d4:4y:9g:27:cf:97:23
yourName@ubuntu (RSA)
If however you get an error like; Could not open a connection to your authentication agent.
Then it means that ssh-agent is not running. You can start/run it with:
ssh-agent bash
(thanks to @Richard in the comments) and then re-run ssh-add -l
Your debut
and fin
values are floating point values, not integers, because taille
is a float.
Make those values integers instead:
item = plateau[int(debut):int(fin)]
Alternatively, make taille
an integer:
taille = int(sqrt(len(plateau)))
Had the same problem , restarted xcode and it found my phone again.
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
Try it like this
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
This works,
#!/usr/bin/Rscript
but I don't know what happens if you have more than 1 version of R installed on your machine.
If you do it like this
#!/usr/bin/env Rscript
it tells the interpreter to just use whatever R appears first on your path.
DBCC CHECKIDENT(table_name, RESEED, value)
table_name = give the table you want to reset value
value=initial value to be zero,to start identity column with 1
For Chart.js 2.x refer to andyhasit's answer - https://stackoverflow.com/a/36954319/360067
For Chart.js 1.x, you can tweak the options and extend the chart type to do this, like so
Chart.types.Line.extend({
name: "LineAlt",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var ctx = this.chart.ctx;
ctx.save();
// text alignment and color
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
ctx.fillStyle = this.options.scaleFontColor;
// position
var x = this.scale.xScalePaddingLeft * 0.4;
var y = this.chart.height / 2;
// change origin
ctx.translate(x, y);
// rotate text
ctx.rotate(-90 * Math.PI / 180);
ctx.fillText(this.datasets[0].label, 0, 0);
ctx.restore();
}
});
calling it like this
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).LineAlt(data, {
// make enough space on the right side of the graph
scaleLabel: " <%=value%>"
});
Notice the space preceding the label value, this gives us space to write the y axis label without messing around with too much of Chart.js internals
Fiddle - http://jsfiddle.net/wyox23ga/
You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.
Inside applicationContext.xml file of a maven Hibernet web app project below settings worked for me.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<jee:jndi-lookup id="dataSource"
jndi-name="Give_DataSource_Path_From_Your_Server"
expected-type="javax.sql.DataSource" />
Hope It will help someone.Thanks!
Take a look on this answer to another related question. It shows how to enable, disable and to see the logs on live servers without restarting.
Here is a summary:
If you don't want or cannot restart the MySQL server you can proceed like this on your running server:
Create your log tables (see answer)
Enable Query logging on the database (Note that the string 'table' should be put literally and not substituted by any table name. Thanks Nicholas Pickering)
SET global general_log = 1;
SET global log_output = 'table';
select * from mysql.general_log;
SET global general_log = 0;
TRUNCATE mysql.general_log
Do this to get the JSON
String json = EntityUtils.toString(response.getEntity());
More details here : get json from HttpResponse
Try this to get value of div content using jquery.
$(".showplaintext").click(function(){_x000D_
alert($(".plain").text());_x000D_
});_x000D_
_x000D_
// Show text content of formatted paragraph_x000D_
$(".showformattedtext").click(function(){_x000D_
alert($(".formatted").text());_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p class="plain">Exploring the zoo, we saw every kangaroo jump and quite a few carried babies. </p>_x000D_
<p class="formatted">Exploring the zoo<strong>, we saw every kangaroo</strong> jump <em><sup> and quite a </sup></em>few carried <a href="#"> babies</a>.</p>_x000D_
<button type="button" class="showplaintext">Get Plain Text</button>_x000D_
<button type="button" class="showformattedtext">Get Formatted Text</button>
_x000D_
Taken from @ Get the text inside an element using jQuery
If you have updated the ADT tools and also SDK platform and you see the above error, restart Eclipse.
You can use XRegExp, an augmented, extensible, cross-browser implementation of regular expressions, including support for additional syntax, flags, and methods:
s
, to make dot match all characters (aka dotall or singleline mode), and x
, for free-spacing and comments (aka extended mode).There is a pandas function that can be applied to DateTime index in pandas data frame.
date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list
the element inside the list:
u'1910-11-02'
You might need to replace the 'u'.
There might be some additional arguments that I should put into the previous functions.
I've been going back and forth on these two options the last few times I've needed them. Up until recently, my preference has been for the sealed trait/case object option.
1) Scala Enumeration Declaration
object OutboundMarketMakerEntryPointType extends Enumeration {
type OutboundMarketMakerEntryPointType = Value
val Alpha, Beta = Value
}
2) Sealed Traits + Case Objects
sealed trait OutboundMarketMakerEntryPointType
case object AlphaEntryPoint extends OutboundMarketMakerEntryPointType
case object BetaEntryPoint extends OutboundMarketMakerEntryPointType
While neither of these really meet all of what a java enumeration gives you, below are the pros and cons:
Scala Enumeration
Pros: -Functions for instantiating with option or directly assuming accurate (easier when loading from a persistent store) -Iteration over all possible values is supported
Cons: -Compilation warning for non-exhaustive search is not supported (makes pattern matching less ideal)
Case Objects/Sealed traits
Pros: -Using sealed traits, we can pre-instantiate some values while others can be injected at creation time -full support for pattern matching (apply/unapply methods defined)
Cons: -Instantiating from a persistent store - you often have to use pattern matching here or define your own list of all possible 'enum values'
What ultimately made me change my opinion was something like the following snippet:
object DbInstrumentQueries {
def instrumentExtractor(tableAlias: String = "s")(rs: ResultSet): Instrument = {
val symbol = rs.getString(tableAlias + ".name")
val quoteCurrency = rs.getString(tableAlias + ".quote_currency")
val fixRepresentation = rs.getString(tableAlias + ".fix_representation")
val pointsValue = rs.getInt(tableAlias + ".points_value")
val instrumentType = InstrumentType.fromString(rs.getString(tableAlias +".instrument_type"))
val productType = ProductType.fromString(rs.getString(tableAlias + ".product_type"))
Instrument(symbol, fixRepresentation, quoteCurrency, pointsValue, instrumentType, productType)
}
}
object InstrumentType {
def fromString(instrumentType: String): InstrumentType = Seq(CurrencyPair, Metal, CFD)
.find(_.toString == instrumentType).get
}
object ProductType {
def fromString(productType: String): ProductType = Seq(Commodity, Currency, Index)
.find(_.toString == productType).get
}
The .get
calls were hideous - using enumeration instead I can simply call the withName method on the enumeration as follows:
object DbInstrumentQueries {
def instrumentExtractor(tableAlias: String = "s")(rs: ResultSet): Instrument = {
val symbol = rs.getString(tableAlias + ".name")
val quoteCurrency = rs.getString(tableAlias + ".quote_currency")
val fixRepresentation = rs.getString(tableAlias + ".fix_representation")
val pointsValue = rs.getInt(tableAlias + ".points_value")
val instrumentType = InstrumentType.withNameString(rs.getString(tableAlias + ".instrument_type"))
val productType = ProductType.withName(rs.getString(tableAlias + ".product_type"))
Instrument(symbol, fixRepresentation, quoteCurrency, pointsValue, instrumentType, productType)
}
}
So I think my preference going forward is to use Enumerations when the values are intended to be accessed from a repository and case objects/sealed traits otherwise.
Your curl
command is entirely wrong. You should be using the following
curl -H 'Authorization: token <MYTOKEN>' ...
That aside, that doesn't authorize your computer to clone the repository if in fact it is private. (Taking a look, however, indicates that it is not.) What you would normally do is the following:
git clone https://scuzzlebuzzle:<MYTOKEN>@github.com/scuzzlebuzzle/ol3-1.git --branch=gh-pages gh-pages
That will add your credentials to the remote created when cloning the repository. Unfortunately, however, you have no control over how Travis clones your repository, so you have to edit the remote like so.
# After cloning
cd gh-pages
git remote set-url origin https://scuzzlebuzzle:<MYTOKEN>@github.com/scuzzlebuzzle/ol3-1.git
That will fix your project to use a remote with credentials built in.
Warning: Tokens have read/write access and should be treated like passwords. If you enter your token into the clone URL when cloning or adding a remote,
Git writes it to your .git/config file in plain text, which is a security risk.
I don't know any MATLAB and I've never used it, but it seems to me you are dividing. Why? Something like this will be much faster:
d = 1/norm(V)
V1 = V * d
Go to web.xml
add <element>
before
<web-app>
and close </element>
after </web-app>
should be somethings like this
<?xml version="1.0" encoding="UTF-8"?>
<element>
<web-app>
....
</web-app>
</element>
Let's start from the beginning and explore this question.
So let's suppose you have two lists:
list_1=['01','98']
list_2=[['01','98']]
And we have to copy both lists, now starting from the first list:
So first let's try by setting the variable copy
to our original list, list_1
:
copy=list_1
Now if you are thinking copy copied the list_1, then you are wrong. The id
function can show us if two variables can point to the same object. Let's try this:
print(id(copy))
print(id(list_1))
The output is:
4329485320
4329485320
Both variables are the exact same argument. Are you surprised?
So as we know python doesn't store anything in a variable, Variables are just referencing to the object and object store the value. Here object is a list
but we created two references to that same object by two different variable names. This means that both variables are pointing to the same object, just with different names.
When you do copy=list_1
, it is actually doing:
Here in the image list_1 and copy are two variable names but the object is same for both variable which is list
So if you try to modify copied list then it will modify the original list too because the list is only one there, you will modify that list no matter you do from the copied list or from the original list:
copy[0]="modify"
print(copy)
print(list_1)
output:
['modify', '98']
['modify', '98']
So it modified the original list :
Now let's move onto a pythonic method for copying lists.
copy_1=list_1[:]
This method fixes the first issue we had:
print(id(copy_1))
print(id(list_1))
4338792136
4338791432
So as we can see our both list having different id and it means that both variables are pointing to different objects. So what actually going on here is:
Now let's try to modify the list and let's see if we still face the previous problem:
copy_1[0]="modify"
print(list_1)
print(copy_1)
The output is:
['01', '98']
['modify', '98']
As you can see, it only modified the copied list. That means it worked.
Do you think we're done? No. Let's try to copy our nested list.
copy_2=list_2[:]
list_2
should reference to another object which is copy of list_2
. Let's check:
print(id((list_2)),id(copy_2))
We get the output:
4330403592 4330403528
Now we can assume both lists are pointing different object, so now let's try to modify it and let's see it is giving what we want:
copy_2[0][1]="modify"
print(list_2,copy_2)
This gives us the output:
[['01', 'modify']] [['01', 'modify']]
This may seem a little bit confusing, because the same method we previously used worked. Let's try to understand this.
When you do:
copy_2=list_2[:]
You're only copying the outer list, not the inside list. We can use the id
function once again to check this.
print(id(copy_2[0]))
print(id(list_2[0]))
The output is:
4329485832
4329485832
When we do copy_2=list_2[:]
, this happens:
It creates the copy of list but only outer list copy, not the nested list copy, nested list is same for both variable, so if you try to modify the nested list then it will modify the original list too as the nested list object is same for both lists.
What is the solution? The solution is the deepcopy
function.
from copy import deepcopy
deep=deepcopy(list_2)
Let's check this:
print(id((list_2)),id(deep))
4322146056 4322148040
Both outer lists have different IDs, let's try this on the inner nested lists.
print(id(deep[0]))
print(id(list_2[0]))
The output is:
4322145992
4322145800
As you can see both IDs are different, meaning we can assume that both nested lists are pointing different object now.
This means when you do deep=deepcopy(list_2)
what actually happens:
Both nested lists are pointing different object and they have separate copy of nested list now.
Now let's try to modify the nested list and see if it solved the previous issue or not:
deep[0][1]="modify"
print(list_2,deep)
It outputs:
[['01', '98']] [['01', 'modify']]
As you can see, it didn't modify the original nested list, it only modified the copied list.
On linux with oracle-jdk the code the OP submitted uses port 7 when not root and ICMP when root. It does do a real ICMP echo request when run as root as the documentation specifies.
If you running this on a MS machine you may have to run the app as administrator to get the ICMP behaviour.
This is an old post, but if anyone comes up with this problem, i post what solved my problem:
I was trying to add the Action Bar Sherlock to my proyect when i get the error:
Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Holo.ActionBar'.
I turns out that the action bar sherlock proyect and my proyect had differents minSdkVersion and targetSdkVersion. Changing that parameters to match in both proyect solved my problem.
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="17"/>
it is compatible with all the browsers, change values to fit your application
background: #fdfdfd;
background: -moz-linear-gradient(top, #fdfdfd 0%, #f6f6f6 60%, #f2f2f2 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fdfdfd), color-stop(60%,#f6f6f6), color-stop(100%,#f2f2f2));
background: -webkit-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: -o-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: -ms-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: linear-gradient(to bottom, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fdfdfd', endColorstr='#f2f2f2',GradientType=0
I know this is a bit late - but to be clear:
A string doesn't really have encoding... in .NET the a string is a collection of char objects. Essentially, if it is a string, it has already been decoded.
However if you are reading the contents of a file, which is made of bytes, and wish to convert that to a string, then the file's encoding must be used.
.NET includes encoding and decoding classes for: ASCII, UTF7, UTF8, UTF32 and more.
Most of these encodings contain certain byte-order marks that can be used to distinguish which encoding type was used.
The .NET class System.IO.StreamReader is able to determine the encoding used within a stream, by reading those byte-order marks;
Here is an example:
/// <summary>
/// return the detected encoding and the contents of the file.
/// </summary>
/// <param name="fileName"></param>
/// <param name="contents"></param>
/// <returns></returns>
public static Encoding DetectEncoding(String fileName, out String contents)
{
// open the file with the stream-reader:
using (StreamReader reader = new StreamReader(fileName, true))
{
// read the contents of the file into a string
contents = reader.ReadToEnd();
// return the encoding.
return reader.CurrentEncoding;
}
}
After some searching on the Internet I found that it is in fact very much possible to call a custom method passing the DataBinder.Eval value.
The custom method can be written in the code behind file, but has to be declared public or protected. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be private.
So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:
default.aspx
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
default.aspx.cs code:
public partial class _Default : System.Web.UI.Page
{
protected string GetDateInHomepageFormat(DateTime d)
{
string retValue = "";
// Do all processing required and return value
return retValue;
}
}
Hope this helps others as well.
The slickest way to do this:
{React.cloneElement(this.props.children, this.props)}
Try this:
function welcomeMessage() { var shape1 = new Shape(); //alert(shape1.draw()); alert(shape1.hasOwnProperty("name")); }
When working with reflection in JavaScript, member objects are always refered to as the name as a string. For example:
for(i in obj) { ... }
The loop iterator i will be hold a string value with the name of the property. To use that in code you have to address the property using the array operator like this:
for(i in obj) { alert("The value of obj." + i + " = " + obj[i]); }
Assuming you're using Spring Boot, another option is to put the following in your application.properties
:
logging.level.org.springframework.security=DEBUG
This is the same for most other Spring modules as well.
If you're not using Spring Boot, try setting the property in your logging configuration, e.g. logback.
Here is the application.yml version as well:
logging:
level:
org:
springframework:
security: DEBUG
May be easier using a java.util.HashSet. For example:
List <String> list = new ArrayList<String>();
list.add("behold");
list.add("bend");
list.add("bet");
//Load the list into a hashSet
Set<String> set = new HashSet<String>(list);
if (set.contains("bend"))
{
System.out.println("String found!");
}
Does this work for you?
interface IMessage
{
void Process(object source);
}
class LoginMessage : IMessage
{
public void Process(object source)
{
}
}
abstract class MessageProcessor
{
public abstract void ProcessMessage(object source, object type);
}
class MessageProcessor<T> : MessageProcessor where T: IMessage
{
public override void ProcessMessage(object source, object o)
{
if (!(o is T)) {
throw new NotImplementedException();
}
ProcessMessage(source, (T)o);
}
public void ProcessMessage(object source, T type)
{
type.Process(source);
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<Type, MessageProcessor> messageProcessors = new Dictionary<Type, MessageProcessor>();
messageProcessors.Add(typeof(string), new MessageProcessor<LoginMessage>());
LoginMessage message = new LoginMessage();
Type key = message.GetType();
MessageProcessor processor = messageProcessors[key];
object source = null;
processor.ProcessMessage(source, message);
}
}
This gives you the correct object. The only thing I am not sure about is whether it is enough in your case to have it as an abstract MessageProcessor.
Edit: I added an IMessage interface. The actual processing code should now become part of the different message classes that should all implement this interface.
find the below explanation:
int main()
{
int a = 10;// say address of 'a' is 2000;
int *p = &a; //it means 'p' is pointing[referencing] to 'a'. i.e p->2000
int c = *p; //*p means dereferncing. it will give the content of the address pointed by 'p'. in this case 'p' is pointing to 2000[address of 'a' variable], content of 2000 is 10. so *p will give 10.
}
conclusion :
&
[address operator] is used for referencing.*
[star operator] is used for de-referencing .Yes, There is a way to change configuration. If you are on a dedicated server and simply need more SQL connections, you may update the "max pool size" entries in both connection strings by following these instructions:
Find your Connection Strings, these will look similar to the examples below :
"add name="SiteSqlServer" connectionString="server=(local);database=dbname;uid=dbuser;pwd=dbpassword;pooling=true;connection lifetime=120;max pool size=25;""
5.Change the max pool size=X value to the required pool size.
This should work:
git show branch:file
Where branch can be any ref (branch, tag, HEAD, ...) and file is the full path of the file. To export it you could use
git show branch:file > exported_file
You should also look at VonC's answers to some related questions:
UPDATE 2015-01-19:
Nowadays you can use relative paths with git show a1b35:./file.txt
.
Take a look at ?legend
and try this:
legend('topright', names(a)[-1] ,
lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)
Finally I found a solution - I'm posting it here for other people who might have the same problem (all 5 of you):
Under product add The following:
<Property Id="PREVIOUSVERSIONSINSTALLED" Secure="yes" />
<Upgrade Id="YOUR_GUID">
<UpgradeVersion
Minimum="1.0.0.0" Maximum="99.0.0.0"
Property="PREVIOUSVERSIONSINSTALLED"
IncludeMinimum="yes" IncludeMaximum="no" />
</Upgrade>
Under InstallExecuteSequence add:
<RemoveExistingProducts Before="InstallInitialize" />
From now on whenever I install the product it removed previous installed versions.
Note: replace upgrade Id with your own GUID
for XML android
android:src="@drawable/foto1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
Use the a
mode. It stands for append
.
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
fclose($myfile);