Try WANem
WANem is a Wide Area Network Emulator, meant to provide a real experience of a Wide Area Network/Internet, during application development / testing over a LAN environment.
FWIW CloudFront supports streaming as well. Might be better than plain streaming from instances.
You can use iperf to benchmark network performance (maximum possible throughput). See following links for details:
Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:
240p 360p 480p 720p 1080p
Resolution 426 x 240 640 x 360 854x480 1280x720 1920x1080
Video Bitrates
Maximum 700 Kbps 1000 Kbps 2000 Kbps 4000 Kbps 6000 Kbps
Recommended 400 Kbps 750 Kbps 1000 Kbps 2500 Kbps 4500 Kbps
Minimum 300 Kbps 400 Kbps 500 Kbps 1500 Kbps 3000 Kbps
It would appear as though this is the case, although the numbers dont sync up to the google table above:
// the bitrates, video width and file names for this clip
bitrates: [
{ url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
{ url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
{ url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
],
First convert your Chart.js canvas to base64 string.
var url_base64 = document.getElementById('myChart').toDataURL('image/png');
Set it as a href attribute for anchor tag.
link.href = url_base64;
<a id='link' download='filename.png'>Save as Image</a>
typeof(BaseClass).IsAssignableFrom(unknownType);
I have the same problem, i read the url with an properties file:
String configFile = System.getenv("system.Environment");
if (configFile == null || "".equalsIgnoreCase(configFile.trim())) {
configFile = "dev.properties";
}
// Load properties
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/" + configFile));
//read url from file
apiUrl = properties.getProperty("url").trim();
URL url = new URL(apiUrl);
//throw exception here
URLConnection conn = url.openConnection();
dev.properties
url = "https://myDevServer.com/dev/api/gate"
it should be
dev.properties
url = https://myDevServer.com/dev/api/gate
without "" and my problem is solved.
According to oracle documentation
- Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
So it means it is not parsed inside the string.
Sorry a bit late to the party and a bit surprised that nobody mentioned the drop method:
ex="test1, test2, test3, test4, test5"
ex.split(",").drop(1).join(",")
=> "test2,test3,test4,test5"
You can add hibernate validator dependency, to provide a Validator
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.12.Final</version>
</dependency>
This kind of warning can mean that You're trying to present new View Controller
through Navigation Controller
while this Navigation Controller
is currently presenting another View Controller
. To fix it You have to dismiss currently presented View Controller
at first and on completion present the new one.
Another cause of the warning can be trying to present View Controller
on thread another than main
.
I was testing out the speed of the functions, and I found consistently that this solution that I had written was much faster than match
ing. We check the new length of the string as compared to the previous length.
const lines = str.length - str.replace(/\n/g, "").length+1;
let str = `Line1
Line2
Line3`;
console.time("LinesTimer")
console.log("Lines: ",str.length - str.replace(/\n/g, "").length+1);
console.timeEnd("LinesTimer")
_x000D_
Your call to text()
doesn't output anything because you inverted your x and your y:
plot(abs_losses, percent_losses,
main= "Absolute Losses vs. Relative Losses(in%)",
xlab= "Losses (absolute, in miles of millions)",
ylab= "Losses relative (in % of January´2007 value)",
col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)
text(abs_losses, percent_losses, labels=namebank, cex= 0.7)
Now if you want to move your labels down, left, up or right you can add argument pos=
with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)
You can of course gives a vector of value to pos
if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):
pos_vector <- rep(3, length(namebank))
pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)
It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.
If your iframe is in the same domain as your parent page you can access the elements using document.frames
collection.
// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on document.frames['myIFrame'].document like you are working on
// normal document object in JS
window.frames['myIFrame'].document.getElementById('myIFrameElemId')
If your iframe is not in the same domain the browser should prevent such access for security reasons.
You can use the following nginx configuration example:
upstream adminhost {
server adminhostname:8080;
}
server {
listen 80;
location ~ ^/admin/(.*)$ {
proxy_pass http://adminhost/$1$is_args$args;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
Setting background-blend-mode
to darken
would be the most direct and shortest way to achieve the purpose however you must set a background-color
first for the blend mode to work.
This is also the best way if you need to manipulate the values in javascript later on.
background: rgba(0, 0, 0, .65) url('http://fc02.deviantart.net/fs71/i/2011/274/6/f/ocean__sky__stars__and_you_by_muddymelly-d4bg1ub.png');
background-blend-mode: darken;
Try using the overload that takes CharSequence
arguments (eg, String
) rather than char
:
str = str.replace("X", "");
You have to add providers array in @Component decorator or in the module where your component is declared. Inside component you can do as below:
@Component({
moduleId: module.id,
selector: 'pm-header',
templateUrl: 'header.component.html',
styleUrls: ['header.component.css'],
directives: [ROUTER_DIRECTIVES, NgClass],
providers: [MobileService]
})
a <div>
can be focused if it has a tabindex
attribute. (the value can be set to -1)
For example:
$("#focus_point").attr("tabindex",-1).focus();
In addition, consider setting outline: none !important;
so it displayed without a focus rectangle.
var element = $("#focus_point");
element.css('outline', 'none !important')
.attr("tabindex", -1)
.focus();
Basically, tree conflicts arise if there is some restructure in the folder structure on the branch.
You need to delete the conflict folder and use svn clean
once.
Hope this solves your conflict.
You can also check for bootstrap datatable plugin as well for above issue.
It will have a large column table scrollable feature with lot of other options
$(document).ready(function() {
$('#example').dataTable( {
"scrollX": true
} );
} );
for more info with example please check out this link
You don't need to specify the module path per se. CMake ships with its own set of built-in find_package scripts, and their location is in the default CMAKE_MODULE_PATH.
The more normal use case for dependent projects that have been CMakeified would be to use CMake's external_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE_MODULE_PATH in order to find the subproject at the system level.
UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Tutorial" bundle:nil];
self.window.rootViewController = [storyboard instantiateInitialViewController];
This is the simple example to understand about python unpacking,
>>> def f(*args, **kwargs):
... print 'args', args, 'kwargs', kwargs
eg1:
>>>f(1, 2)
>>> args (1,2) kwargs {} #args return parameter without reference as a tuple
>>>f(a = 1, b = 2)
>>> args () kwargs {'a': 1, 'b': 2} #args is empty tuple and kwargs return parameter with reference as a dictionary
Let's me give a more detail example. As to the below struct:
struct Count{
uint32_t c;
Count(uint32_t i=0):c(i){}
uint32_t getCount(){
return c;
}
uint32_t add(const Count& count){
uint32_t total = c + count.getCount();
return total;
}
};
As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object
. In the method add
count
is declared as const object, but the method getCount
is not const method, so count.getCount()
may change the members in count
.
Compile error as below(core message in my compiler):
error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]
To solve the above problem, you can:
uint32_t getCount(){...}
to uint32_t getCount() const {...}
. So count.getCount()
won't change the members in count
.or
uint32_t add(const Count& count){...}
to uint32_t add(Count& count){...}
. So count
don't care about changing members in it.As to you problem, objects in the std::set are stored as const StudentT, but the method getId
and getName
are not const, so you give the above error.
You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.
let session = URLSession.shared
let url = "http://...."
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
var params :[String: Any]?
params = ["Some_ID" : "111", "REQUEST" : "SOME_API_NAME"]
do{
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
if let response = response {
let nsHTTPResponse = response as! HTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
print ("status code = \(statusCode)")
}
if let error = error {
print ("\(error)")
}
if let data = data {
do{
let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
print ("data = \(jsonResponse)")
}catch _ {
print ("OOps not good JSON formatted response")
}
}
})
task.resume()
}catch _ {
print ("Oops something happened buddy")
}
This should work:
if (!string.IsNullOrWhiteSpace(dateTimeEnd))
eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
eventCustom.DateTimeEnd = null;
Note that this will throw an exception if the string is not in the correct format.
It will be worked fine. This is best way to delete old files and remove empty directories recursively. following .bat file is,
forfiles /p [PATH] /s /m [FILE-PATTERN] /d -[DAYS] /c "cmd /c del @path"
for /f "delims=" %%d in ('dir [PATH] /s /b /ad ^| sort /r') do rd "%%d"
The placeholders needs to be replaced as follows (without the quotation marks):
[DAYS] = Max. age of the files in days, e.g. “10”
[PATH] = Path to search for old files and empty folders, e.g. “C:\Backup\”
[FILE-PATTERN] = Pattern that matches files to delete, e.g. “*.bkp”
The script has been successfully tested under Windows 7 and Windows Server 2003.
<VirtualHost *:80>
DocumentRoot /var/www/app1
ServerName app1.example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/example
ServerName example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/wildcard
ServerName other.example.com
ServerAlias *.example.com
</VirtualHost>
Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.
Because your question is geared towards a single table, you can use this:
EXEC sp_fkeys 'TableName'
I found it on SO here:
https://stackoverflow.com/a/12956348/652519
I found the information I needed pretty quickly. It lists the foreign key's table, column and name.
EDIT
Here's a link to the documentation that details the different parameters that can be used: https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-fkeys-transact-sql
you can also use just
StringFormat=d
in your datagrid column for date time showing
finally it will be
<sdk:DataGridTextColumn Binding="{Binding Path=DeliveryDate,StringFormat=d}" Header="Delivery date" Width="*" />
the out put will look like
I think this is the most reliable way to get the desktop path which isn't always the same as the username.
MsgBox CreateObject("WScript.Shell").specialfolders("Desktop")
i'll make an example,
first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit)
, and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),
setting up the netcat server to listen on port 9999: nc -l 9999
now hitting http://127.0.0.1:9999 in firefox, i get:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
now let us compare that with this simple script:
<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);
i get:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*
there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent
specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding
header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:
<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
CURLOPT_ENCODING=>'gzip, deflate',
CURLOPT_HTTPHEADER=>array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Connection: keep-alive',
'Upgrade-Insecure-Requests: 1',
),
));
curl_exec($ch);
now running that code, our netcat server gets:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1
and voila! our php-emulated browser
GET request should now be indistinguishable from the real firefox GET request :)
this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding
header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,
<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
CURLOPT_ENCODING=>'gzip, deflate',
CURLOPT_HTTPHEADER=>array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Accept-Encoding: gzip, deflate',
'Connection: keep-alive',
'Upgrade-Insecure-Requests: 1',
),
));
curl_exec($ch);
running that, our netcat server gets:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)
Please check this example here: Accessing Structure Members
There is explained that the right way to do it is like this:
strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);
pip install pyqt5
for python3 for ubuntu
First of all float and double are both used for representation of numbers fractional numbers. So, the difference between the two stems from the fact with how much precision they can store the numbers.
For example: I have to store 123.456789 One may be able to store only 123.4567 while other may be able to store the exact 123.456789.
So, basically we want to know how much accurately can the number be stored and is what we call precision.
Quoting @Alessandro here
The precision indicates the number of decimal digits that are correct, i.e. without any kind of representation error or approximation. In other words, it indicates how many decimal digits one can safely use.
Float can accurately store about 7-8 digits in the fractional part while Double can accurately store about 15-16 digits in the fractional part
So, double can store double the amount of fractional part as of float. That is why Double is called double the float
I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.
public class RandomNumberGenerator {
private static final Set<String> generatedNumbers = new HashSet<String>();
public RandomNumberGenerator() {
}
public static void main(String[] args) {
final int maxLength = 7;
final int maxTry = 10;
for (int i = 0; i < 10; i++) {
System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry));
}
}
public static String getRandomId(final int maxLength, final int maxTry) {
final Random random = new Random(System.nanoTime());
final int max = (int) Math.pow(10, maxLength);
final int maxMin = (int) Math.pow(10, maxLength-1);
int i = 0;
boolean unique = false;
int randomId = -1;
while (i < maxTry) {
randomId = random.nextInt(max - maxMin - 1) + maxMin;
synchronized (generatedNumbers) {
if (generatedNumbers.contains(randomId) == false) {
unique = true;
break;
}
}
i++;
}
if (unique == false) {
throw new RuntimeException("Cannot generate unique id!");
}
synchronized (generatedNumbers) {
generatedNumbers.add(String.valueOf(randomId));
}
return String.valueOf(randomId);
}
}
echo $PATH
and copy it's valueexport PATH=""
export PATH="/path/you/want/to/keep"
For anyone else looking to do what the original poster is asking, please consider to use fragments instead the way Kevin said. Here is an excellent tutorial on how to do that:
https://github.com/codepath/android_guides/wiki/Fragment-Navigation-Drawer
If you choose to instead use activities instead of fragments you are going to run into the problem of the nav drawer being re-created every time you navigate to a new activity. This results in an ugly/slow rendering of the nav drawer each time.
How about using a template function to bind all constructors?
template <class... T> Derived(T... t) : Base(t...) {}
You can create a thread just like this:
Thread thread = new Thread(new Runnable() {
public void run() {
}
});
thread.start();
Also, you can use Runnable, Asyntask, Timer, TimerTaks and AlarmManager to excecute Threads.
try execution the following command
vim .bashrc
:set ff=unix
:wq!
if you are on linux, edit the /etc/php/php.ini
(or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment
;extension=imap.so
so that it becomes like this:
extension=imap.so
Then, restart the apache by
# /etc/rc.d/httpd restart
I'm a friend of keeping the original files, so that you can still use the archived original ones and do new encodes from these fresh ones when the old transcodes are out of date. eg. migrating them from previously transocded mpeg2-hd to mpeg4-hd (and perhaps from mpeg4-hd to its successor in sometime). but all of these should be done from the original. any compression step will followed by a loss of quality. it will need some time to redo this again, but in my opinion it's worth the effort.
so, if you want to keep the originals, you can use the running time in seconds of you tapes times the maximum datarate of hdv (constants 27mbit/s I think) to get your needed storage capacity
A JTextField
was designed to use an ActionListener
just like a JButton
is. See the addActionListener()
method of JTextField
.
For example:
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("some action");
}
};
JTextField textField = new JTextField(10);
textField.addActionListener( action );
Now the event is fired when the Enter key is used.
Also, an added benefit is that you can share the listener with a button even if you don't want to make the button a default button.
JButton button = new JButton("Do Something");
button.addActionListener( action );
Note, this example uses an Action
, which implements ActionListener
because Action
is a newer API with addition features. For example you could disable the Action
which would disable the event for both the text field and the button.
If you use fragments you can prepare XML layout and than stratch critical elements programmatically
int thirdScreenWidth = (int)(screenWidth *0.33);
View view = inflater.inflate(R.layout.fragment_second, null);
View _container = view.findViewById(R.id.rim1container);
_container.getLayoutParams().width = thirdScreenWidth * 2;
_container = view.findViewById(R.id.rim2container);
_container.getLayoutParams().width = screenWidth - thirdScreenWidth * 2;
_container = view.findViewById(R.id.rim3container);
_container.getLayoutParams().width = screenWidth - thirdScreenWidth * 2;
This layout for 3 equal columns. First element takes 2x2 Result in the picture
Since beta Bootstrap 4 doesn't depend on Tether but Popper.js. All scripts (must be in this order):
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
See the current documentation for the newest script versions.
Bootstrap 4 alpha needs Tether, so you need to include tether.min.js
before you include bootstrap.min.js
, eg.
<script src="https://npmcdn.com/[email protected]/dist/js/tether.min.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/js/bootstrap.min.js"></script>
Surprised no one mentioned a simple if
statement can make sure your loop only gets executed once per format (on the first column, of the first row).
private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// once per format
if (e.ColumnIndex == 0 && e.RowIndex == 0)
{
foreach (DataGridViewRow row in dgv.Rows)
if (row != null)
row.DefaultCellStyle.BackColor = Color.Red;
}
}
I had to transform the divs to list items otherwise all my divs would get that class and only the generated ones should get it Thanks everyone, I love this site and the helpful people on it !!!! You can follow the newbie school project at http://low-budgetwebservice.be/project/webbuilder.html suggestions are always welcome :). So this worked for me:
/* Add Class Heading*/
$(document).ready(function() {
$( document ).on( 'click', 'ul#items li', function () {
$('ul#items li').removeClass('active');
$(this).addClass('active');
});
});
@Ali Shakiba your code needs some modification. Error part:
for (int i = 0; i < myArray.length; i++) {
myStatement.setString(i, myArray[i][1]);
myStatement.setString(i, myArray[i][2]);
}
Updated code:
String myArray[][] = {
{"1-1", "1-2"},
{"2-1", "2-2"},
{"3-1", "3-2"}
};
StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");
for (int i = 0; i < myArray.length - 1; i++) {
mySql.append(", (?, ?)");
}
mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());
for (int i = 0; i < myArray.length; i++) {
myStatement.setString((2 * i) + 1, myArray[i][1]);
myStatement.setString((2 * i) + 2, myArray[i][2]);
}
myStatement.executeUpdate();
Update:
Planned in the scope of 3.7 release
https://github.com/microsoft/TypeScript/issues/33352
You can try to write a custom function like that.
The main advantage of the approach is a type-checking and partial intellisense.
export function nullSafe<T,
K0 extends keyof T,
K1 extends keyof T[K0],
K2 extends keyof T[K0][K1],
K3 extends keyof T[K0][K1][K2],
K4 extends keyof T[K0][K1][K2][K3],
K5 extends keyof T[K0][K1][K2][K3][K4]>
(obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) {
let result: any = obj;
const keysCount = arguments.length - 1;
for (var i = 1; i <= keysCount; i++) {
if (result === null || result === undefined) return result;
result = result[arguments[i]];
}
return result;
}
And usage (supports up to 5 parameters and can be extended):
nullSafe(a, 'b', 'c');
Example on playground.
If you're using jQuery Cookie (https://plugins.jquery.com/cookie/), you can use decimal point or fractions.
As one day is 1
, one minute would be 1 / 1440
(there's 1440 minutes in a day).
So 30 minutes is 30 / 1440 = 0.02083333
.
Final code:
$.cookie("example", "foo", { expires: 30 / 1440, path: '/' });
I've added path: '/'
so that you don't forget that the cookie is set on the current path. If you're on /my-directory/
the cookie is only set for this very directory.
In case someone is interested in another JavaScript TimPicker, I developed and maintain a jQuery plugin that does the job. It works something like EZ Time JS (although I didn't knew about it until 5 minutes ago :D), allowing users to enter time in almost any way they feel comfortable with, and converting the input into a common format.
Checkout the jQuery TimePicker Options page to see it in action.
The command is date
To customise the output there are a myriad of options available, see date --help
for a list.
For example, date '+%A %W %Y %X'
gives Tuesday 34 2013 08:04:22
which is the name of the day of the week, the week number, the year and the time.
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
String truncatedValue = String.format("%f", percentageValue).split("\\.")[0];
solves the purpose
The problem is two fold-
(int) percentageValue
String.format("%.0f", percentageValue)
or new java.text.DecimalFormat("#").format(percentageValue)
as both of these round the decimal part.Use a second class that has only the hover assigned:
HTML
<a class="myclass myclass_hover" href="#">My anchor</a>
CSS
.myclass {
/* all anchor styles */
}
.myclass_hover:hover {
/* example color */
color:#00A;
}
Now you can use Jquery to remove the class, for instance if the element has been clicked:
JQUERY
$('.myclass').click( function(e) {
e.preventDefault();
$(this).removeClass('myclass_hover');
});
Hope this answer is helpful.
We have an app in Google Play and the App Store that will scan barcodes into a web site. The app is called Scan to Web. http://berrywing.com/scantoweb.html
You can even embed a link or button to start the scanner yourself within your web page.
<a href="bwstw://startscanner">Link to start scanner</a>
The developer documentation website for the app covers how to use the app and use JavaScript for processing the barcode scan. http://berrywing.com/scantoweb/#htmlscanbutton
Issue: It's because either you are not stopping your application or the application is already somehow running on the same port somehow.
Solution, Before starting it another time, the earlier application needs to be killed and the port needs to be freed up.
Depending on your platform you can run the below commands to stop the application,
on windows
netstat -anp | find "your application port number"` --> find PID
taskkill /F /PID
on Linux,
netstat -ntpl | grep "your application port number"
kill pid // pid you will get from previous command
on Mac OS
lsof -n -iTCP:"port number"
kill pid //pid you will get from previous command
Time changes everything. Here is a web site which provide online syntax checking for shell script.
I found it is very powerful detecting common errors.
ShellCheck is a static analysis and linting tool for sh/bash scripts. It's mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures.
Haskell source code is available on GitHub!
TLDR if you don't want to read all these great answers :-)
Explicit:
Using DateTimeOffset
because the timezone is forced to UTC+0.
Implicit:
Using DateTime
where you hope everyone sticks to the unwritten rule of the timezone always being UTC+0.
(Side note for devs: explicit is always better than implicit!)
(Side side note for Java devs, C# DateTimeOffset
== Java OffsetDateTime
, read this: https://www.baeldung.com/java-zoneddatetime-offsetdatetime)
I often have this problem with sequences (as opposed to discrete values). If I have a sequence of ints, and I want to SUM them, when the list is empty I'll receive the error "InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.".
I find I can solve this by casting the sequence to a nullable type. SUM and the other aggregate operators don't throw this error if a sequence of nullable types is empty.
So for example something like this
MySum = MyTable.Where(x => x.SomeCondtion).Sum(x => x.AnIntegerValue);
becomes
MySum = MyTable.Where(x => x.SomeCondtion).Sum(x => (int?) x.AnIntegerValue);
The second one will return 0 when no rows match the where clause. (the first one throws an exception when no rows match).
var _login = function (loginData) {_x000D_
_x000D_
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;_x000D_
_x000D_
var deferred = $q.defer();_x000D_
_x000D_
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {_x000D_
_x000D_
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });_x000D_
_x000D_
_authentication.isAuth = true;_x000D_
_authentication.userName = loginData.userName;_x000D_
_x000D_
deferred.resolve(response);_x000D_
_x000D_
}).error(function (err, status) {_x000D_
_logOut();_x000D_
deferred.reject(err);_x000D_
});_x000D_
_x000D_
return deferred.promise;_x000D_
_x000D_
};_x000D_
_x000D_
In my case, I've a sampleViewController
's view added as a subview, then tries to present a popover from the view of sampleViewController
(here self
instead a UIViewController
instance):
[self.view addSubview:sampleViewController.view];
The right way should be below:
// make sure the vc has been added as a child view controller as well
[self addChildViewController:sampleViewController];
[self.view addSubview:sampleViewController.view];
[sampleViewController didMoveToParentViewController:self];
B.t.w., this also works for the case that present a popover form a tableview cell, you just need to make sure the tableview controller has been added as child view controller as well.
This is how to set an image into ImageView
using the setImageResource() method:
ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);
Custom format
[>=1000]#,##0,"K";0
will give you:
Note the comma between the zero and the "K". To display millions or billions, use two or three commas instead.
Add programatically noborder class to specific row to hide it
<style>
.noborder
{
border:none;
}
</style>
<table>
<tr>
<th>heading1</th>
<th>heading2</th>
</tr>
<tr>
<td>content1</td>
<td>content2</td>
</tr>
/*no border for this row */
<tr class="noborder">
<td>content1</td>
<td>content2</td>
</tr>
</table>
Just to help anyone who is looking for a concrete example of what @Mchl was describing, try something like
SELECT * FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'my_schema' AND TABLE_NAME = 'my_table'
AND COLUMN_NAME = 'my_column'`
If it returns false (zero results) then you know the column doesn't exist.
If you want to use some variable, you may use this way:
String value= "your value";
driver.execute_script("document.getElementById('q').value=' "+value+" ' ");
For the sake of completeness, there is also a data.table
solution:
library(data.table)
result <- setDT(df)[, paste0(names(df), "_length") := lapply(.SD, stringr::str_length)]
result
# col1 col2 col1_length col2_length
#1: abc adf qqwe 3 8
#2: abcd d 4 1
#3: a e 1 1
#4: abcdefg f 7 1
For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind
.
Imagine for example a GridView with a ItemTemplate
and EditItemTemplate
. If you use Bind
or Eval
in the ItemTemplate
, there will be no difference. If you use Eval
in the EditItemTemplate
, the value will not be able to be passed to the Update
method of the DataSource
that the grid is bound to.
UPDATE: I've come up with this example:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Data binding demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView
ID="grdTest"
runat="server"
AutoGenerateEditButton="true"
AutoGenerateColumns="false"
DataSourceID="mySource">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="edtName"
runat="server"
Text='<%# Bind("Name") %>'
/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
<asp:ObjectDataSource
ID="mySource"
runat="server"
SelectMethod="Select"
UpdateMethod="Update"
TypeName="MyCompany.CustomDataSource" />
</body>
</html>
And here's the definition of a custom class that serves as object data source:
public class CustomDataSource
{
public class Model
{
public string Name { get; set; }
}
public IEnumerable<Model> Select()
{
return new[]
{
new Model { Name = "some value" }
};
}
public void Update(string Name)
{
// This method will be called if you used Bind for the TextBox
// and you will be able to get the new name and update the
// data source accordingly
}
public void Update()
{
// This method will be called if you used Eval for the TextBox
// and you will not be able to get the new name that the user
// entered
}
}
This actually makes sense, in some way, considering how (relative) paths are treated usually:
string GetFullPath(string path)
{
string baseDir = @"C:\Users\Foo.Bar";
return Path.Combine(baseDir, path);
}
// Get full path for RELATIVE file path
GetFullPath("file.txt"); // = C:\Users\Foo.Bar\file.txt
// Get full path for ROOTED file path
GetFullPath(@"C:\Temp\file.txt"); // = C:\Temp\file.txt
The real question is: Why are paths, which start with "\"
, considered "rooted"? This was new to me too, but it works that way on Windows:
new FileInfo("\windows"); // FullName = C:\Windows, Exists = True
new FileInfo("windows"); // FullName = C:\Users\Foo.Bar\Windows, Exists = False
showInventory(player);
is passing a type as parameter. That's illegal, you need to pass an object.
For example, something like:
player p;
showInventory(p);
I'm guessing you have something like this:
int main()
{
player player;
toDo();
}
which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:
int main()
{
player p;
toDo(p);
}
and
std::string toDo(player& p)
{
//....
showInventory(p);
//....
}
PostgreSQL also supports full POSIX regular expressions:
select * from table where value ~* 'foo|bar|baz';
The ~*
is for a case insensitive match, ~
is case sensitive.
Another option is to use ANY:
select * from table where value like any (array['%foo%', '%bar%', '%baz%']);
select * from table where value ilike any (array['%foo%', '%bar%', '%baz%']);
You can use ANY with any operator that yields a boolean. I suspect that the regex options would be quicker but ANY is a useful tool to have in your toolbox.
If you call your classes tests Maven seems to run them automatically, at least they did for me. Rename the classes and Maven will just go through to verification without running them.
You could use Series.reindex
:
import pandas as pd
idx = pd.date_range('09-01-2013', '09-30-2013')
s = pd.Series({'09-02-2013': 2,
'09-03-2013': 10,
'09-06-2013': 5,
'09-07-2013': 1})
s.index = pd.DatetimeIndex(s.index)
s = s.reindex(idx, fill_value=0)
print(s)
yields
2013-09-01 0
2013-09-02 2
2013-09-03 10
2013-09-04 0
2013-09-05 0
2013-09-06 5
2013-09-07 1
2013-09-08 0
...
Although many of these answers will work, this shows a straightforward example when using CommandField in GridView using the OnClientClick property.
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound"... >
<Columns>
<!-- Data columns here -->
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
ASPX.CS:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
{
(e.Row.Cells[2].Controls[2] as Button).OnClientClick = "return confirm('Do you want to delete this row?');";
}
}
Method 1:\
add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables
Method 2: (if method 1 not work then)
simple open command prompt with "run as administrator"
CREATE PROCEDURE DBO.MY_STORED_PROCEDURE
(@PARAM1VALUE INT,
@PARAM2VALUE INT,
@OUTPARAM VARCHAR(20) OUT)
AS
BEGIN
SELECT * FROM DBO.PARAMTABLENAME WHERE PARAM1VALUE=@PARAM1VALUE
END
DECLARE @OUTPARAM2 VARCHAR(20)
EXEC DBO.MY_STORED_PROCEDURE 1,@OUTPARAM2 OUT
PRINT @OUTPARAM2
Using a custom route component, this is possible in React Router v3.
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var routes = (
<Route path="/" handler={Index}>
<MyRoute myprop="value" path="comments" handler={Comments}/>
<DefaultRoute handler={Dashboard}/>
</Route>
);
As for the <MyRoute>
component code, it should be something like:
import React from 'react';
import { Route } from 'react-router';
import { createRoutesFromReactChildren } from 'react-router/lib//RouteUtils';
const MyRoute = () => <div><MyRoute> elements are for configuration only and should not be rendered</div>;
MyRoute.createRouteFromReactElement = (element, parentRoute) => {
const { path, myprop } = element.props;
// dynamically add crud route
const myRoute = createRoutesFromReactChildren(
<Route path={path} />,
parentRoute
)[0];
// higher-order component to pass myprop as resource to components
myRoute.component = ({ children }) => (
<div>
{React.Children.map(children, child => React.cloneElement(child, { myprop }))}
</div>
);
return myRoute;
};
export default MyRoute;
For more details about the custom route component approach, check out my blog post on the subject: http://marmelab.com/blog/2016/09/20/custom-react-router-component.html
For copy directory use following command
cp -r source Destination
For example
cp -r /home/hasan /opt
For copy file use command without -r
cp /home/file /home/hasan/
Without more details as to what the question is exactly asking, I am going to answer the title of the question,
Create an Array
:
String[] myArray = new String[2];
int[] intArray = new int[2];
// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};
Create an ArrayList
:
ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");
ArrayList<Integer> myNum = new ArrayList<Integer>();
myNum.add(1);
myNum.add(2);
This means, create an ArrayList
of String
and Integer
objects. You cannot use int
because thats a primitive data types, see the link for a list of primitive data types.
Create a Stack
:
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
Create an Queue
: (using LinkedList)
Queue<String> myQueue = new LinkedList<String>();
Queue<Integer> myNumbers = new LinkedList<Integer>();
myQueue.add("Hello");
myQueue.add("World");
myNumbers.add(1);
myNumbers.add(2);
Same thing as an ArrayList
, this declaration means create an Queue
of String
and Integer
objects.
In response to your comment from the other given answer,
i am pretty confused now, why are using string. and what does
<String>
means
We are using String
only as a pure example, but you can add any other object, but the main point is that you use an object not a primitive type. Each primitive data type has their own primitive wrapper class, see link for list of primitive data type's wrapper class.
I have posted some links to explain the difference between the two, but here are a list of primitive types
byte
short
char
int
long
boolean
double
float
Which means, you are not allowed to make an ArrayList
of integer's like so:
ArrayList<int> numbers = new ArrayList<int>();
^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
^ perfectly valid
Also, you can use your own objects, here is my Monster
object I created,
public class Monster {
String name = null;
String location = null;
int age = 0;
public Monster(String name, String loc, int age) {
this.name = name;
this.loc = location;
this.age = age;
}
public void printDetails() {
System.out.println(name + " is from " + location +
" and is " + age + " old.");
}
}
Here we have a Monster
object, but now in our Main.java
class we want to keep a record of all our Monster
's that we create, so let's add them to an ArrayList
public class Main {
ArrayList<Monster> myMonsters = new ArrayList<Monster>();
public Main() {
Monster yetti = new Monster("Yetti", "The Mountains", 77);
Monster lochness = new Monster("Lochness Monster", "Scotland", 20);
myMonsters.add(yetti); // <-- added Yetti to our list
myMonsters.add(lochness); // <--added Lochness to our list
for (Monster m : myMonsters) {
m.printDetails();
}
}
public static void main(String[] args) {
new Main();
}
}
(I helped my girlfriend's brother with a Java game, and he had to do something along those lines as well, but I hope the example was well demonstrated)
adb shell
su
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
This assumes your /system is yaffs2 and that it's at /dev/block/mtdblock3 the easier/better way to do this on most Android phones is:
adb shell
su
mount -o remount,rw /system
Done. This just says remount /system read-write, you don't have to specify filesystem or mount location.
You can cut off the milliseconds using a Calendar
:
java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));
Output:
2014-04-04 10:10:17.78
2014-04-04 10:10:17.0
Lambda Expressions
Func<int, int, int> add = (a, b) => (a + b);
Obscure String Formats
Console.WriteLine("{0:D10}", 2); // 0000000002
Dictionary<string, string> dict = new Dictionary<string, string> {
{"David", "C#"},
{"Johann", "Perl"},
{"Morgan", "Python"}
};
Console.WriteLine( "{0,10} {1, 10}", "Programmer", "Language" );
Console.WriteLine( "-".PadRight( 21, '-' ) );
foreach (string key in dict.Keys)
{
Console.WriteLine( "{0, 10} {1, 10}", key, dict[key] );
}
try adding this in AppDelegate applicationWillEnterForeground.
func applicationWillEnterForeground(_ application: UIApplication) {
// makes viewWillAppear run
self.window?.rootViewController?.beginAppearanceTransition(true, animated: false)
self.window?.rootViewController?.endAppearanceTransition()
}
Random r = new Random();
List<string> list = new List(originalArray);
List<string> randomStrings = new List();
while(list.Count > 0)
{
int i = r.Random(list.Count);
randomStrings.Add(list[i]);
list.RemoveAt(i);
}
Instead of removeClass and addClass, you can also do it like this:
$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');
Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.
That is neither a good idea in terms of peformance nor in terms of fail-safety.
There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:
In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.
So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.
If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).
Conclusion:
using-statement
to dispose and close(in case of Connections) implicitelyThat's true not only for Connections(although most noticable). Every object implementing IDisposable
should be disposed(simplest by using-statement
), all the more in the System.Data.SqlClient
namespace.
All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.
Edit: Here's a possible implementation of your retrievePromotion
-method:
public Promotion retrievePromotion(int promotionID)
{
Promotion promo = null;
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
using (var da = new SqlDataAdapter(queryString, connection))
{
// you could also use a SqlDataReader instead
// note that a DataTable does not need to be disposed since it does not implement IDisposable
var tblPromotion = new DataTable();
// avoid SQL-Injection
da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
try
{
connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise
da.Fill(tblPromotion);
if (tblPromotion.Rows.Count != 0)
{
var promoRow = tblPromotion.Rows[0];
promo = new Promotion()
{
promotionID = promotionID,
promotionTitle = promoRow.Field<String>("PromotionTitle"),
promotionUrl = promoRow.Field<String>("PromotionURL")
};
}
}
catch (Exception ex)
{
// log this exception or throw it up the StackTrace
// we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
throw;
}
}
}
return promo;
}
In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.
In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.
With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.
You can create a function:
function changeInputType(oldObj, oTyp, nValue) {
var newObject = document.createElement('input');
newObject.type = oTyp;
if(oldObj.size) newObject.size = oldObj.size;
if(oldObj.value) newObject.value = nValue;
if(oldObj.name) newObject.name = oldObj.name;
if(oldObj.id) newObject.id = oldObj.id;
if(oldObj.className) newObject.className = oldObj.className;
oldObj.parentNode.replaceChild(newObject,oldObj);
return newObject;
}
And you do a call like:
changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);
You can simplify the code by introducing an extra variable.
#include <string.h>
#include <stdio.h>
int main()
{
char str[100], *s = str, *t = NULL;
strcpy(str, "a space delimited string");
while ((t = strtok(s, " ")) != NULL) {
s = NULL;
printf(":%s:\n", t);
}
return 0;
}
For files encoding...
public class FRomUtf8ToIso {
static File input = new File("C:/Users/admin/Desktop/pippo.txt");
static File output = new File("C:/Users/admin/Desktop/ciccio.txt");
public static void main(String[] args) throws IOException {
BufferedReader br = null;
FileWriter fileWriter = new FileWriter(output);
try {
String sCurrentLine;
br = new BufferedReader(new FileReader( input ));
int i= 0;
while ((sCurrentLine = br.readLine()) != null) {
byte[] isoB = encode( sCurrentLine.getBytes() );
fileWriter.write(new String(isoB, Charset.forName("ISO-8859-15") ) );
fileWriter.write("\n");
System.out.println( i++ );
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
static byte[] encode(byte[] arr){
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-15");
ByteBuffer inputBuffer = ByteBuffer.wrap( arr );
// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);
// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();
return outputData;
}
}
using commands module
import commands
"""
Get high load process details
"""
result = commands.getoutput("ps aux | sort -nrk 3,3 | head -n 1")
print result -- python 2x
print (result) -- python 3x
Match
objects are always true, and None
is returned if there is no match. Just test for trueness.
Code:
>>> st = 'bar'
>>> m = re.match(r"ba[r|z|d]",st)
>>> if m:
... m.group(0)
...
'bar'
Output = bar
If you want search
functionality
>>> st = "bar"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m is not None:
... m.group(0)
...
'bar'
and if regexp
not found than
>>> st = "hello"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m:
... m.group(0)
... else:
... print "no match"
...
no match
As @bukzor mentioned if st = foo bar
than match will not work. So, its more appropriate to use re.search
.
Here a .NET C# similar implementation of a timespan class that supports days, hours, minutes and seconds. This implementation also supports negative timespans.
const MILLIS_PER_SECOND = 1000;
const MILLIS_PER_MINUTE = MILLIS_PER_SECOND * 60; // 60,000
const MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60; // 3,600,000
const MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; // 86,400,000
export class TimeSpan {
private _millis: number;
private static interval(value: number, scale: number): TimeSpan {
if (Number.isNaN(value)) {
throw new Error("value can't be NaN");
}
const tmp = value * scale;
const millis = TimeSpan.round(tmp + (value >= 0 ? 0.5 : -0.5));
if ((millis > TimeSpan.maxValue.totalMilliseconds) || (millis < TimeSpan.minValue.totalMilliseconds)) {
throw new TimeSpanOverflowError("TimeSpanTooLong");
}
return new TimeSpan(millis);
}
private static round(n: number): number {
if (n < 0) {
return Math.ceil(n);
} else if (n > 0) {
return Math.floor(n);
}
return 0;
}
private static timeToMilliseconds(hour: number, minute: number, second: number): number {
const totalSeconds = (hour * 3600) + (minute * 60) + second;
if (totalSeconds > TimeSpan.maxValue.totalSeconds || totalSeconds < TimeSpan.minValue.totalSeconds) {
throw new TimeSpanOverflowError("TimeSpanTooLong");
}
return totalSeconds * MILLIS_PER_SECOND;
}
public static get zero(): TimeSpan {
return new TimeSpan(0);
}
public static get maxValue(): TimeSpan {
return new TimeSpan(Number.MAX_SAFE_INTEGER);
}
public static get minValue(): TimeSpan {
return new TimeSpan(Number.MIN_SAFE_INTEGER);
}
public static fromDays(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_DAY);
}
public static fromHours(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_HOUR);
}
public static fromMilliseconds(value: number): TimeSpan {
return TimeSpan.interval(value, 1);
}
public static fromMinutes(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_MINUTE);
}
public static fromSeconds(value: number): TimeSpan {
return TimeSpan.interval(value, MILLIS_PER_SECOND);
}
public static fromTime(hours: number, minutes: number, seconds: number): TimeSpan;
public static fromTime(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan;
public static fromTime(daysOrHours: number, hoursOrMinutes: number, minutesOrSeconds: number, seconds?: number, milliseconds?: number): TimeSpan {
if (milliseconds != undefined) {
return this.fromTimeStartingFromDays(daysOrHours, hoursOrMinutes, minutesOrSeconds, seconds, milliseconds);
} else {
return this.fromTimeStartingFromHours(daysOrHours, hoursOrMinutes, minutesOrSeconds);
}
}
private static fromTimeStartingFromHours(hours: number, minutes: number, seconds: number): TimeSpan {
const millis = TimeSpan.timeToMilliseconds(hours, minutes, seconds);
return new TimeSpan(millis);
}
private static fromTimeStartingFromDays(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan {
const totalMilliSeconds = (days * MILLIS_PER_DAY) +
(hours * MILLIS_PER_HOUR) +
(minutes * MILLIS_PER_MINUTE) +
(seconds * MILLIS_PER_SECOND) +
milliseconds;
if (totalMilliSeconds > TimeSpan.maxValue.totalMilliseconds || totalMilliSeconds < TimeSpan.minValue.totalMilliseconds) {
throw new TimeSpanOverflowError("TimeSpanTooLong");
}
return new TimeSpan(totalMilliSeconds);
}
constructor(millis: number) {
this._millis = millis;
}
public get days(): number {
return TimeSpan.round(this._millis / MILLIS_PER_DAY);
}
public get hours(): number {
return TimeSpan.round((this._millis / MILLIS_PER_HOUR) % 24);
}
public get minutes(): number {
return TimeSpan.round((this._millis / MILLIS_PER_MINUTE) % 60);
}
public get seconds(): number {
return TimeSpan.round((this._millis / MILLIS_PER_SECOND) % 60);
}
public get milliseconds(): number {
return TimeSpan.round(this._millis % 1000);
}
public get totalDays(): number {
return this._millis / MILLIS_PER_DAY;
}
public get totalHours(): number {
return this._millis / MILLIS_PER_HOUR;
}
public get totalMinutes(): number {
return this._millis / MILLIS_PER_MINUTE;
}
public get totalSeconds(): number {
return this._millis / MILLIS_PER_SECOND;
}
public get totalMilliseconds(): number {
return this._millis;
}
public add(ts: TimeSpan): TimeSpan {
const result = this._millis + ts.totalMilliseconds;
return new TimeSpan(result);
}
public subtract(ts: TimeSpan): TimeSpan {
const result = this._millis - ts.totalMilliseconds;
return new TimeSpan(result);
}
}
const ts = TimeSpan.zero;
From milliseconds
const milliseconds = 10000; // 1 second
// by using the constructor
const ts1 = new TimeSpan(milliseconds);
// or as an alternative you can use the static factory method
const ts2 = TimeSpan.fromMilliseconds(milliseconds);
From seconds
const seconds = 86400; // 1 day
const ts = TimeSpan.fromSeconds(seconds);
From minutes
const minutes = 1440; // 1 day
const ts = TimeSpan.fromMinutes(minutes);
From hours
const hours = 24; // 1 day
const ts = TimeSpan.fromHours(hours);
From days
const days = 1; // 1 day
const ts = TimeSpan.fromDays(days);
From time with given hours, minutes and seconds
const hours = 1;
const minutes = 1;
const seconds = 1;
const ts = TimeSpan.fromTime(hours, minutes, seconds);
From time2 with given days, hours, minutes, seconds and milliseconds
const days = 1;
const hours = 1;
const minutes = 1;
const seconds = 1;
const milliseconds = 1;
const ts = TimeSpan.fromTime(days, hours, minutes, seconds, milliseconds);
From maximal safe integer
const ts = TimeSpan.maxValue;
From minimal safe integer
const ts = TimeSpan.minValue;
From minimal safe integer
const ts = TimeSpan.minValue;
Add
const ts1 = TimeSpan.fromDays(1);
const ts2 = TimeSpan.fromHours(1);
const ts = ts1.add(ts2);
console.log(ts.days); // 1
console.log(ts.hours); // 1
console.log(ts.minutes); // 0
console.log(ts.seconds); // 0
console.log(ts.milliseconds); // 0
Subtract
const ts1 = TimeSpan.fromDays(1);
const ts2 = TimeSpan.fromHours(1);
const ts = ts1.subtract(ts2);
console.log(ts.days); // 0
console.log(ts.hours); // 23
console.log(ts.minutes); // 0
console.log(ts.seconds); // 0
console.log(ts.milliseconds); // 0
Getting the intervals
const days = 1;
const hours = 1;
const minutes = 1;
const seconds = 1;
const milliseconds = 1;
const ts = TimeSpan.fromTime2(days, hours, minutes, seconds, milliseconds);
console.log(ts.days); // 1
console.log(ts.hours); // 1
console.log(ts.minutes); // 1
console.log(ts.seconds); // 1
console.log(ts.milliseconds); // 1
console.log(ts.totalDays) // 1.0423726967592593;
console.log(ts.totalHours) // 25.016944722222224;
console.log(ts.totalMinutes) // 1501.0166833333333;
console.log(ts.totalSeconds) // 90061.001;
console.log(ts.totalMilliseconds); // 90061001;
See also here: https://github.com/erdas/timespan
Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.
new Double(99.9999).intValue()
To add a header just add the following code to the location block where you want to add the header:
location some-location {
add_header X-my-header my-header-content;
}
Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.
If you are running the
mvn spring-boot:run
from the command line, make sure you are in the directory that contains the pom.xml file. Otherwise, you will run into the No plugin found for prefix 'spring-boot' in the current project and in the plugin groups error.
If you take advantage of width: 100vw;
and height: 100vh;
, the object with these styles applied will stretch to the full width and height of the device.
Also note, there are times padding and margins can get added to your view, by browsers and the like. I added a *
global no padding and margins so you can see the difference. Keep this in mind.
*{_x000D_
box-sizing: border-box;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
display: grid;_x000D_
border-style: solid;_x000D_
border-color: red;_x000D_
grid-template-columns: repeat(3, 1fr);_x000D_
grid-template-rows: repeat(3, 1fr);_x000D_
grid-gap: 10px;_x000D_
width: 100vw;_x000D_
height: 100vh;_x000D_
}_x000D_
.one {_x000D_
border-style: solid;_x000D_
border-color: blue;_x000D_
grid-column: 1 / 3;_x000D_
grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
border-style: solid;_x000D_
border-color: yellow;_x000D_
grid-column: 2 / 4;_x000D_
grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
border-style: solid;_x000D_
border-color: violet;_x000D_
grid-row: 2 / 5;_x000D_
grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
border-style: solid;_x000D_
border-color: aqua;_x000D_
grid-column: 3;_x000D_
grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
border-style: solid;_x000D_
border-color: green;_x000D_
grid-column: 2;_x000D_
grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
border-style: solid;_x000D_
border-color: purple;_x000D_
grid-column: 3;_x000D_
grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
<div class="one">One</div>_x000D_
<div class="two">Two</div>_x000D_
<div class="three">Three</div>_x000D_
<div class="four">Four</div>_x000D_
<div class="five">Five</div>_x000D_
<div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
You only need to copy <iframe> from the YouTube Embed section (click on SHARE below the video and then EMBED and copy the entire iframe).
I just wrote my little subclass of UIView that has ability to produce native iOS 7 blur on any custom view. It uses UIToolbar but in a safe way for changing it's frame, bounds, color and alpha with real-time animation.
Please let me know if you notice any problems.
Using the java.time
framework built into Java 8 and later.
import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;
long epoch = Long.parseLong("1081157732");
Instant instant = Instant.ofEpochSecond(epoch);
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); # ZonedDateTime = 2004-04-05T09:35:32Z[UTC]
In this case you should better use ZonedDateTime
to mark it as date in UTC time zone because Epoch is defined in UTC in Unix time used by Java.
ZoneOffset
contains a handy constant for the UTC time zone, as seen in last line above. Its superclass, ZoneId
can be used to adjust into other time zones.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
It's a destructor. The function is guaranteed to be called when the object goes out of scope.
In android resources it's rather simple
<string name="smth">%1$02d</string>
I met the same challenge while trying to install [email protected].
And after looking at the current official documentation, and having read the answers above, i noticed that you might not necessarily have to install node-gyp nor install windows-build tools. This is what it says, here about installing node-gyp on windows. Remember node-gyp is involved in the installation process of node-sass. And you don't really have to re-install another python version.
This is the savior, configure the python path that "npm" should look for while installing any packages that require build-tools.
C:\> npm config set python /Python36/python
I had installed python3.6.3, on windows-7, there.
Using join
:
join -t $'\t' -o 1.2,1.1 file.txt file.txt
Notes:
-t $'\t'
In GNU join
the more intuitive -t '\t'
without the $
fails, (coreutils v8.28 and earlier?); it's probably a bug that a workaround like $
should be necessary. See: unix join separator char.
join
needs two filenames, even though there's just one file being worked on. Using the same name twice tricks join
into performing the desired action.
For systems with low resources join
offers a smaller footprint than some of the tools used in other answers:
wc -c $(realpath `which cut join sed awk perl`) | head -n -1
43224 /usr/bin/cut
47320 /usr/bin/join
109840 /bin/sed
658072 /usr/bin/gawk
2093624 /usr/bin/perl
If someone is looking for another option for Git Lab and the options above do not work, then we have another option. For a local installation of Git Lab server, we have found that the approach, below, allows us to include the package dependency. We generated and use an access token to do so.
$ npm install --save-dev https://git.yourdomain.com/userOrGroup/gitLabProjectName/repository/archive.tar.gz?private_token=InsertYourAccessTokenHere
Of course, if one is using an access key this way, it should have a limited set of permissions.
Good luck!
To understand the use of "SET SERVEROUTPUT ON" I will take an example
DECLARE
a number(10) :=10;
BEGIN
dbms_output.put_line(a) ;
dbms_output.put_line('Hello World ! ') ;
END ;
With an output : PL/SQl procedure successfully completed i.e without the expected output
And the main reason behind is that ,whatever we pass inside dbms_output.put_line(' ARGUMENT '/VALUES) i.e. ARGUMENT/VALUES , is internally stored inside a buffer in SGA(Shared Global Area ) memory area upto 2000 bytes .
*NOTE :***However one should note that this buffer is only created when we use **dbms_output package. And we need to set the environment variable only once for a session !!
And in order to fetch it from that buffer we need to set the environment variable for the session . It makes a lot of confusion to the beginners that we are setting the server output on ( because of its nomenclature ) , but unfortunately its nothing like that . Using SET SERVER OUTPUT ON are just telling the PL/SQL engine that
*Hey please print the ARGUMENT/VALUES that I will be passing inside dbms_output.put_line
and in turn PL/SQl run time engine prints the argument on the main console .
I think I am clear to you all . Wish you all the best . To know more about it with the architectural structure of Oracle Server Engine you can see my answer on Quora http://qr.ae/RojAn8
And to answer your question "One should use SET SERVER OUTPUT in the beginning of the session. "
Above many of the answers are good but none of the worked for me fully. So i combined the answer from @nmr and got this one.
final Dialog d = new Dialog(getActivity());
// d.getWindow().setBackgroundDrawable(R.color.action_bar_bg);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.dialog_box_shipment_detail);
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE); // for activity use context instead of getActivity()
Display display = wm.getDefaultDisplay(); // getting the screen size of device
Point size = new Point();
display.getSize(size);
int width = size.x - 20; // Set your heights
int height = size.y - 80; // set your widths
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = width;
lp.height = height;
d.getWindow().setAttributes(lp);
d.show();
What are you doing: (I am using bytes instead of in for better reading)
You start with int *ap
and so on, so your (your computers) memory looks like this:
-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory --------
100: something <- here is *ap
101: 41 <- here starts a[]
102: 42
103: 43
104: 44
105: 45
106: something <- here waits x
lets take a look waht happens when (print short cut for ...print("$d", ...)
print a[0] -> 41 //no surprise
print a -> 101 // because a points to the start of the array
print *a -> 41 // again the first element of array
print a+1 -> guess? 102
print *(a+1) -> whats behind 102? 42 (we all love this number)
and so on, so a[0] is the same as *a, a[1] = *(a+1), ....
a[n] just reads easier.
now, what happens at line 9?
ap=a[4] // we know a[4]=*(a+4) somehow *105 ==> 45
// warning! converting int to pointer!
-------------- your memory --------
100: 45 <- here is *ap now 45
x = *ap; // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang! // dont touch neighbours garden
So the "warning" is not just a warning it's a severe error.
Personally I prefer this method. This will overwrite the file on the destination, removes the source file and also prevent removing the source file when the copy fails.
string source = @"c:\test\SomeFile.txt";
string destination = @"c:\test\test\SomeFile.txt";
try
{
File.Copy(source, destination, true);
File.Delete(source);
}
catch
{
//some error handling
}
I faced 1.40s
while working with a pure laravel in development area!
the problem was using: php artisan serve
to run the webserver
when I used apache webserver (or NGINX) instead for the same code I got it down to 153ms
I got a similar error and it took me a while to realize that in my case I named the array variable payInvoices and the function also payInvoices. It confused AngularJs. Once I changed the name to processPayments() it finally worked. Just wanted to share this error and solution as it took me long time to figure this out.
void
is a reserved JavaScript keyword. It evaluates the expression and always returns undefined
.
I would also recommend to use all the CSS properties in a different file than the HTML file, so you can have your code organized better.
So to make your img responsive, I would do:
First, name your <img>
tag using a class
or id
attribute in your HTML file:
<img src="IMAGE LINK" border="0" class="responsive-image" alt="Null">
Then, in my CSS file I would make the changes to make it responsive:
.responsive-image {
height: auto;
width: 100%;
}
This is usually happens when the remote is down/unavailable; or the remote machine doesn't have ssh installed; or a firewall doesn't allow a connection to be established to the remote host.
ssh
returns 255 when an error occurred or 255 is returned by the remote script:
EXIT STATUS
ssh exits with the exit status of the remote command or
with 255 if an error occurred.
Usually you would an error message something similar to:
ssh: connect to host host.domain.com port 22: No route to host
Or
ssh: connect to host HOSTNAME port 22: Connection refused
Check-list:
What happens if you run the ssh command directly from the command line?
Are you able to ping
that machine?
Does the remote has ssh installed?
If installed, then is the ssh service running?
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: http://vimeo.com/18399381 and here vimeo . com / 18232653
They are not one and the same. Let me explain the difference.
forEach
: This iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database)
map
: This iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase). It does not mutate the array on which it is called (although if passed a callback function, it may do so).
References
You need to either provide the absolute path to data.csv, or run your script in the same directory as data.csv.
I have added few lines inside package.json:
"scripts": {
...
"clean": "rmdir /s /q node_modules",
"reinstall": "npm run clean && npm install",
"rebuild": "npm run clean && npm install && rmdir /s /q dist && npm run build --prod",
...
}
If you want to clean
only you can use this rimraf node_modules
or rm -rf node_modules
.
It works fine
I have modified the solution of @yogi. The addition is that when the file is of incorrect format I reset the input element value.
function checkFile(sender, validExts) {
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0 && fileExt != "") {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
$(sender).val("");
return false;
}
else return true;
}
I have custom verification buildin, because in open file window the user can still choose the options "All files ('*')", regardless if I explicitly set the accept attribute in input element.
usually when i work with remote location teams it is important for me that i have prior knowledge what change done by other teams in same file, before i follow git stages untrack-->staged-->commit for that i wrote an bash script which help me to avoid unnecessary resolve merge conflict with remote team or make new local branch and compare and merge on main branch
#set -x
branchname=`git branch | grep -F '*' | awk '{print $2}'`
echo $branchname
git fetch origin ${branchname}
for file in `git status | grep "modified" | awk "{print $2}" `
do
echo "PLEASE CHECK OUT GIT DIFF FOR "$file
git difftool FETCH_HEAD $file ;
done
in above script i fetch remote main branch (not necessary its master branch)to FETCH_HEAD them make a list of my modified file only and compare modified files to git difftool
here many difftool supported by git, i configure 'Meld Diff Viewer' for good GUI comparison .
I wanted to just add this as a comment to the previous answer, but I can't. I tried Dave Sexton's answer but had problems if the count was 1. This forces an array even if one object is returned.
([System.Object[]](gci c:\pstback\ -Filter *.pst |
? { $_.LastWriteTime -gt (Get-Date).AddDays(-3)})).Count
It still doesn't return zero if empty, but testing '-lt 1' works.
If the string contains Unicode data (strictly speaking, non-BMP characters) the other methods that have been posted will corrupt it, because you cannot swap the order of high and low surrogate code units when reversing the string. (More information about this can be found on my blog.)
The following code sample will correctly reverse a string that contains non-BMP characters, e.g., "\U00010380\U00010381" (Ugaritic Letter Alpa, Ugaritic Letter Beta).
public static string Reverse(this string input)
{
if (input == null)
throw new ArgumentNullException("input");
// allocate a buffer to hold the output
char[] output = new char[input.Length];
for (int outputIndex = 0, inputIndex = input.Length - 1; outputIndex < input.Length; outputIndex++, inputIndex--)
{
// check for surrogate pair
if (input[inputIndex] >= 0xDC00 && input[inputIndex] <= 0xDFFF &&
inputIndex > 0 && input[inputIndex - 1] >= 0xD800 && input[inputIndex - 1] <= 0xDBFF)
{
// preserve the order of the surrogate pair code units
output[outputIndex + 1] = input[inputIndex];
output[outputIndex] = input[inputIndex - 1];
outputIndex++;
inputIndex--;
}
else
{
output[outputIndex] = input[inputIndex];
}
}
return new string(output);
}
Here's another way to do it:
Assuming you installed it with MacPorts, which can be done by doing:
sudo port install fish
Your shell will be located in /opt/local/bin/fish
.
You need to tell OSX that this is a valid shell. To do that, add this path to the end of the /etc/shells
file.
Once you've done this, you can change the shell by going to System Preferences -> Accounts. Click on the Lock to allow changes. Right-click on the account, and choose "Advanced Options...". In the "Login shell" field, add the path to fish.
I went searching around for a similar question - the way I've managed to initialize a Git repository for an existing project file is this (disclaimer: this is done in Visual Studio 2013 Express, without a Team Foundation Server setup):
That did it for me - assuming Git is set up for you, you can go to menu View ? Team Explorer, then double click the repository for your project file, and make your initial commit (making sure to add whatever files you'd like).
Use getJSON
$.getJSON(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
});
Detail look here http://api.jquery.com/jQuery.getJSON/
Make sure you have full-text search feature installed.
Create full-text search catalog.
use AdventureWorks
create fulltext catalog FullTextCatalog as default
select *
from sys.fulltext_catalogs
Create full-text search index.
create fulltext index on Production.ProductDescription(Description)
key index PK_ProductDescription_ProductDescriptionID
Before you create the index, make sure:
- you don't already have full-text search index on the table as only one full-text search index allowed on a table
- a unique index exists on the table. The index must be based on single-key column, that does not allow NULL.
- full-text catalog exists. You have to specify full-text catalog name explicitly if there is no default full-text catalog.
You can do step 2 and 3 in SQL Sever Management Studio. In object explorer, right click on a table, select Full-Text index
menu item and then Define Full-Text Index...
sub-menu item. Full-Text indexing wizard will guide you through the process. It will also create a full-text search catalog for you if you don't have any yet.
You can find more info at MSDN
Work for me in CentOS:
$ service mysql stop
$ mysqld --skip-grant-tables &
$ mysql -u root mysql
mysql> FLUSH PRIVILEGES;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
$ service mysql restart
In Pro Angular-6 book is detailed as below;
invalid: This property returns true if the element’s contents are invalid and false otherwise.
pristine: This property returns true if the element’s contents have not been changed.
From my experience, this will show up most of the time when the class you are trying to call has some bugs and cannot be compiled. Check if the class that is not being reflected can be executed at its own.
In Java I used encoding "IBM850" to write the file. That solved the problem.
start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.
start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh
hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.
Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,
bin/hadoop-daemon.sh start datanode
Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.
Hope this answers your query.
This is what I've done to automatically add my local project node_modules/.bin
path to PATH
. In ~/.profile
I added:
if [ -d "$PWD/node_modules/.bin" ]; then
PATH="$PWD/node_modules/.bin"
fi
Then reload your bash profile: source ~/.profile
Try this
<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */
22 bytes, if you do it like this:
System.Guid guid = System.Guid.NewGuid();
byte[] guidbytes = guid.ToByteArray();
string uuid = Convert.ToBase64String(guidbytes).Trim('=');
Exports:
You have two types of exports:
Syntax:
// Module A
export const importantData_1 = 1;
export const importantData_2 = 2;
export default function foo () {}
Imports:
The type of export (i.e., named or default exports) affects how to import something:
Syntax:
// Module B, imports from module A which is located in the same directory
import { importantData_1 , importantData_2 } from './A'; // For our named imports
// Syntax single named import:
// import { importantData_1 }
// For our default export (foo), the name choice is arbitrary
import ourFunction from './A';
Things of interest:
Whenever you want to rename a named import this is possible via aliases. The syntax for this is the following:
import { importantData_1 as myData } from './A';
Now we have imported importantData_1
, but the identifier is myData
instead of importantData_1
.
If the delete is recent enough (Like an Oh-NO! moment) you should still have a message:
Deleted branch <branch name> (was abcdefghi).
you can still run:
git checkout abcdefghi
git checkout -b <some new branch name or the old one>
I would like to suggest to use react-native-vector-icons to import icons to your project. As you use vector icons, you don't need to worry much on icon scaling side. While using the package you are able to use all popular icon set such as fontawesome, ionicons etc..
Besides these iconsets you can also bring your own icons too to your react-native project by packing your icons as a ttf file and you can import that ttf directly to both android and ios project. You can utilise the same react-native-vector-icons library to manage those icons
Here is a detailed procedure to setup custom icons
https://medium.com/bam-tech/add-custom-icons-to-your-react-native-application-f039c244386c
Template refs section tells how this has been unified:
ref="myEl"
; :ref=
with a v-for
const myEl = ref(null)
and expose it from setup
The reference carries the DOM element from mounting onwards.
Returning pure array is slightly faster than returning an array of objects.
one of the ways I used it :
protected List<Field> getFieldsWithJsonView(Class sourceClass, Class jsonViewName){
List<Field> fields = new ArrayList<>();
for (Field field : sourceClass.getDeclaredFields()) {
JsonView jsonViewAnnotation = field.getDeclaredAnnotation(JsonView.class);
if(jsonViewAnnotation!=null){
boolean jsonViewPresent = false;
Class[] viewNames = jsonViewAnnotation.value();
if(jsonViewName!=null && Arrays.asList(viewNames).contains(jsonViewName) ){
fields.add(field);
}
}
}
return fields;
}
Brendan is correct. You can edit the Select command to edit a filtered list of records. For instance "WHERE dept_no = 200"
.
My variant: stored procedure that takes table name, field names and delimiter as arguments. Inspired by post http://www.marcogoncalves.com/2011/03/mysql-split-column-string-into-rows/
delimiter $$
DROP PROCEDURE IF EXISTS split_value_into_multiple_rows $$
CREATE PROCEDURE split_value_into_multiple_rows(tablename VARCHAR(20),
id_column VARCHAR(20), value_column VARCHAR(20), delim CHAR(1))
BEGIN
DECLARE id INT DEFAULT 0;
DECLARE value VARCHAR(255);
DECLARE occurrences INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE splitted_value VARCHAR(255);
DECLARE done INT DEFAULT 0;
DECLARE cur CURSOR FOR SELECT tmp_table1.id, tmp_table1.value FROM
tmp_table1 WHERE tmp_table1.value IS NOT NULL AND tmp_table1.value != '';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET @expr = CONCAT('CREATE TEMPORARY TABLE tmp_table1 (id INT NOT NULL, value VARCHAR(255)) ENGINE=Memory SELECT ',
id_column,' id, ', value_column,' value FROM ',tablename);
PREPARE stmt FROM @expr;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
DROP TEMPORARY TABLE IF EXISTS tmp_table2;
CREATE TEMPORARY TABLE tmp_table2 (id INT NOT NULL, value VARCHAR(255) NOT NULL) ENGINE=Memory;
OPEN cur;
read_loop: LOOP
FETCH cur INTO id, value;
IF done THEN
LEAVE read_loop;
END IF;
SET occurrences = (SELECT CHAR_LENGTH(value) -
CHAR_LENGTH(REPLACE(value, delim, '')) + 1);
SET i=1;
WHILE i <= occurrences DO
SET splitted_value = (SELECT TRIM(SUBSTRING_INDEX(
SUBSTRING_INDEX(value, delim, i), delim, -1)));
INSERT INTO tmp_table2 VALUES (id, splitted_value);
SET i = i + 1;
END WHILE;
END LOOP;
SELECT * FROM tmp_table2;
CLOSE cur;
DROP TEMPORARY TABLE tmp_table1;
END; $$
delimiter ;
Usage example (normalization):
CALL split_value_into_multiple_rows('my_contacts', 'contact_id', 'interests', ',');
CREATE TABLE interests (
interest_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
interest VARCHAR(30) NOT NULL
) SELECT DISTINCT value interest FROM tmp_table2;
CREATE TABLE contact_interest (
contact_id INT NOT NULL,
interest_id INT NOT NULL,
CONSTRAINT fk_contact_interest_my_contacts_contact_id FOREIGN KEY (contact_id) REFERENCES my_contacts (contact_id),
CONSTRAINT fk_contact_interest_interests_interest_id FOREIGN KEY (interest_id) REFERENCES interests (interest_id)
) SELECT my_contacts.contact_id, interests.interest_id
FROM my_contacts, tmp_table2, interests
WHERE my_contacts.contact_id = tmp_table2.id AND interests.interest = tmp_table2.value;
Build solution only builds those projects which have changed in the solution, and does not effect assemblies that have not changed,
ReBuild first cleans, all the assemblies from the solution and then builds entire solution regardless of changes done.
Clean, simply cleans the solution.
To get mod_rewrite to work for me in Apache 2.4, I had to add the "Require all granted" line below.
<Directory /var/www>
# Required if running apache > 2.4
Require all granted
RewriteEngine on
RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L]
</Directory>
supposedly a similar requirement exists for Apache 2.2 as well, if you're using that:
<Directory /var/www>
# Required if running apache 2.2
Order allow,deny
Allow from all
RewriteEngine on
RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L]
</Directory>
Note that an ErrorDocument 404
directive can sometimes override these things as well, so if it's not working try commenting out your ErrorDocument directive and see if it works. The above example can be used to ensure a site isn't served from cache by including a subfolder in the path, though the files reside at the root of the server.
not right way
git remote set-url origin [email protected]:erhandemirciinstagram/..
right way
git remote set-url origin https://[email protected]/..
You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.
There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use
&
infoo(&$a);
.
For example, instead of using:
// Wrong way!
myFunc(&$arg); # Deprecated pass-by-reference argument
function myFunc($arg) { }
Use:
// Right way!
myFunc($var); # pass-by-value argument
function myFunc(&$arg) { }
If you have no concrete implementations of the class and the methods aren't static
whats the point of testing them? If you have a concrete class then you'll be testing those methods as part of the concrete class's public API.
I know what you are thinking "I don't want to test these methods over and over thats the reason I created the abstract class", but my counter argument to that is that the point of unit tests is to allow developers to make changes, run the tests, and analyze the results. Part of those changes could include overriding your abstract class's methods, both protected
and public
, which could result in fundamental behavioral changes. Depending on the nature of those changes it could affect how your application runs in unexpected, possibly negative ways. If you have a good unit testing suite problems arising from these types changes should be apparent at development time.
If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image:
build: ./dir
image: webapp:tag
This results in an image named webapp
and tagged tag
, built from ./dir
.
That Macvim is obsolete. Use https://github.com/macvim-dev/macvim instead
See the FAQ (https://github.com/b4winckler/macvim/wiki/FAQ#how-can-i-open-files-from-terminal) for how to install the mvim
script for launching from the command line
I know this thread is old and there are already comprehensive answers.
Just in case you don't know this:
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
You don't have to hardcode IE version number as
<meta http-equiv="X-UA-Compatible" content="IE=9" >
This is what you are looking for:
^((?!(abc|def)).)*$
the explanation is here: Regular expression to match a line that doesn't contain a word?
A similar question was asked about doing this on an ASP page (link) and the consensus over there was that it was not possible to do with recaptcha. It seems that multiple forms on a single page must share the captcha, unless you're willing to use a different captcha. If you are not locked into recaptcha a good library to take a look at is the Zend Frameworks Zend_Captcha component (link). It contains a few
What ultimately worked for me was the following steps:
Another approach can be to store a key:value pair as a simple class using the following syntax :
<div id="my_div" class="foo:'bar'">...</div>
This is valid and can easily be retrieved with jQuery selectors or a custom made function.
Lodash is inspired by Underscore.js, but nowadays it is a superior solution. You can make your custom builds, have a higher performance, support AMD and have great extra features. Check this Lodash vs. Underscore.js benchmarks on jsperf and... this awesome post about Lodash:
One of the most useful feature when you work with collections, is the shorthand syntax:
var characters = [
{ 'name': 'barney', 'age': 36, 'blocked': false },
{ 'name': 'fred', 'age': 40, 'blocked': true }
];
// Using "_.filter" callback shorthand
_.filter(characters, { 'age': 36 });
// Using Underscore.js
_.filter(characters, function(character) { return character.age === 36; } );
// ? [{ 'name': 'barney', 'age': 36, 'blocked': false }]
(taken from Lodash documentation)
There's only one way I can think of to accomplish this task in O(1)... that is to 'cheat' and use a physical device (with linear or even parallel programming I think the limit is O(log(k)) where k represents the number of bytes of the number).
However you could very easily imagine a physical device that connects each bit an to output line with a 0/1 voltage. Then you could just electronically read of the total voltage on a 'summation' line in O(1). It would be quite easy to make this basic idea more elegant with some basic circuit elements to produce the output in whatever form you want (e.g. a binary encoded output), but the essential idea is the same and the electronic circuit would produce the correct output state in fixed time.
I imagine there are also possible quantum computing possibilities, but if we're allowed to do that, I would think a simple electronic circuit is the easier solution.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View titleView = getWindow().findViewById(android.R.id.title);
if (titleView != null) {
ViewParent parent = titleView.getParent();
if (parent != null && (parent instanceof View)) {
View parentView = (View)parent;
parentView.setBackgroundColor(Color.RED);
}
}
on above code you can try you can use title instead of titlebar this will affect on all activity in your application
You can convert it to char* if you don't need a modifiable string by using:
(char*) yourString.c_str();
This would be very useful when you want to publish a String variable via MQTT in arduino.
Abstract your initialization into a method, and call the method from mounted
and wherever else you want.
new Vue({
methods:{
init(){
//call API
//Setup game
}
},
mounted(){
this.init()
}
})
Then possibly have a button in your template to start over.
<button v-if="playerWon" @click="init">Play Again</button>
In this button, playerWon
represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init
.
If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:
<a id="sign_up" class="sign_new">Sign up</a>
And jQuery:
$(document).ready(function(){
$('#sign_up').click(function(){
alert('Sign new href executed.');
});
});
If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).
$(document).ready(function(){
$('#sign_up').click(function(event){
alert('Sign new href executed.');
event.stopPropagation();
});
});
In Java 8, the syntax for this simplifies greatly and can be used to accomplish this transformation succinctly.
Do note, you will need to change your field from a concrete implementation to the List
interface for this to work smoothly.
public class Wetland {
private String name;
private List<String> species;
public Wetland(String name, String[] speciesArr) {
this.name = name;
species = Arrays.stream(speciesArr)
.collect(Collectors.toList());
}
}
Check your imports. There could be two classes with the same name. Either from your code or from a library you are using. Personally that was the issue.
The nature of wanting to include the row where A == 5
and all rows upto but not including the row where A == 8
means we will end up using iloc
(loc
includes both ends of slice).
In order to get the index labels we use idxmax
. This will return the first position of the maximum value. I run this on a boolean series where A == 5
(then when A == 8
) which returns the index value of when A == 5
first happens (same thing for A == 8
).
Then I use searchsorted
to find the ordinal position of where the index label (that I found above) occurs. This is what I use in iloc
.
i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
df.iloc[i5:i8]
numpy
you can further enhance this by using the underlying numpy objects the analogous numpy functions. I wrapped it up into a handy function.
def find_between(df, col, v1, v2):
vals = df[col].values
mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
idx = df.index.values
i1, i2 = idx.searchsorted([mx1, mx2])
return df.iloc[i1:i2]
find_between(df, 'A', 5, 8)
The Bootstrap grid system has four classes:
xs (for phones)
sm (for tablets)
md (for desktops)
lg (for larger desktops)The classes above can be combined to create more dynamic and flexible layouts.
Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only need to specify xs.
OK, the answer is easy, but read on:
col-lg- stands for column large = 1200px
col-md- stands for column medium = 992px
col-xs- stands for column extra small = 768px
The pixel numbers are the breakpoints, so for example col-xs
is targeting the element when the window is smaller than 768px(likely mobile devices)...
I also created the image below to show how the grid system works, in this examples I use them with 3, like col-lg-6
to show you how the grid system work in the page, look at how lg
, md
and xs
are responsive to the window size:
.load()
& .unload()
have been deprecated$(window).load();
Will execute after the page along with all its contents are done loading. This means that all images, CSS (and content defined by CSS like custom fonts and images), scripts, etc. are all loaded. This happens event fires when your browser's "Stop" -icon becomes gray, so to speak. This is very useful to detect when the document along with all its contents are loaded.
$(document).ready();
This on the other hand will fire as soon as the web browser is capable of running your JavaScript, which happens after the parser is done with the DOM. This is useful if you want to execute JavaScript as soon as possible.
$(window).unload();
This event will be fired when you are navigating off the page. That could be Refresh/F5, pressing the previous page button, navigating to another website or closing the entire tab/window.
To sum up, ready() will be fired before load(), and unload() will be the last to be fired.
Modern answer: Use LocalDate
from java.time
, the modern Java date and time API, and its toString
method:
LocalDate date = LocalDate.of(2012, Month.DECEMBER, 1); // get from somewhere
String formattedDate = date.toString();
System.out.println(formattedDate);
This prints
2012-12-01
A date (whether we’re talking java.util.Date
or java.time.LocalDate
) doesn’t have a format in it. All it’s got is a toString
method that produces some format, and you cannot change the toString
method. Fortunately, LocalDate.toString
produces exactly the format you asked for.
The Date
class is long outdated, and the SimpleDateFormat
class that you tried to use, is notoriously troublesome. I recommend you forget about those classes and use java.time
instead. The modern API is so much nicer to work with.
Except: it happens that you get a Date
from a legacy API that you cannot change or don’t want to change just now. The best thing you can do with it is convert it to java.time.Instant
and do any further operations from there:
Date oldfashoinedDate = // get from somewhere
LocalDate date = oldfashoinedDate.toInstant()
.atZone(ZoneId.of("Asia/Beirut"))
.toLocalDate();
Please substitute your desired time zone if it didn’t happen to be Asia/Beirut. Then proceed as above.
Link: Oracle tutorial: Date Time, explaining how to use java.time
.
copy tablename from 'filepath\filename' DELIMITERS '=' ENCODING 'WIN1252';
you can try this to handle UTF8 encoding.
Download & Copy Your .jar
file in libs
folder then adding these line to build.gradle:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.code.gson:gson:2.3.1'
}
Do not forget to click "Sync now"
If you don't want to install MySQL workbench, and are looking for an online tool, this might help: http://ondras.zarovi.cz/sql/demo/
I use it quite often to create simple DB schemas for various apps I build.
You can also perform Implicit Type Conversions with template literals. Example:
let fruits = ["mango","orange","pineapple","papaya"];
console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya
You need to pass an array of element to jsx
. The problem is that forEach
does not return anything (i.e it returns undefined
). So it's better to use map
because map
returns an array:
class QuestionSet extends Component {
render(){
<div className="container">
<h1>{this.props.question.text}</h1>
{this.props.question.answers.map((answer, i) => {
console.log("Entered");
// Return the element. Also pass key
return (<Answer key={answer} answer={answer} />)
})}
}
export default QuestionSet;
No one mentioned that case classes have val
constructor parameters yet this is also the default for regular classes (which I think is an inconsistency in the design of Scala). Dario implied such where he noted they are "immutable".
Note you can override the default by prepending the each constructor argument with var
for case classes. However, making case classes mutable causes their equals
and hashCode
methods to be time variant.[1]
sepp2k already mentioned that case classes automatically generate equals
and hashCode
methods.
Also no one mentioned that case classes automatically create a companion object
with the same name as the class, which contains apply
and unapply
methods. The apply
method enables constructing instances without prepending with new
. The unapply
extractor method enables the pattern matching that others mentioned.
Also the compiler optimizes the speed of match
-case
pattern matching for case classes[2].
Just in normal mode press:
For the first letter, with error checking:
public string CapitalizeFirstLetter(string s)
{
if (String.IsNullOrEmpty(s))
return s;
if (s.Length == 1)
return s.ToUpper();
return s.Remove(1).ToUpper() + s.Substring(1);
}
And here's the same as a handy extension
public static string CapitalizeFirstLetter(this string s)
{
if (String.IsNullOrEmpty(s)) return s;
if (s.Length == 1) return s.ToUpper();
return s.Remove(1).ToUpper() + s.Substring(1);
}
As @Lighthart as shown, yes it's possible, although it adds significant fat to the controller and isn't DRY.
You should really define your own query in the entity repository, it's simple and best practice.
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function findAll()
{
return $this->findBy(array(), array('username' => 'ASC'));
}
}
Then you must tell your entity to look for queries in the repository:
/**
* @ORM\Table(name="User")
* @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\Repository\UserRepository")
*/
class User
{
...
}
Finally, in your controller:
$this->getDoctrine()->getRepository('AcmeBundle:User')->findAll();
Why don't you simply use the size()
method on your Collection
to get the number of elements?
Iterator
is just meant to iterate,nothing else.
Search till the seconds for the timestamp column in postgress
select * from "TableName" e
where timestamp >= '2020-08-08T13:00:00' and timestamp < '2020-08-08T17:00:00';
I was having issues because I updated my AdHoc provisioning profile with some new devices for use on TestFlight. Assumedly this is happening because Xcode has an old reference to your provisioning profile in either the codesigning build settings for the project or the targets. The way I fixed mine was to:
genrsa
has been replaced by genpkey
& when run manually in a terminal it will prompt for a password:
openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096
However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell
script:
get_passwd() {
local passwd=
echo -ne "Enter passwd for private key: ? "; read -s passwd
openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}
.Cells(.Rows.Count,"A").End(xlUp).row
I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:
.Cells(Rows.Count,"A").End(xlUp).row
Before the Cells, you can write your worksheet name, for example:
Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row
The worksheet name is not necessary when you operate on the same worksheet.
A recursive algorithm that parses through an XmlDocument
Here is an example - Recursively reading an xml document and using regex to get contents
Here is another recursive example - http://www.java2s.com/Tutorial/CSharp/0540__XML/LoopThroughXmlDocumentRecursively.html
Transmission Delay : Amount of time required to pump all bits/packets into the electric wire/optic fibre.
Propagation delay : It's the amount of time needed for a packet to reach the destination.
If propagation delay is very high than transmission delay the chance of losing the packet is high.
$('myObject').css({'background-image': 'url(imgUrl)',});
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
Outside of your loop create an int:
int numberOfItemIds = 0;
for (int i = 0; i < key.length; i++) {
Then in the loop, increment it:
itemId = p.getItemId();
numberOfItemIds++;
Check with your bean class. Column data type and bean datatype must be same.
You'll need to switch to the database you want the user on (not the admin db) ...
use mydatabase
See this post for more help ... https://web.archive.org/web/20140316031938/http://learnmongo.com/posts/quick-tip-mongodb-users/
Some different and clean way to achieve this is by using HttpClient like this:
public async Task<HttpResponseMessage> PostResult(string url, ResultObject resultObject)
{
using (var client = new HttpClient())
{
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.PostAsJsonAsync(url, resultObject);
}
catch (Exception ex)
{
throw ex
}
return response;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Data.SqlClient;
public partial class ExcuteScript : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sqlConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ccwebgrity;Data Source=SURAJIT\SQLEXPRESS";
string script = File.ReadAllText(@"E:\Project Docs\MX462-PD\MX756_ModMappings1.sql");
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
Here is shortest way of doing it.
$userRecord = Model::where(['email'=>$email, 'password'=>$password])->first();
Do the following steps
1. Make sure that the hosting / your pc mod_rewrite module is active. if not active then try to activate in a way, open the httpd.conf file. You can check this in the phpinfo.php to find out.
change this setting :
#LoadModule rewrite_module modules/mod_rewrite.so
to be and restart wamp
LoadModule rewrite_module modules/mod_rewrite.so
2. Then go to .htaccess file, and try to modify to be:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ index.php/$1 [L,QSA]
if above does not work try with this:
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
3. Move .htaccess file to root directory, where is index.php there.
www OR root folder
- index.php
- .htaccess
You have to specify any one of the above phase to resolve the above error. In most of the situations, this would have occurred due to running the build from the eclipse environment.
instead of mvn clean package or mvn package you can try only package its work fine for me
Pawel and Jobayer has already mentioned about how to install popper.js through npm.
If you are using front-end package manager like bower. use the following command
bower install popper.js --save
You can do it now with HTML5
In essence you use the multiple attribute on the file input.
<input type='file' multiple>
If you need any type of quoting (single, double, and triple for both) you can "combine"(0) the strings:
>>> raw_string_with_quotes = r'double"' r"single'" r'''double triple""" ''' r"""single triple''' """
>>> print raw_string_with_quotes
double"single'double triple""" single triple'''
You may also "combine"(0) raw strings with non-raw strings:
>>> r'raw_string\n' 'non-raw string\n'
'raw_string\\nnon-raw string\n'
(0): In fact, the Python parser joins the strings, and it does not create multiple strings. If you add the "+" operator, then multiple strings are created and combined.
Try this:
if(Math.floor(id) == id && $.isNumeric(id))
alert('yes its an int!');
$.isNumeric(id)
checks whether it's numeric or not
Math.floor(id) == id
will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.
Replacing the border-color with outline-color should work.