It's very simple.
Create a new empty repository in GitHub (without readme or license, you can add them later) and the following screen will show.
In the import code option, paste your Bitbucket repo's URL and voilà!!
From Android 19, you can register an app life cycle callback in your Application class's onCreate() like this:
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new AppLifecycleCallback());
}
The AppLifecycleCallback looks like this:
class AppLifecycleCallback implements Application.ActivityLifecycleCallbacks {
private int numStarted = 0;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
if (numStarted == 0) {
//app went to foreground
}
numStarted++;
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
numStarted--;
if (numStarted == 0) {
// app went to background
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
There's a Firefox extension that adds the CORS headers to any HTTP response working on the latest Firefox (build 36.0.1) released March 5, 2015. I tested it and it's working on both Windows 7 and Mavericks. I'll guide you throught the steps to get it working.
1) Getting the extension
You can either download the xpi from here (author builds) or from here (mirror, may not be updated).
Or download the files from GitHub. Now it's also on Firefox Marketplace: Download here. In this case, the addon is installed after you click install and you can skip to step 4.
If you downloaded the xpi you can jump to step 3. If you downloaded the zip from GitHub, go to step 2.
2) Building the xpi
You need to extract the zip, get inside the "cors-everywhere-firefox-addon-master" folder, select all the items and zip them. Then, rename the created zip as *.xpi
Note: If you are using the OS X gui, it may create some hidden files, so you 'd be better using the command line.
3) Installing the xpi
You can just drag and drop the xpi to firefox, or go to: "about:addons", click on the cog on the top right corner and select "install add on from file", then select you .xpi file. Now, restart firefox.
4) Getting it to work
Now, the extension won't be working by default. You need to drag the extension icon to the extension bar, but don't worry. There are pictures!
5) Testing if it's working
jQuery
$.get( "http://example.com/", function( data ) {
console.log (data);
});
JavaScript
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","http://example.com/");
xmlhttp.send();
6) Final considerations
Note that https to http is not allowed.
There may be a way around it, but it's behind the scope of the question.
You will find I have added the session_start() at the very top of the page. I have also removed the session_start() call later in the page. This page should work fine.
<?php
session_start();
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Welcome</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').hover(
function () {
//show its submenu
$('ul', this).slideDown(100);
},
function () {
//hide its submenu
$('ul', this).slideUp(100);
}
);
});
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="header"> </td>
</tr>
<tr>
<td class="menu"><table align="center" cellpadding="0" cellspacing="0" width="80%">
<tr>
<td>
<ul id="nav">
<li><a href="#">Catalog</a>
<ul><li><a href="#">Products</a></li>
<li><a href="#">Bulk Upload</a></li>
</ul>
<div class="clear"></div>
</li>
<li><a href="#">Purchase </a>
</li>
<li><a href="#">Customer Service</a>
<ul>
<li><a href="#">Contact Us</a></li>
<li><a href="#">CS Panel</a></li>
</ul>
<div class="clear"></div>
</li>
<li><a href="#">All Reports</a></li>
<li><a href="#">Configuration</a>
<ul> <li><a href="#">Look and Feel </a></li>
<li><a href="#">Business Details</a></li>
<li><a href="#">CS Details</a></li>
<li><a href="#">Emaqil Template</a></li>
<li><a href="#">Domain and Analytics</a></li>
<li><a href="#">Courier</a></li>
</ul>
<div class="clear"></div>
</li>
<li><a href="#">Accounts</a>
<ul><li><a href="#">Ledgers</a></li>
<li><a href="#">Account Details</a></li>
</ul>
<div class="clear"></div></li>
</ul></td></tr></table></td>
</tr>
<tr>
<td valign="top"><table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="22%" height="327" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td> </td>
</tr>
<tr>
<td height="45"><strong>-> Products</strong></td>
</tr>
<tr>
<td height="61"><strong>-> Categories</strong></td>
</tr>
<tr>
<td height="48"><strong>-> Sub Categories</strong></td>
</tr>
</table></td>
<td width="78%" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
<tr>
<td>
<table width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="26%"> </td>
<td width="74%"><h2>Manage Categories</h2></td>
</tr>
</table></td>
</tr>
<tr>
<td height="30">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<table width="49%" align="center" cellpadding="0" cellspacing="0">
<tr><td>
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p>
<label class="style4">Category Name</label>
<input type="text" name="categoryname" /><br /><br />
<label class="style4">Category Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<br />
<br />
<input type="submit" id="submit" value="UPLOAD" />
</p>
</form>
<?php
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/category";
$cname = $_POST['categoryname'];
$image = $_FILES['image'];
$cname = mysql_real_escape_string($cname);
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $cname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: managecategories.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: managecategories.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: managecategories.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: mangaecategories.php");
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: mangagecategories.php");
exit;
}
?>
You just need to find the right multiplier, which can be easily calculated from the hist
object.
myhist <- hist(mtcars$mpg)
multiplier <- myhist$counts / myhist$density
mydensity <- density(mtcars$mpg)
mydensity$y <- mydensity$y * multiplier[1]
plot(myhist)
lines(mydensity)
A more complete version, with a normal density and lines at each standard deviation away from the mean (including the mean):
myhist <- hist(mtcars$mpg)
multiplier <- myhist$counts / myhist$density
mydensity <- density(mtcars$mpg)
mydensity$y <- mydensity$y * multiplier[1]
plot(myhist)
lines(mydensity)
myx <- seq(min(mtcars$mpg), max(mtcars$mpg), length.out= 100)
mymean <- mean(mtcars$mpg)
mysd <- sd(mtcars$mpg)
normal <- dnorm(x = myx, mean = mymean, sd = mysd)
lines(myx, normal * multiplier[1], col = "blue", lwd = 2)
sd_x <- seq(mymean - 3 * mysd, mymean + 3 * mysd, by = mysd)
sd_y <- dnorm(x = sd_x, mean = mymean, sd = mysd) * multiplier[1]
segments(x0 = sd_x, y0= 0, x1 = sd_x, y1 = sd_y, col = "firebrick4", lwd = 2)
If you want to be more targeted to the actual child component than you should do the follow. This way, if other child components share the same class name, they won't be affected.
Plunker: https://plnkr.co/edit/ooBRp3ROk6fbWPuToytO?p=preview
For example:
import {Component, NgModule } from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>I'm the host parent</h2>
<child-component class="target1"></child-component><br/>
<child-component class="target2"></child-component><br/>
<child-component class="target3"></child-component><br/>
<child-component class="target4"></child-component><br/>
<child-component></child-component><br/>
</div>
`,
styles: [`
/deep/ child-component.target1 .child-box {
color: red !important;
border: 10px solid red !important;
}
/deep/ child-component.target2 .child-box {
color: purple !important;
border: 10px solid purple !important;
}
/deep/ child-component.target3 .child-box {
color: orange !important;
border: 10px solid orange !important;
}
/* this won't work because the target component is spelled incorrectly */
/deep/ xxxxchild-component.target4 .child-box {
color: orange !important;
border: 10px solid orange !important;
}
/* this will affect any component that has a class name called .child-box */
/deep/ .child-box {
color: blue !important;
border: 10px solid blue !important;
}
`]
})
export class App {
}
@Component({
selector: 'child-component',
template: `
<div class="child-box">
Child: This is some text in a box
</div>
`,
styles: [`
.child-box {
color: green;
border: 1px solid green;
}
`]
})
export class ChildComponent {
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, ChildComponent ],
bootstrap: [ App ]
})
export class AppModule {}
Hope this helps!
codematrix
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.
If you have the proxies set up correctly, and still cannot reach the internet, it could be the DNS resolution. Check /etc/resolve.conf
on the host Ubuntu VM. If it contains nameserver 127.0.1.1
, that is wrong.
Run these commands on the host Ubuntu VM to fix it:
sudo vi /etc/NetworkManager/NetworkManager.conf
# Comment out the line `dns=dnsmasq` with a `#`
# restart the network manager service
sudo systemctl restart network-manager
cat /etc/resolv.conf
Now /etc/resolv.conf
should have a valid value for nameserver, which will be copied by the docker containers.
$('#id-you-want-to-change').attr('id', 'id-you-want-it-to-be');
XHTML solution:
<input type="radio" name="imgsel" value="" checked="checked" />
Please note, that the actual value of checked
attribute does not actually matter; it's just a convention to assign "checked"
. Most importantly, strings like "true"
or "false"
don't have any special meaning.
If you don't aim for XHTML conformance, you can simplify the code to:
<input type="radio" name="imgsel" value="" checked>
Use the a
mode. It stands for append
.
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
fclose($myfile);
After uninstalling a few apps I'm able to install the new one...
I think OS calculates the total memory required to run all apps. If it doesn't fit then it says "in sufficient memory".
You don't really have to call the __init__
methods of the base class(es), but you usually want to do it because the base classes will do some important initializations there that are needed for rest of the classes methods to work.
For other methods it depends on your intentions. If you just want to add something to the base classes behavior you will want to call the base classes method additionally to your own code. If you want to fundamentally change the behavior, you might not call the base class' method and implement all the functionality directly in the derived class.
On the iPhone there is no concept of quitting an app. The only action that should cause an app to quit is touching the Home button on the phone, and that's not something developers have access to.
According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.
This probably isn't relevant any more to this thread, but hopefully helpful to somebody. I've had 500 errors for the past hour as I had a controller return an array not supported by the php version ran on my (crappy) server. Seems trivial but had the hallmarks of a codeigniter error.
I had to use:
class emck_model extends CI_Model {
public function getTiles(){
return array(...);
}
}
Instead of
class emck_model extends CI_Model {
public function getTiles(){
return [...];
}
}
Cheers
require_relative
is a convenient subset of require
require_relative('path')
equals:
require(File.expand_path('path', File.dirname(__FILE__)))
if __FILE__
is defined, or it raises LoadError
otherwise.
This implies that:
require_relative 'a'
and require_relative './a'
require relative to the current file (__FILE__
).
This is what you want to use when requiring inside your library, since you don't want the result to depend on the current directory of the caller.
eval('require_relative("a.rb")')
raises LoadError
because __FILE__
is not defined inside eval
.
This is why you can't use require_relative
in RSpec tests, which get eval
ed.
The following operations are only possible with require
:
require './a.rb'
requires relative to the current directory
require 'a.rb'
uses the search path ($LOAD_PATH
) to require. It does not find files relative to current directory or path.
This is not possible with require_relative
because the docs say that path search only happens when "the filename does not resolve to an absolute path" (i.e. starts with /
or ./
or ../
), which is always the case for File.expand_path
.
The following operation is possible with both, but you will want to use require
as it is shorter and more efficient:
require '/a.rb'
and require_relative '/a.rb'
both require the absolute path.Reading the source
When the docs are not clear, I recommend that you take a look at the sources (toggle source in the docs). In some cases, it helps to understand what is going on.
require:
VALUE rb_f_require(VALUE obj, VALUE fname) {
return rb_require_safe(fname, rb_safe_level());
}
require_relative:
VALUE rb_f_require_relative(VALUE obj, VALUE fname) {
VALUE base = rb_current_realfilepath();
if (NIL_P(base)) {
rb_loaderror("cannot infer basepath");
}
base = rb_file_dirname(base);
return rb_require_safe(rb_file_absolute_path(fname, base), rb_safe_level());
}
This allows us to conclude that
require_relative('path')
is the same as:
require(File.expand_path('path', File.dirname(__FILE__)))
because:
rb_file_absolute_path =~ File.expand_path
rb_file_dirname1 =~ File.dirname
rb_current_realfilepath =~ __FILE__
Try this:
result = []
acc = 0
for i in time_interval:
acc += i
result.append(acc)
Directly from the command line:
for /L %n in (1,1,100) do @echo %n
Using a batch file:
@echo off
for /L %%n in (1,1,100) do echo %%n
Displays:
1
2
3
...
100
DATABASE
MongoDB states a nice example:
To select a database to use, in the mongo shell, issue the use <db> statement, as in the following example:
use myDB
use myNewDB
Content from: https://docs.mongodb.com/manual/core/databases-and-collections/#databases
COLLECTIONS
Lowercase names: avoids case sensitivity issues, MongoDB collection names are case sensitive.
Plural: more obvious to label a collection of something as the plural, e.g. "files" rather than "file"
>No word separators: Avoids issues where different people (incorrectly) separate words (username <-> user_name, first_name <->
firstname). This one is up for debate according to a few people
around here but provided the argument is isolated to collection names I don't think it should be ;) If you find yourself improving the
readability of your collection name by adding underscores or
camelCasing your collection name is probably too long or should use
periods as appropriate which is the standard for collection
categorization.Dot notation for higher detail collections: Gives some indication to how collections are related. For example you can be reasonably sure you could delete "users.pagevisits" if you deleted "users", provided the people that designed the schema did a good job.
Content from: http://www.tutespace.com/2016/03/schema-design-and-naming-conventions-in.html
For collections I'm following these suggested patterns until I find official MongoDB documentation.
You may get find yourself in the situation where you have users trying to enter phone numbers with all sorts of separators between area code and the main number block (e.g., spaces, dashes, periods, ect...) So you'll want to strip the input of all characters that are not numbers so you can sterilize the input you are working with. The easiest way to do this is with a RegEx expression.
string formattedPhoneNumber = new System.Text.RegularExpressions.Regex(@"\D")
.Replace(originalPhoneNumber, string.Empty);
Then the answer you have listed should work in most cases.
To answer what you have about your extension issue, you can strip anything that is longer than the expected length of ten (for a regular phone number) and add that to the end using
formattedPhoneNumber = Convert.ToInt64(formattedPhoneNumber)
.ToString("###-###-#### " + new String('#', (value.Length - 10)));
You will want to do an 'if' check to determine if the length of your input is greater than 10 before doing this, if not, just use:
formattedPhoneNumber = Convert.ToInt64(value).ToString("###-###-####");
Your code (which looks ok) doesn't return a pointer to an array. It returns a pointer to the first element of an array.
In fact that's usually what you want to do. Most manipulation of arrays are done via pointers to individual elements, not via pointers to the array as a whole.
You can define a pointer to an array, for example this:
double (*p)[42];
defines p
as a pointer to a 42-element array of double
s. A big problem with that is that you have to specify the number of elements in the array as part of the type -- and that number has to be a compile-time constant. Most programs that deal with arrays need to deal with arrays of varying sizes; a given array's size won't vary after it's been created, but its initial size isn't necessarily known at compile time, and different array objects can have different sizes.
A pointer to the first element of an array lets you use either pointer arithmetic or the indexing operator []
to traverse the elements of the array. But the pointer doesn't tell you how many elements the array has; you generally have to keep track of that yourself.
If a function needs to create an array and return a pointer to its first element, you have to manage the storage for that array yourself, in one of several ways. You can have the caller pass in a pointer to (the first element of) an array object, probably along with another argument specifying its size -- which means the caller has to know how big the array needs to be. Or the function can return a pointer to (the first element of) a static array defined inside the function -- which means the size of the array is fixed, and the same array will be clobbered by a second call to the function. Or the function can allocate the array on the heap -- which makes the caller responsible for deallocating it later.
Everything I've written so far is common to C and C++, and in fact it's much more in the style of C than C++. Section 6 of the comp.lang.c FAQ discusses the behavior of arrays and pointers in C.
But if you're writing in C++, you're probably better off using C++ idioms. For example, the C++ standard library provides a number of headers defining container classes such as <vector>
and <array>
, which will take care of most of this stuff for you. Unless you have a particular reason to use raw arrays and pointers, you're probably better off just using C++ containers instead.
EDIT : I think you edited your question as I was typing this answer. The new code at the end of your question is, as you observer, no good; it returns a pointer to an object that ceases to exist as soon as the function returns. I think I've covered the alternatives.
Actually there is. There is a static method valueOf in the java.sql.Date
object which does exactly that. So we have
java.util.Date date = java.sql.Date.valueOf(localDate);
and that's it. No explicit setting of time zones because the local time zone is taken implicitly.
From docs:
The provided LocalDate is interpreted as the local date in the local time zone.
The java.sql.Date
subclasses java.util.Date
so the result is a java.util.Date
also.
And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:
LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();
I know this is an "older" post. This question and the provided answers helped me get ideas for my own problem. I think this solution addresses the OP question (intersecting borders with 4 and 2 columns depending on display)
Fiddle: https://jsfiddle.net/tqmfpwhv/1/
css based on OP information, media query at end is for med & lg view.
.vr-all {
padding:0px;
border-right:1px solid #CC0000;
}
.vr-xs {
padding:0px;
}
.vr-md {
padding:0px;
}
.hrspacing { padding:0px; }
.hrcolor {
border-color: #CC0000;
border-style: solid;
border-bottom: 1px;
margin:0px;
padding:0px;
}
/* for medium and up */
@media(min-width:992px){
.vr-xs {
border-right:1px solid #CC0000;
}
}
html adjustments to OP provided code. Red border and Img links for example.
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="one">
<h5>Rich Media Ad Production</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" />
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="two">
<h5>Web Design & Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="three">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="four">
<h5>Creative Design</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for for all viewports -->
<div class="col-xs-12 hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="five">
<h5>Web Analytics</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="six">
<h5>Search Engine Marketing</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="seven">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="eight">
<h5>Quality Assurance</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
</div>
</div>
You can't use AJAX to fetch files from the user machine. This is absolutely the wrong way to go about it.
Use the FileReader API:
<input type="file" id="file input">
js:
console.log(document.getElementById("file input").files); // list of File objects
var file = document.getElementById("file input").files[0];
var reader = new FileReader();
content = reader.readAsText(file);
console.log(content);
Then parse content
as CSV. Keep in mind that your parser currently does not deal with escaped values in CSV like: value1,value2,"value 3","value ""4"""
it is very simple....
[in make file]
==== 1 ===================
OBJS = ....\
version.o <<== add to your obj lists
==== 2 ===================
DATE = $(shell date +'char szVersionStr[20] = "%Y-%m-%d %H:%M:%S";') <<== add
all:version $(ProgramID) <<== version add at first
version: <<== add
echo '$(DATE)' > version.c <== add ( create version.c file)
[in program]
=====3 =============
extern char szVersionStr[20];
[ using ]
=== 4 ====
printf( "Version: %s\n", szVersionStr );
If you already have the full local copy, you can remove unwanted sub folders by using --set-depth
command.
svn update --set-depth=exclude www
See: http://blogs.collab.net/subversion/sparse-directories-now-with-exclusion
The set-depth
command support multipile paths.
Updating the root local copy will not change the depth of the modified folder.
To restore the folder to being recusively checkingout, you could use --set-depth
again with infinity param.
svn update --set-depth=infinity www
Wrap each ajax call in a named function and just add them to the success callbacks of the previous call:
function callA() {
$.ajax({
...
success: function() {
//do stuff
callB();
}
});
}
function callB() {
$.ajax({
...
success: function() {
//do stuff
callC();
}
});
}
function callC() {
$.ajax({
...
});
}
callA();
As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:
dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))
So that the x
variable matches the corresponding variable in df
, and so on. Then you simply include it using geom_text
:
ggplot(df) + geom_bar(aes(x,fill=x)) +
geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
axis.title.x=theme_blank(),legend.title=theme_blank(),
axis.title.y=theme_blank())
This example will plot just the percentages, but you can paste
together the counts as well via something like this:
dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")
Note that in the current version of ggplot2, opts
is deprecated, so we would use theme
and element_blank
now.
Still pretty bewildering. It seems some combination of the above suggestions worked in Eclipse 3.7.2.
First, I had to move to a network that dl-ssl.google.com hasn't blocked (this is an ongoing problem with the Google server) (Easy with a laptop, less so with my tower.)
The Eclipse folks should look at this problem. The user sees an error, something about a missing package "org.eclipse.wst.sse.core', say. There are 50 or so plugin repositories listed. which of these is the one that has this package??? None has a name containing a 'wst' or 'sse'.
This is very poor. There needs to be a way for the user to associate the error message with a repository solution.
Anyway: after some hunt-and-peck I ended up selecting (and reloading each repository, and with Contact all update sites during install to find required software checked)
One of these provided the packages needed for the Android plugin . Best guess: Helios.
Building on some of the answers here, but using some simple math for a smooth transition using a sine curve:
scrollTo(element, from, to, duration, currentTime) {
if (from <= 0) { from = 0;}
if (to <= 0) { to = 0;}
if (currentTime>=duration) return;
let delta = to-from;
let progress = currentTime / duration * Math.PI / 2;
let position = delta * (Math.sin(progress));
setTimeout(() => {
element.scrollTop = from + position;
this.scrollTo(element, from, to, duration, currentTime + 10);
}, 10);
}
Usage:
// Smoothly scroll from current position to new position in 1/2 second.
scrollTo(element, element.scrollTop, element.scrollTop + 400, 500, 0);
PS. take note of ES6 style
bool is a fundamental datatype in C++. Converting true
to an integer type will yield 1, and converting false
will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like
enum bool {
false, true
};
So did the Windows API. Starting with C99, we have _Bool
as a basic data type. Including stdbool.h
will typedef #define
that to bool
and provide the constants true
and false
. They didn't make bool a basic data-type (and thus a keyword) because of compatibility issues with existing code.
Both your queries are correct and should give you the right answer.
I would suggest the following query to troubleshoot your problem.
SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc
That is add count(*) field. This will give you idea how many rows were eliminated using the group command.
As detailed in this answer, mayur & user3869623's answer's are now relating to a deprecated router. You can now pass multiple parameters as follows:
To call router:
this.router.navigate(['/myUrlPath', "someId", "another ID"]);
In routes.ts:
{ path: 'myUrlpath/:id1/:id2', component: componentToGoTo},
this code worked for me..
//Disable bluetooth
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
For this to work, you must have the following permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
You can use a simple, low-cost USB port reader like this test connects directly to your Android device; it has a utility app and an SDK you can use for app development: https://www.atlasrfidstore.com/sls-rfid-smartmicro-android-micro-usb-reader/
You may want to use the "xcode-select" command in terminal to switch between the different Xcode version in the installed folders.
Here is a slightly different answer. Your column names & lengths may all match, but perhaps you are specifying the columns in the wrong order in your SELECT statement. Say tableX and tableY have columns with the same name, but in different order
Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.
Sometimes a prototype in some place add an extra element.
I have a similar issue running Linux systems. After the system was booted, a container with a restart policy of "unless-stopped" would not restart automatically unless I typed a command that used docker in some way such as "docker ps". I was surprised as I expected that command to just report some status information. Next I tried the command "systemctl status docker". On a system where no docker commands had been run, this command reported the following:
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)
Active: inactive (dead) TriggeredBy: ? docker.socket
Docs: https://docs.docker.com
On a system where "docker ps" had been run with no other Docker commands, I got the following:
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)
Active: active (running) since Sun 2020-11-22 08:33:23 PST; 1h 25min ago
TriggeredBy: ? docker.socket
Docs: https://docs.docker.com
Main PID: 3135 (dockerd)
Tasks: 13
Memory: 116.9M
CGroup: /system.slice/docker.service
+-3135 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
... [various messages not shown ]
The most likely explanation is that Docker waits for some docker command before fully initializing and starting containers. You could presumably run "docker ps" in a systemd unit file at a point after all the services your containers need have been initialized. I've tested this by putting a file named docker-onboot.service in the directory /lib/systemd/system with the following contents:
[Unit]
# This service is provided to force Docker containers
# that should automatically restart to restart when the system
# is booted. While the Docker daemon will start automatically,
# it will not be fully initialized until some Docker command
# is actually run. This unit merely runs "docker ps": any
# Docker command will result in the Docker daemon completing
# its initialization, at which point all containers that can be
# automatically restarted after booting will be restarted.
#
Description=Docker-Container Startup on Boot
Requires=docker.socket
After=docker.socket network-online.target containerd.service
[Service]
Type=oneshot
ExecStart=/usr/bin/docker ps
[Install]
WantedBy=multi-user.target
So far (one test, with this service enabled), the container started when the computer was booted. I did not try a dependency on docker.service because docker.service won't start until a docker command is run. The next test will be with the docker-onboot disabled (to see if the WantedBy dependency will automatically start it).
Also, eclipse offers the possibility to sort class members for you, if you for some reason mixed them up:
Open your class file, the go to "Source" in the main menu and select "Sort Members".
taken from here: Sorting methods in Eclipse
Incredibly old question, but bearing in mind that the OP said he does not want to use Do While
and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop
:
This never runs anything if the status is already at "Fail"...
While (i < 20 And Not bShouldStop)
If (Status = "Fail") Then
bShouldStop = True
Else
i = i + 1
'
' Do Something
'
End If
Wend
Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.
While (i < 20 And Not bShouldStop)
i = i + 1
'
' Do Something
'
If (Status = "Fail") Then
bShouldStop = True
End If
Wend
Ultimately, if the variable Status
is being modified inside the While
(and assuming you don't need i
outside the while, it makes no difference really, but just wanted to present multiple options...
List is an interface. It doesn't have methods. When you call a method on a List reference, it in fact calls the method of ArrayList in both cases.
And for the future you can change List obj = new ArrayList<>
to List obj = new LinkList<>
or other types which implement List interface.
You can try a box-shadow inset
something like this: box-shadow:inset 0px -5px 0px 0px #fff
adds a white 5px border to the bottom of the element without increasing the size
Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)
for example:
Person.staticMethod(); //accessing static method.
for non-static method you must instantiate the class.
Person person1 = new Person(); //instantiating
person1.nonStaticMethod(); //accessing non-static method.
Many people on this thread and on google explain very well that attr_accessible
specifies a whitelist of attributes that are allowed to be updated in bulk (all the attributes of an object model together at the same time)
This is mainly (and only) to protect your application from "Mass assignment" pirate exploit.
This is explained here on the official Rails doc : Mass Assignment
attr_accessor
is a ruby code to (quickly) create setter and getter methods in a Class. That's all.
Now, what is missing as an explanation is that when you create somehow a link between a (Rails) model with a database table, you NEVER, NEVER, NEVER need attr_accessor
in your model to create setters and getters in order to be able to modify your table's records.
This is because your model inherits all methods from the ActiveRecord::Base
Class, which already defines basic CRUD accessors (Create, Read, Update, Delete) for you.
This is explained on the offical doc here Rails Model and here Overwriting default accessor (scroll down to the chapter "Overwrite default accessor")
Say for instance that: we have a database table called "users" that contains three columns "firstname", "lastname" and "role" :
SQL instructions :
CREATE TABLE users (
firstname string,
lastname string
role string
);
I assumed that you set the option config.active_record.whitelist_attributes = true
in your config/environment/production.rb to protect your application from Mass assignment exploit. This is explained here : Mass Assignment
Your Rails model will perfectly work with the Model here below :
class User < ActiveRecord::Base
end
However you will need to update each attribute of user separately in your controller for your form's View to work :
def update
@user = User.find_by_id(params[:id])
@user.firstname = params[:user][:firstname]
@user.lastname = params[:user][:lastname]
if @user.save
# Use of I18 internationalization t method for the flash message
flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
end
respond_with(@user)
end
Now to ease your life, you don't want to make a complicated controller for your User model.
So you will use the attr_accessible
special method in your Class model :
class User < ActiveRecord::Base
attr_accessible :firstname, :lastname
end
So you can use the "highway" (mass assignment) to update :
def update
@user = User.find_by_id(params[:id])
if @user.update_attributes(params[:user])
# Use of I18 internationlization t method for the flash message
flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
end
respond_with(@user)
end
You didn't add the "role" attributes to the attr_accessible
list because you don't let your users set their role by themselves (like admin). You do this yourself on another special admin View.
Though your user view doesn't show a "role" field, a pirate could easily send a HTTP POST request that include "role" in the params hash. The missing "role" attribute on the attr_accessible
is to protect your application from that.
You can still modify your user.role attribute on its own like below, but not with all attributes together.
@user.role = DEFAULT_ROLE
Why the hell would you use the attr_accessor
?
Well, this would be in the case that your user-form shows a field that doesn't exist in your users table as a column.
For instance, say your user view shows a "please-tell-the-admin-that-I'm-in-here" field. You don't want to store this info in your table. You just want that Rails send you an e-mail warning you that one "crazy" ;-) user has subscribed.
To be able to make use of this info you need to store it temporarily somewhere.
What more easy than recover it in a user.peekaboo
attribute ?
So you add this field to your model :
class User < ActiveRecord::Base
attr_accessible :firstname, :lastname
attr_accessor :peekaboo
end
So you will be able to make an educated use of the user.peekaboo
attribute somewhere in your controller to send an e-mail or do whatever you want.
ActiveRecord will not save the "peekaboo" attribute in your table when you do a user.save
because she don't see any column matching this name in her model.
Making changes as below and redeploying on server content type as
Response.ContentType = "application/octet-stream";
This worked for me.
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
Generally, Threads are called light weight process. If we divide memory into three sections then it will be: Code, data and Stack. Every process has its own code, data and stack sections and due to this context switch time is a little high. To reduce context switching time, people have come up with concept of thread, which shares Data and code segment with other thread/process and it has its own STACK segment.
The answer of JasonW is fine. But since apache httpd 2.4.6 there is a alternative: mod_remoteip
All what you must do is:
Enable the module:
LoadModule remoteip_module modules/mod_remoteip.so
Add the following to your apache httpd config. Note that you must add this line not into the configuration of the proxy server. You must add this to the configuration of the proxy target httpd server (the server behind the proxy):
RemoteIPHeader X-Forwarded-For
See at http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html for more informations and more options.
Just to add a very simple solution, that was good enough for me, and I think addresses the OP's issue. I used the solution in this answer except with a regular Background
value instead of an image.
<Style x:Key="SomeButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
No re-templating beyond forcing the Background
to always be the Transparent
background from the templated button - mouseover no longer affects the background once this is done. Obviously replace Transparent
with any preferred value.
For Java 8 Spring offers ifPresentOrElse
from "Utility methods to work with Optionals" to achieve what you want.
Example would be:
import static org.springframework.data.util.Optionals.ifPresentOrElse;
ifPresentOrElse(dao.find(), obj -> obj.setAvailable(true), () -> logger.fatal("Object not available"));
Bootstrap 2 , 3 Check is any modal open in page :
if($('.modal.in').length)
compatible version Bootstrap 2 , 3 , 4+
if($('.modal.in, .modal.show').length)
Only Bootstrap 4+
if($('.modal.show').length)
public boolean isAlertPresent() {
try
{
driver.switchTo().alert();
system.out.println(" Alert Present");
}
catch (NoAlertPresentException e)
{
system.out.println("No Alert Present");
}
}
I think you're missing something.
<ul>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:black;">
</div>
</li>
</ul>
<ul>
<li style="height:100px;">
<div style="height:500px; background-color:red;">
</div>
</li>
</ul>
In FF4, this displays a 100px black bar, followed by a 500px red block.
A little bit different example:
<ul>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:black;">
</div>
</li>
</ul>
<ul>
<li style="height:100px;">
<div style="height:500px; background-color:red;">
</div>
</li>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:blue;">
</div>
</li>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:green;">
</div>
</li>
</ul>
Atom does not have a built-in command for formatting html. However, you can install the atom-beautify package to get this behavior.
I resolved this problem by taking the full and transactional backup. Sometimes, the backup process is not completed and that's one of the reason the .ldf file is not getting shrink. Try this. It worked for me.
This code makes json my default and allows me to use the XML format as well. I'll just append the xml=true
.
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Thanks everyone!
How to filter (skip) non-UTF8 charachers from array?
To address this comment in @uname01's post and the OP, ignore the errors:
Code
>>> b'\x80abc'.decode("utf-8", errors="ignore")
'abc'
Details
From the docs, here are more examples using the same errors
parameter:
>>> b'\x80abc'.decode("utf-8", "replace")
'\ufffdabc'
>>> b'\x80abc'.decode("utf-8", "backslashreplace")
'\\x80abc'
>>> b'\x80abc'.decode("utf-8", "strict")
Traceback (most recent call last):
...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:
invalid start byte
The errors argument specifies the response when the input string can’t be converted according to the encoding’s rules. Legal values for this argument are
'strict'
(raise aUnicodeDecodeError
exception),'replace'
(useU+FFFD
,REPLACEMENT CHARACTER
), or'ignore'
(just leave the character out of the Unicode result).
I would like to add some documentation link. Check out more detail here.
In newer versions change was made to the flags: from the documentation:
--extended-insert, -e
Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.
--opt
This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.
Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.
--skip-extended-insert
Turn off extended-insert
Here is what worked for me (sugested by soulBit):
1) Restart using restart from the file menu
2) Once it started again, manually close and open it.
This is the simplest solution ever and it completely removes the annoying thing.
You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--'
as one of the values.
string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief, ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();
When a fragment is moved to the backstack, it isn't destroyed. All the instance variables remain there. So this is the place to save your data. In onActivityCreated
you check the following conditions:
Edit: Here's an example
public class ExampleFragment extends Fragment {
private List<String> myData;
@Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("list", (Serializable) myData);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
//probably orientation change
myData = (List<String>) savedInstanceState.getSerializable("list");
} else {
if (myData != null) {
//returning from backstack, data is fine, do nothing
} else {
//newly created, compute data
myData = computeData();
}
}
}
}
As the best anwser have writed using XMLHttpResponse
except window.open
, and I make the abstracts-anwser as a instance.
The main Js file is download.js
Download-JS
// var download_url = window.BASE_URL+ "/waf/p1/download_rules";
var download_url = window.BASE_URL+ "/waf/p1/download_logs_by_dt";
function download33() {
var sender_data = {"start_time":"2018-10-9", "end_time":"2018-10-17"};
var x=new XMLHttpRequest();
x.open("POST", download_url, true);
x.setRequestHeader("Content-type","application/json");
// x.setRequestHeader("Access-Control-Allow-Origin", "*");
x.setRequestHeader("Authorization", "JWT " + localStorage.token );
x.responseType = 'blob';
x.onload=function(e){download(x.response, "test211.zip", "application/zip" ); }
x.send( JSON.stringify(sender_data) ); // post-data
}
Based on comments below, it no longer works in modern browsers
This question demonstrates an approach that might be helpful to you: Silent print an embedded PDF
It uses the <embed>
tag to embed the PDF in the document:
<embed
type="application/pdf"
src="path_to_pdf_document.pdf"
id="pdfDocument"
width="100%"
height="100%" />
Then you call the .print()
method on the element in Javascript when the PDF is loaded:
function printDocument(documentId) {
var doc = document.getElementById(documentId);
//Wait until PDF is ready to print
if (typeof doc.print === 'undefined') {
setTimeout(function(){printDocument(documentId);}, 1000);
} else {
doc.print();
}
}
You could place the embed in a hidden iframe and print it from there, giving you a seamless experience.
This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.
In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.
Now sure why it worked, but it did.
Just call plt.show()
at the end:
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0,50,60,80])
for i in np.arange(1,5):
z = 68 + 4 * np.random.randn(50)
zm = np.cumsum(z) / range(1,len(z)+1)
plt.plot(zm)
n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)
plt.plot(n,su,n,sl)
plt.show()
The child process environment is lost in the moment it ceases to exist, and moving the environment content from there to the parent is somewhat tricky.
You probably need to spawn a shell script (you can generate one dynamically to /tmp) which will output the virtualenv environment variables to a file, which you then read in the parent Python process and put in os.environ.
Or you simply parse the activate script in using for the line in open("bin/activate"), manually extract stuff, and put in os.environ. It is tricky, but not impossible.
This can be done in java 8 using Stream.
import java.util.stream.Stream;
String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());
Probably you want something like:
firstline = True
for row in kidfile:
if firstline: #skip first line
firstline = False
continue
# parse the line
An other way to achive the same result is calling readline
before the loop:
kidfile.readline() # skip the first line
for row in kidfile:
#parse the line
You can call sortable
on a <tbody>
instead of on the individual rows.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>?
<script>
$('tbody').sortable();
</script>
$(function() {_x000D_
$( "tbody" ).sortable();_x000D_
});
_x000D_
_x000D_
table {_x000D_
border-spacing: collapse;_x000D_
border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
_x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr> _x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td> _x000D_
<td>10</td>_x000D_
</tr> _x000D_
</tbody> _x000D_
</table>
_x000D_
You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.
You have to set translate property in such way that both the <div>
overlap each other then You can use JavaScript to show and hide both the <div>
according to your requirements
You can also replace without a regular expression.
while(str.indexOf(' ')!=-1)str.replace(' ',' ');
An Algorithm is a clearly defined set of instructions to solve a problem, Heuristics involve utilising an approach of learning and discovery to reach a solution.
So, if you know how to solve a problem then use an algorithm. If you need to develop a solution then it's heuristics.
Swift
You should always use the system defaults and not hard coding the font name because the default font could be changed by Apple at any time.
There are a couple of system default fonts(normal, bold, italic) with different sizes(label, button, others):
let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let font2 = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
let font3 = UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)
beaware that the default font size depends on the target view (label, button, others)
Examples:
let labelFont = UIFont.systemFont(ofSize: UIFont.labelFontSize)
let buttonFont = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
let textFieldFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Lynxster</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
in the name tag give the name of the project folder and save this file with .project extension & paste it in the project folder.
this worked for me.
I am using this solution:
Create a separate repository that holds folder node_modules. If you have native modules that should be build for specific platform then create a separate repository for each platform.
Attach these repositories to your project repository with git submodule
:
git submodule add .../your_project_node_modules_windows.git node_modules_windows
git submodule add .../your_project_node_modules_linux_x86_64 node_modules_linux_x86_64
Create a link from platform-specific node_modules
to node_modules
directory and add node_modules
to .gitignore
.
Run npm install
.
Commit submodule repository changes.
Commit your project repository changes.
So you can easily switch between node_modules
on different platforms (for example, if you are developing on OS X and deploying to Linux).
Python 3
from urllib.error import HTTPError
Python 2
from urllib2 import HTTPError
Just catch HTTPError
, handle it, and if it's not Error 404, simply use raise
to re-raise the exception.
See the Python tutorial.
e.g. complete example for Pyhton 2
import urllib2
from urllib2 import HTTPError
try:
urllib2.urlopen("some url")
except HTTPError as err:
if err.code == 404:
<whatever>
else:
raise
Detach your form form the page you-re using into a simple php page that has the form and php code only, and test it like that.
Any bootstrap or java script might clean out the _FILES[]. That was my case
Use some regex like [0-9]
or \d
:
$words = preg_replace('/\d+/', '', $words );
You might want to read the preg_replace() documentation as this is directly shown there.
You have three possibilites:
(new RegExp('word')).test(str)
// or
/word/.test(str)
str.indexOf('word') !== -1
str.includes('word')
Regular expressions seem to be faster (at least in Chrome 10).
Performance test - short haystack
Performance test - long haystack
It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 indexOf
seems to be faster, in Safari 5, indexOf
is clearly slower than any other method.
You have to see and try for your self. It depends on your needs. For example a case-insensitive search is way faster with regular expressions.
Update 2018:
Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):
Chrome: indexOf (~98% faster) <-- wow
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)
Note that cached RegExp is: var r = new RegExp('simple'); var c = r.test(str);
as opposed to: /simple/.test(str)
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
const PASSENGER_API = 'api/passengers';
getPassengers(): Observable<Passenger[]> {
return this.http
.get<Passenger[]>(PASSENGER_API)
.pipe(catchError((error: HttpErrorResponse) => throwError(error)));
}
Just for fun, let's benchmark it:
$ for ((i=0; i<1000000; i++)) ; do echo $RANDOM; done > random_numbers
$ time perl -nle '$sum += $_ } END { print $sum' random_numbers
16379866392
real 0m0.226s
user 0m0.219s
sys 0m0.002s
$ time awk '{ sum += $1 } END { print sum }' random_numbers
16379866392
real 0m0.311s
user 0m0.304s
sys 0m0.005s
$ time { { tr "\n" + < random_numbers ; echo 0; } | bc; }
16379866392
real 0m0.445s
user 0m0.438s
sys 0m0.024s
$ time { s=0;while read l; do s=$((s+$l));done<random_numbers;echo $s; }
16379866392
real 0m9.309s
user 0m8.404s
sys 0m0.887s
$ time { s=0;while read l; do ((s+=l));done<random_numbers;echo $s; }
16379866392
real 0m7.191s
user 0m6.402s
sys 0m0.776s
$ time { sed ':a;N;s/\n/+/;ta' random_numbers|bc; }
^C
real 4m53.413s
user 4m52.584s
sys 0m0.052s
I aborted the sed run after 5 minutes
I've been diving to lua, and it is speedy:
$ time lua -e 'sum=0; for line in io.lines() do sum=sum+line end; print(sum)' < random_numbers
16388542582.0
real 0m0.362s
user 0m0.313s
sys 0m0.063s
and while I'm updating this, ruby:
$ time ruby -e 'sum = 0; File.foreach(ARGV.shift) {|line| sum+=line.to_i}; puts sum' random_numbers
16388542582
real 0m0.378s
user 0m0.297s
sys 0m0.078s
Heed Ed Morton's advice: using $1
$ time awk '{ sum += $1 } END { print sum }' random_numbers
16388542582
real 0m0.421s
user 0m0.359s
sys 0m0.063s
vs using $0
$ time awk '{ sum += $0 } END { print sum }' random_numbers
16388542582
real 0m0.302s
user 0m0.234s
sys 0m0.063s
If you are using windows8:
command prompt
command prompt
and click Run as administrator
. Then execute the keytool command.Note that if there are ties in top 10 values, you will only get the top 10 rows, not the top 10 values with the answers provided.
Ex: if the top 5 values are 10, 11, 12, 13, 14, 15 but your data contains
10, 10, 11, 12, 13, 14, 15 you will only get 10, 10, 11, 12, 13, 14 as your top 5 with a LIMIT
Here is a solution which will return more than 10 rows if there are ties but you will get all the rows where some_value_column
is technically in the top 10.
select
*
from
(select
*,
rank() over (order by some_value_column desc) as my_rank
from mytable) subquery
where my_rank <= 10
You can define a function type in interface in various ways,
export interface IParam {
title: string;
callback(arg1: number, arg2: number): number;
}
export interface IParam {
title: string;
callback: (arg1: number, arg2: number) => number;
}
type MyFnType = (arg1: number, arg2: number) => number;
export interface IParam {
title: string;
callback: MyFnType;
}
Using is very straight forward,
function callingFn(paramInfo: IParam):number {
let needToCall = true;
let result = 0;
if(needToCall){
result = paramInfo.callback(1,2);
}
return result;
}
export interface IParam{
title: string;
callback(lateCallFn?:
(arg1:number,arg2:number)=>number):number;
}
For ones who wanna use scikit-learn, you can use
from sklearn.preprocessing import normalize
x = [1,2,3,4]
normalize([x]) # array([[0.18257419, 0.36514837, 0.54772256, 0.73029674]])
normalize([x], norm="l1") # array([[0.1, 0.2, 0.3, 0.4]])
normalize([x], norm="max") # array([[0.25, 0.5 , 0.75, 1.]])
In my case the JWT is created by a separate API so ASP.NET need only decode and validate it. In contrast to the accepted answer we're using RSA which is a non-symmetric algorithm, so the SymmetricSecurityKey
class mentioned above won't work.
Here's the result.
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Threading;
using System.Threading.Tasks;
public static async Task<JwtSecurityToken> VerifyAndDecodeJwt(string accessToken)
{
try
{
var configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{securityApiOrigin}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
var openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None);
var validationParameters = new TokenValidationParameters()
{
ValidateLifetime = true,
ValidateAudience = false,
ValidateIssuer = false,
RequireSignedTokens = true,
IssuerSigningKeys = openIdConfig.SigningKeys,
};
new JwtSecurityTokenHandler().ValidateToken(accessToken, validationParameters, out var validToken);
// threw on invalid, so...
return validToken as JwtSecurityToken;
}
catch (Exception ex)
{
logger.Info(ex.Message);
return null;
}
}
It happenes when the entity manager is trying to point to many persistence units. Do the following steps:
Check this
double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first
URL url = new URL(yourUrl, "/api/v1/status.xml");
According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:
URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");
Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage("images/background.png"),
fit: BoxFit.cover
),
),
this also works inside a container.
Can be very simplified like that :
input[type="checkbox"]{
outline:2px solid red;
outline-offset: -2px;
}
Works without any plugin :)
Have you tried: http://flori.github.com/json/?
Failing that, you could just parse it out? If it's only arrays you're interested in, something to split the above out will be quite simple.
2.0 COMPATIBLE SOLUTION:
Execute the below commands in Terminal (Linux/MacOS) or in Command Prompt (Windows) to install Tensorflow 2.0 using Bazel:
git clone https://github.com/tensorflow/tensorflow.git
cd tensorflow
#The repo defaults to the master development branch. You can also checkout a release branch to build:
git checkout r2.0
#Configure the Build => Use the Below line for Windows Machine
python ./configure.py
#Configure the Build => Use the Below line for Linux/MacOS Machine
./configure
#This script prompts you for the location of TensorFlow dependencies and asks for additional build configuration options.
#Build Tensorflow package
#CPU support
bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package
#GPU support
bazel build --config=opt --config=cuda --define=no_tensorflow_py_deps=true //tensorflow/tools/pip_package:build_pip_package
It helped me to convert the result of simplexml_load_file($file) into a JSON Structure and decode it back:
$xml = simplexml_load_file("$token.xml");
$json = json_encode($xml);
$xml_fixed = json_decode($json);
$try1 = $xml->structure->{"@attributes"}['value'];
print_r($try1);
>> result: SimpleXMLElement Object
(
)
$try2 = $xml_fixed->structure->{"@attributes"}['value'];
print_r($try2);
>> result: stdClass Object
(
[key] => value
)
java can not support multiple inheritence.but u can do this in this way
class X
{
}
class Y extends X
{
}
class Z extends Y{
}
That would be to make it difficult for a third-party to insert the JSON response into an HTML document with the <script>
tag. Remember that the <script>
tag is exempt from the Same Origin Policy.
Please check out the below links
http://www.codeproject.com/Questions/376355/import-MS-Excel-to-datatable (6 solutions posted)
A carriage return (\r
) makes the cursor jump to the first column (begin of the line) while the newline (\n
) jumps to the next line and eventually to the beginning of that line. So to be sure to be at the first position within the next line one uses both.
Your Problem were the slice declarations in your data structs
(except for Track
, they shouldn't be slices...). This was compounded by some rather goofy fieldnames in the fetched json file, which can be fixed via structtags, see godoc.
The code below parsed the json successfully. If you've further questions, let me know.
package main
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type Tracks struct {
Toptracks Toptracks_info
}
type Toptracks_info struct {
Track []Track_info
Attr Attr_info `json: "@attr"`
}
type Track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable Streamable_info
Artist Artist_info
Attr Track_attr_info `json: "@attr"`
}
type Attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type Streamable_info struct {
Text string `json: "#text"`
Fulltrack string
}
type Artist_info struct {
Name string
Mbid string
Url string
}
type Track_attr_info struct {
Rank string
}
func perror(err error) {
if err != nil {
panic(err)
}
}
func get_content() {
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
res, err := http.Get(url)
perror(err)
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var data Tracks
err = decoder.Decode(&data)
if err != nil {
fmt.Printf("%T\n%s\n%#v\n",err, err, err)
switch v := err.(type){
case *json.SyntaxError:
fmt.Println(string(body[v.Offset-40:v.Offset]))
}
}
for i, track := range data.Toptracks.Track{
fmt.Printf("%d: %s %s\n", i, track.Artist.Name, track.Name)
}
}
func main() {
get_content()
}
A string is a list of characters (i.e. code points). The number of bytes taken to represent the string depends entirely on which encoding you use to turn it into bytes.
That said, you can turn the string into a byte array and then look at its size as follows:
// The input string for this test
final String string = "Hello World";
// Check length, in characters
System.out.println(string.length()); // prints "11"
// Check encoded sizes
final byte[] utf8Bytes = string.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "11"
final byte[] utf16Bytes= string.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "24"
final byte[] utf32Bytes = string.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "44"
final byte[] isoBytes = string.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "11"
final byte[] winBytes = string.getBytes("CP1252");
System.out.println(winBytes.length); // prints "11"
So you see, even a simple "ASCII" string can have different number of bytes in its representation, depending which encoding is used. Use whichever character set you're interested in for your case, as the argument to getBytes()
. And don't fall into the trap of assuming that UTF-8 represents every character as a single byte, as that's not true either:
final String interesting = "\uF93D\uF936\uF949\uF942"; // Chinese ideograms
// Check length, in characters
System.out.println(interesting.length()); // prints "4"
// Check encoded sizes
final byte[] utf8Bytes = interesting.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "12"
final byte[] utf16Bytes= interesting.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "10"
final byte[] utf32Bytes = interesting.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "16"
final byte[] isoBytes = interesting.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "4" (probably encoded "????")
final byte[] winBytes = interesting.getBytes("CP1252");
System.out.println(winBytes.length); // prints "4" (probably encoded "????")
(Note that if you don't provide a character set argument, the platform's default character set is used. This might be useful in some contexts, but in general you should avoid depending on defaults, and always use an explicit character set when encoding/decoding is required.)
Simply removing libstdc++-6.dll.a \ libstdc++.dll.a from the mingw directory fixes this.
I tried using the flag -static-libstdc++ but this did not work for me. I found the solution in: http://ghc.haskell.org/trac/ghc/ticket/4468#
Try the easy and usable way: just call StripHTML(WebBrowserControl_name);
public string StripHTML(WebBrowser webp)
{
try
{
doc.execCommand("SelectAll", true, null);
IHTMLSelectionObject currentSelection = doc.selection;
if (currentSelection != null)
{
IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
if (range != null)
{
currentSelection.empty();
return range.text;
}
}
}
catch (Exception ep)
{
//MessageBox.Show(ep.Message);
}
return "";
}
I am not sure is it the right way but this one works for me.
First import the component which contains the method you want to call in your component
import myComponent from './MyComponent'
and then call any method of MyCompenent
myComponent.methods.doSomething()
Yes IFNULL function will be working to achieve your desired result.
SELECT uo.order_id, uo.order_total, uo.order_status,
(SELECT IFNULL(SUM(uop.price * uop.qty),0)
FROM uc_order_products uop
WHERE uo.order_id = uop.order_id
) AS products_subtotal,
(SELECT IFNULL(SUM(upr.amount),0)
FROM uc_payment_receipts upr
WHERE uo.order_id = upr.order_id
) AS payment_received,
(SELECT IFNULL(SUM(uoli.amount),0)
FROM uc_order_line_items uoli
WHERE uo.order_id = uoli.order_id
) AS line_item_subtotal
FROM uc_orders uo
WHERE uo.order_status NOT IN ("future", "canceled")
AND uo.uid = 4172;
<merge/>
is useful because it can get rid of unneeded ViewGroups, i.e. layouts that are simply used to wrap other views and serve no purpose themselves.
For example, if you were to <include/>
a layout from another file without using merge, the two files might look something like this:
layout1.xml:
<FrameLayout>
<include layout="@layout/layout2"/>
</FrameLayout>
layout2.xml:
<FrameLayout>
<TextView />
<TextView />
</FrameLayout>
which is functionally equivalent to this single layout:
<FrameLayout>
<FrameLayout>
<TextView />
<TextView />
</FrameLayout>
</FrameLayout>
That FrameLayout in layout2.xml may not be useful. <merge/>
helps get rid of it. Here's what it looks like using merge (layout1.xml doesn't change):
layout2.xml:
<merge>
<TextView />
<TextView />
</merge>
This is functionally equivalent to this layout:
<FrameLayout>
<TextView />
<TextView />
</FrameLayout>
but since you are using <include/>
you can reuse the layout elsewhere. It doesn't have to be used to replace only FrameLayouts - you can use it to replace any layout that isn't adding something useful to the way your view looks/behaves.
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
In the upload.php
file you can access the data passed with $_FILES['file']
.
Thanks everyone for trying to help:)
I took the answer from here (with some changes) MDN
I also added
.modal { position: absolute; }
to the stylesheet to allow the dialog to scroll, but if the user has moved down to the bottom of a long page the modal can end up hidden off the top of the visible area.
I understand this is no longer an issue in bootstrap 3, but looking for a relatively quick fix until we upgrade I ended up with the above plus calling the following before opening the modal
$('.modal').css('top', $(document).scrollTop() + 50);
Seems to be happy in FireFox, Chrome, IE10 8 & 7 (the browsers I had to hand)
Results of testing with the utility Split wrote (link is in his answer):
device: (crash amount/total amount/percentage of total)
Locks still have uses in JS. In my experience I only needed to use locks to prevent spam clicking on elements making AJAX calls. If you have a loader set up for AJAX calls then this isn't required (as well as disabling the button after clicking). But either way here is what I used for locking:
var LOCK_INDEX = [];
function LockCallback(key, action, manual) {
if (LOCK_INDEX[key])
return;
LOCK_INDEX[key] = true;
action(function () { delete LOCK_INDEX[key] });
if (!manual)
delete LOCK_INDEX[key];
}
Usage:
Manual unlock (usually for XHR)
LockCallback('someKey',(delCallback) => {
//do stuff
delCallback(); //Unlock method
}, true)
Auto unlock
LockCallback('someKey',() => {
//do stuff
})
Use following hexadecimal code for transparent text colour: #00FFFF00
If you want to commit on top of the current HEAD with the exact state at a different commit, undoing all the intermediate commits, then you can use reset
to create the correct state of the index to make the commit.
# Reset the index and working tree to the desired tree
# Ensure you have no uncommitted changes that you want to keep
git reset --hard 56e05fced
# Move the branch pointer back to the previous HEAD
git reset --soft HEAD@{1}
git commit -m "Revert to 56e05fced"
For anyone meaning to do this more reliably for different Minecraft versions, I have a Python script (adapted from parts of minecraft-launcher-lib) that does the job very nicely
Besides setting some basic variables near the top after the functions, it calls a get_classpath
that goes through for example ~/.minecraft/versions/1.16.5/1.16.5.json
, and loops over the libraries
array, checking to see if each object (within the array), is supposed to be added to the classpath (cp
variable). whether this library is added to the java classpath is governed by the should_use_library
function, deterministic based on the computer's architecture and operating system. finally, some jarfiles that are platform specific have extra things prepended to them (ex. natives-linux
in org/lwjgl/lwjgl/3.2.1/lwjgl-3.2.1-natives-linux.jar
). this extra prepended string is handled by get_natives_string
and is empty if it doesn't apply to the current library
tested on Linux, distribution Arch Linux
#!/usr/bin/env python
import json
import os
import platform
from pathlib import Path
import subprocess
"""Debug output
"""
def debug(str):
if os.getenv('DEBUG') != None:
print(str)
"""
[Gets the natives_string toprepend to the jar if it exists. If there is nothing native specific, returns and empty string]
"""
def get_natives_string(lib):
arch = ""
if platform.architecture()[0] == "64bit":
arch = "64"
elif platform.architecture()[0] == "32bit":
arch = "32"
else:
raise Exception("Architecture not supported")
nativesFile=""
if not "natives" in lib:
return nativesFile
# i've never seen ${arch}, but leave it in just in case
if "windows" in lib["natives"] and platform.system() == 'Windows':
nativesFile = lib["natives"]["windows"].replace("${arch}", arch)
elif "osx" in lib["natives"] and platform.system() == 'Darwin':
nativesFile = lib["natives"]["osx"].replace("${arch}", arch)
elif "linux" in lib["natives"] and platform.system() == "Linux":
nativesFile = lib["natives"]["linux"].replace("${arch}", arch)
else:
raise Exception("Platform not supported")
return nativesFile
"""[Parses "rule" subpropery of library object, testing to see if should be included]
"""
def should_use_library(lib):
def rule_says_yes(rule):
useLib = None
if rule["action"] == "allow":
useLib = False
elif rule["action"] == "disallow":
useLib = True
if "os" in rule:
for key, value in rule["os"].items():
os = platform.system()
if key == "name":
if value == "windows" and os != 'Windows':
return useLib
elif value == "osx" and os != 'Darwin':
return useLib
elif value == "linux" and os != 'Linux':
return useLib
elif key == "arch":
if value == "x86" and platform.architecture()[0] != "32bit":
return useLib
return not useLib
if not "rules" in lib:
return True
shouldUseLibrary = False
for i in lib["rules"]:
if rule_says_yes(i):
return True
return shouldUseLibrary
"""
[Get string of all libraries to add to java classpath]
"""
def get_classpath(lib, mcDir):
cp = []
for i in lib["libraries"]:
if not should_use_library(i):
continue
libDomain, libName, libVersion = i["name"].split(":")
jarPath = os.path.join(mcDir, "libraries", *
libDomain.split('.'), libName, libVersion)
native = get_natives_string(i)
jarFile = libName + "-" + libVersion + ".jar"
if native != "":
jarFile = libName + "-" + libVersion + "-" + native + ".jar"
cp.append(os.path.join(jarPath, jarFile))
cp.append(os.path.join(mcDir, "versions", lib["id"], f'{lib["id"]}.jar'))
return os.pathsep.join(cp)
version = '1.16.5'
username = '{username}'
uuid = '{uuid}'
accessToken = '{token}'
mcDir = os.path.join(os.getenv('HOME'), '.minecraft')
nativesDir = os.path.join(os.getenv('HOME'), 'versions', version, 'natives')
clientJson = json.loads(
Path(os.path.join(mcDir, 'versions', version, f'{version}.json')).read_text())
classPath = get_classpath(clientJson, mcDir)
mainClass = clientJson['mainClass']
versionType = clientJson['type']
assetIndex = clientJson['assetIndex']['id']
debug(classPath)
debug(mainClass)
debug(versionType)
debug(assetIndex)
subprocess.call([
'/usr/bin/java',
f'-Djava.library.path={nativesDir}',
'-Dminecraft.launcher.brand=custom-launcher',
'-Dminecraft.launcher.version=2.1',
'-cp',
classPath,
'net.minecraft.client.main.Main',
'--username',
username,
'--version',
version,
'--gameDir',
mcDir,
'--assetsDir',
os.path.join(mcDir, 'assets'),
'--assetIndex',
assetIndex,
'--uuid',
uuid,
'--accessToken',
accessToken,
'--userType',
'mojang',
'--versionType',
'release'
])
Runnable (vs) Callable comes into point when we are using Executer framework.
ExecutorService is a subinterface of Executor
, which accepts both Runnable and Callable tasks.
Earlier Multi-Threading can be achieved using Interface Runnable
Since 1.0, but here the problem is after completing the thread task we are unable to collect the Threads information. In-order to collect the data we may use Static fields.
Example Separate threads to collect each student data.
static HashMap<String, List> multiTasksData = new HashMap();
public static void main(String[] args) {
Thread t1 = new Thread( new RunnableImpl(1), "T1" );
Thread t2 = new Thread( new RunnableImpl(2), "T2" );
Thread t3 = new Thread( new RunnableImpl(3), "T3" );
multiTasksData.put("T1", new ArrayList() ); // later get the value and update it.
multiTasksData.put("T2", new ArrayList() );
multiTasksData.put("T3", new ArrayList() );
}
To resolve this problem they have introduced Callable<V>
Since 1.5 which returns a result and may throw an exception.
Single Abstract Method : Both Callable and Runnable interface have a single abstract method, which means they can be used in lambda expressions in java 8.
public interface Runnable {
public void run();
}
public interface Callable<Object> {
public Object call() throws Exception;
}
There are a few different ways to delegate tasks for execution to an ExecutorService.
execute(Runnable task):void
crates new thread but not blocks main thread or caller thread as this method return void.submit(Callable<?>):Future<?>
, submit(Runnable):Future<?>
crates new thread and blocks main thread when you are using future.get().Example of using Interfaces Runnable, Callable with Executor framework.
class CallableTask implements Callable<Integer> {
private int num = 0;
public CallableTask(int num) {
this.num = num;
}
@Override
public Integer call() throws Exception {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " : Started Task...");
for (int i = 0; i < 5; i++) {
System.out.println(i + " : " + threadName + " : " + num);
num = num + i;
MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
}
System.out.println(threadName + " : Completed Task. Final Value : "+ num);
return num;
}
}
class RunnableTask implements Runnable {
private int num = 0;
public RunnableTask(int num) {
this.num = num;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " : Started Task...");
for (int i = 0; i < 5; i++) {
System.out.println(i + " : " + threadName + " : " + num);
num = num + i;
MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
}
System.out.println(threadName + " : Completed Task. Final Value : "+ num);
}
}
public class MainThread_Wait_TillWorkerThreadsComplete {
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println("Main Thread start...");
Instant start = java.time.Instant.now();
runnableThreads();
callableThreads();
Instant end = java.time.Instant.now();
Duration between = java.time.Duration.between(start, end);
System.out.format("Time taken : %02d:%02d.%04d \n", between.toMinutes(), between.getSeconds(), between.toMillis());
System.out.println("Main Thread completed...");
}
public static void runnableThreads() throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<?> f1 = executor.submit( new RunnableTask(5) );
Future<?> f2 = executor.submit( new RunnableTask(2) );
Future<?> f3 = executor.submit( new RunnableTask(1) );
// Waits until pool-thread complete, return null upon successful completion.
System.out.println("F1 : "+ f1.get());
System.out.println("F2 : "+ f2.get());
System.out.println("F3 : "+ f3.get());
executor.shutdown();
}
public static void callableThreads() throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<Integer> f1 = executor.submit( new CallableTask(5) );
Future<Integer> f2 = executor.submit( new CallableTask(2) );
Future<Integer> f3 = executor.submit( new CallableTask(1) );
// Waits until pool-thread complete, returns the result.
System.out.println("F1 : "+ f1.get());
System.out.println("F2 : "+ f2.get());
System.out.println("F3 : "+ f3.get());
executor.shutdown();
}
}
In the case of RStudio for Windows I succeeded in changing the language following the instructions found in R for Windows FAQ, in particular I wrote:
language = EN
inside the file Rconsole
(in my installation it is C:\Program Files\R\R-2.15.2\etc\Rconsole
); this works also for the command Rscript
.
For example you can locate the Rconsole
file with this two commands from a command prompt:
cd \
dir Rconsole /s
The first one make the root as the current directory, the second one looks for the Rconsole
file.
In the following screenshot you have that Rconsole
file is in the folder C:\Program Files\R\R-3.4.1\etc
.
You may have more than one location, in that case you may edit all the Rconsole
files.
After that you can open the Rconsole
file with your favorite editor and look for the line language =
and then append EN
at the end of that line.
In the following screenshot the interesting line is the number 70 and you have to append EN
at the end of it.
It's very simple, Try this code as below:
for(var i = 1; i <= 5; i++) {
for(var j = 1; j<= i; j++) {
document.write("*");
}
document.write("<br/>");
}
You can use lock variables "a" and "b" and synchronize them for locking the "critical section" in reverse order. Eg. Notify "a" then Lock "b" ,"PRINT", Notify "b" then Lock "a".
Please refer the below the code :
public class EvenOdd {
static int a = 0;
public static void main(String[] args) {
EvenOdd eo = new EvenOdd();
A aobj = eo.new A();
B bobj = eo.new B();
aobj.a = Lock.lock1;
aobj.b = Lock.lock2;
bobj.a = Lock.lock2;
bobj.b = Lock.lock1;
Thread t1 = new Thread(aobj);
Thread t2 = new Thread(bobj);
t1.start();
t2.start();
}
static class Lock {
final static Object lock1 = new Object();
final static Object lock2 = new Object();
}
class A implements Runnable {
Object a;
Object b;
public void run() {
while (EvenOdd.a < 10) {
try {
System.out.println(++EvenOdd.a + " A ");
synchronized (a) {
a.notify();
}
synchronized (b) {
b.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class B implements Runnable {
Object a;
Object b;
public void run() {
while (EvenOdd.a < 10) {
try {
synchronized (b) {
b.wait();
System.out.println(++EvenOdd.a + " B ");
}
synchronized (a) {
a.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
OUTPUT :
1 A
2 B
3 A
4 B
5 A
6 B
7 A
8 B
9 A
10 B
**Return the comman longest substring**
def longestSubString(str1, str2):
longestString = ""
maxLength = 0
for i in range(0, len(str1)):
if str1[i] in str2:
for j in range(i + 1, len(str1)):
if str1[i:j] in str2:
if(len(str1[i:j]) > maxLength):
maxLength = len(str1[i:j])
longestString = str1[i:j]
return longestString
async function main() {
var getQuoteError
var quote = await getQuote().catch(err => { getQuoteError = err }
if (getQuoteError) return console.error(err)
console.log(quote)
}
Alternatively instead of declaring a possible var to hold an error at the top you can do
if (quote instanceof Error) {
// ...
}
Though that won't work if something like a TypeError or Reference error is thrown. You can ensure it is a regular error though with
async function main() {
var quote = await getQuote().catch(err => {
console.error(err)
return new Error('Error getting quote')
})
if (quote instanceOf Error) return quote // get out of here or do whatever
console.log(quote)
}
My preference for this is wrapping everything in a big try-catch block where there's multiple promises being created can make it cumbersome to handle the error specifically to the promise that created it. With the alternative being multiple try-catch blocks which I find equally cumbersome
1.Create new folder in d drive D:/data/db
2.Open terminal on D:/data/db
3.Type mongod and enter.
4.Type mongo and enter.
and your mongodb has strated............
app._router.stack.forEach(function(r){
if (r.route && r.route.path){
console.log(r.route.path)
}
})
You have to disable the sandbox for Groovy in your job configuration.
Currently this is not possible for multibranch projects where the groovy script comes from the scm. For more information see https://issues.jenkins-ci.org/browse/JENKINS-28178
I just thought to give you the reason why your solution did not work:
When $(document).ready()
is executed only the $('#topbar-show')
selector can find a matching element from the DOM. The #topbar-show
element has not been created yet.
To get past this problem, you may use live event bindings
$('#topbar-show').live('click',function(e){});
$('#topbar-hide').live('click',function(e){});
This is the most simple way to fix you solution. The rest of these answer go further to provide you a better solutions instead that do not modify the hopefully permanent id attribute.
When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.
So it is safe in the sense of that the result might be huge and wrong, but it will never crash.
Place it in a div and give it an id
<div id=myForm>
then create a really really simple css to go with it.
#myForm select {
width:200px; }
#myForm select:focus {
width:auto; }
That's all you need.
You can use
insert into table_name
(date_field)
values
(TO_DATE('2003/05/03 21:02:44', 'yyyy/mm/dd hh24:mi:ss'));
Hope it helps.
I've solved the problem , and I will explain how :
Alternatively , if you don't want to add to environment variables. You can open the android studio and go to : Settings -> Version Control -> Git In text box next to "Path to Git Executable" you will see "git.exe" , just give it a full path like so : C:\Users\Your_Username\AppData\Local\GitHub\PortableGit_ca477551eeb4aea0e4ae9fcd3358bd96720bb5c8\bin\git.exe
Hope it saved your time . Happy coding :)
EDIT : For latest Github for windows versions some can find the git.exe under "...\cmd\git.exe" rather than "...\bin\git.exe".
Bash is primarily a batch / shell scripting language with far less support for various data types and all sorts of quirks around control structures -- not to mention compatibility issues.
Which is faster? Neither, because you are not comparing apples to apples here. If you had to sort an ascii text file and you were using tools like zcat, sort, uniq, and sed then you will smoke Python performance wise.
However, if you need a proper programming environment that supports floating point and various control flow, then Python wins hands down. If you wrote say a recursive algorithm in Bash and Python, the Python version will win in an order of magnitude or more.
As described here http://developer.android.com/reference/java/util/regex/Pattern.html
Patterns are compiled regular expressions. In many cases, convenience methods such as
String.matches
,String.replaceAll
andString.split
will be preferable, but if you need to do a lot of work with the same regular expression, it may be more efficient to compile it once and reuse it. The Pattern class and its companion, Matcher, also offer more functionality than the small amount exposed by String.
public class RegularExpressionTest {
public static void main(String[] args) {
System.out.println("String is = "+getOnlyStrings("!&(*^*(^(+one(&(^()(*)(*&^%$#@!#$%^&*()("));
System.out.println("Number is = "+getOnlyDigits("&(*^*(^(+91-&*9hi-639-0097(&(^("));
}
public static String getOnlyDigits(String s) {
Pattern pattern = Pattern.compile("[^0-9]");
Matcher matcher = pattern.matcher(s);
String number = matcher.replaceAll("");
return number;
}
public static String getOnlyStrings(String s) {
Pattern pattern = Pattern.compile("[^a-z A-Z]");
Matcher matcher = pattern.matcher(s);
String number = matcher.replaceAll("");
return number;
}
}
Result
String is = one
Number is = 9196390097
Most answers here are not correct as they would add bottom space to the last <li>
as well, so they are not adding space ONLY in between <li>
!
The most accurate and efficient solution is the following:
li.menu-item:not(:last-child) {
margin-bottom: 3px;
}
Explanation:
by using :not(:last-child)
the style will be applie to all items (li.menu-item) but the last one.
Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.
@Path("/hello")
public class Hello {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {
String input = (String) inputJsonObj.get("input");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
And, your client code should look like this:
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new LoggingFilter());
WebResource service = client.resource(getBaseURI());
JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("input", "Value");
System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));
This works, apply in ul
:
display:flex;
flex-direction:column;
flex-wrap:wrap;
I've had this problem before, you can go to "advanced" tab of "choose a data source" page and click on "suggested types" button, and set the "number of rows" as much as you want. after that, the type and text qualified are set to the true values.
i applied the above solution and can convert my data to SQL.
open powershell and run below command:
import-csv C:\Users\Documents\Weekly_Status.csv | export-csv C:\Users\Documents\Weekly_Status2.csv -NoTypeInformation -Encoding UTF8
If you want to use jquery $("..").is(":focus")
.
You can take a look at this stack
input
may have a hidden attribute:input:checked + span::before {
content: 'un';
}
_x000D_
<label>
<input type='checkbox' hidden/>
<span>check</span>
<label>
_x000D_
I had the same error message and after lots of trial and error found out that it was caused by an advanced filter which was set on the ListObject. After clearing the advanced filter .listrows.add worked fine again. To clear the filter I use this - no idea how one could clear the filter only for the specific listobject instead of the complete worksheet.
Worksheets("mysheet").ShowAllData
#include <iostream>
#include <string>
using namespace std;
// Replace function..
string replace(string word, string target, string replacement){
int len, loop=0;
string nword="", let;
len=word.length();
len--;
while(loop<=len){
let=word.substr(loop, 1);
if(let==target){
nword=nword+replacement;
}else{
nword=nword+let;
}
loop++;
}
return nword;
}
//Main..
int main() {
string word;
cout<<"Enter Word: ";
cin>>word;
cout<<replace(word, "x", "y")<<endl;
return 0;
}
Google Apps Script is javascript, you can use all the string methods...
var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }
You can find doc on many sites, this one for example.
I have Following code perfactly run using ajax with multi-part form data
function getUserDetail()
{
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var phoneNumber = document.getElementById("phoneNumber").value;
var gender =$("#userForm input[type='radio']:checked").val();
//var gender2 = document.getElementById("gender2").value;
//alert("fn"+firstName+lastName+username+email);
var roleIndex = document.getElementById("role");
var role = roleIndex.options[roleIndex.selectedIndex].value;
var jobTitleIndex = document.getElementById("jobTitle");
var jobTitle = jobTitleIndex.options[jobTitleIndex.selectedIndex].value;
var shiftIdIndex = document.getElementById("shiftId");
var shiftId = shiftIdIndex.options[shiftIdIndex.selectedIndex].value;
var addressLine1 = document.getElementById("addressLine1").value;
var addressLine2 = document.getElementById("addressLine2").value;
var streetRoad = document.getElementById("streetRoad").value;
var countryIndex = document.getElementById("country");
var country = countryIndex.options[countryIndex.selectedIndex].value;
var stateIndex = document.getElementById("state");
var state = stateIndex.options[stateIndex.selectedIndex].value;
var cityIndex = document.getElementById("city");
var city = cityIndex.options[cityIndex.selectedIndex].value;
var pincode = document.getElementById("pincode").value;
var branchIndex = document.getElementById("branch");
var branch = branchIndex.options[branchIndex.selectedIndex].value;
var language = document.getElementById("language").value;
var profilePicture = document.getElementById("profilePicture").value;
//alert(profilePicture);
var addDocument = document.getElementById("addDocument").value;
var shiftIdIndex = document.getElementById("shiftId");
var shiftId = shiftIdIndex.options[shiftIdIndex.selectedIndex].value;
var data = new FormData();
data.append('firstName', firstName);
data.append('lastName', lastName);
data.append('username', username);
data.append('email', email);
data.append('phoneNumber', phoneNumber);
data.append('role', role);
data.append('jobTitle', jobTitle);
data.append('gender', gender);
data.append('shiftId', shiftId);
data.append('lastName', lastName);
data.append('addressLine1', addressLine1);
data.append('addressLine2', addressLine2);
data.append('streetRoad', streetRoad);
data.append('country', country);
data.append('state', state);
data.append('city', city);
data.append('pincode', pincode);
data.append('branch', branch);
data.append('language', language);
data.append('profilePicture', $('#profilePicture')[0].files[0]);
for (var i = 0; i < $('#document')[0].files.length; i++) {
data.append('document[]', $('#document')[0].files[i]);
}
$.ajax({
//url : '${pageContext.request.contextPath}/user/save-user',
type: "POST",
Accept: "application/json",
async: true,
contentType:false,
processData: false,
data: data,
cache: false,
success : function(data) {
reset();
$(".alert alert-success alert-div").text("New User Created Successfully!");
},
error :function(data, textStatus, xhr){
$(".alert alert-danger alert-div").text("new User Not Create!");
}
});
//
}
.container {_x000D_
width:100%;_x000D_
display:table;_x000D_
vertical-align:middle;_x000D_
}_x000D_
_x000D_
.left {_x000D_
width:100%;_x000D_
display:table-cell;_x000D_
text-align:center;_x000D_
}_x000D_
_x000D_
.right {_x000D_
width:40px;_x000D_
height:40px;_x000D_
display:table-cell;_x000D_
float:right;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div
_x000D_
Try this. It worked for me.
__tests__
folderYou could add a .eslintrc.yml
file in your __tests__
folders, that extends you basic configuration:
extends: <relative_path to .eslintrc>
env:
jest: true
If you have only one __tests__
folder, this solution is the best since it scope jest environment only where it is needed.
If you have more test folders (OPs case), I'd still suggest to add those files. And if you have tons of those folders can add them with a simple zsh script:
#!/usr/bin/env zsh
for folder in **/__tests__/ ;do
count=$(($(tr -cd '/' <<< $folder | wc -c)))
echo $folder : $count
cat <<EOF > $folder.eslintrc.yml
extends: $(printf '../%.0s' {1..$count}).eslintrc
env:
jest: true
EOF
done
This script will look for __tests__
folders and add a .eslintrc.yml
file with to configuration shown above. This script has to be launched within the folder containing your parent .eslintrc
.
Here is the MD5 code inserted in an Excel Module with the name "module_md5":
Private Const BITS_TO_A_BYTE = 8
Private Const BYTES_TO_A_WORD = 4
Private Const BITS_TO_A_WORD = 32
Private m_lOnBits(30)
Private m_l2Power(30)
Sub SetUpArrays()
m_lOnBits(0) = CLng(1)
m_lOnBits(1) = CLng(3)
m_lOnBits(2) = CLng(7)
m_lOnBits(3) = CLng(15)
m_lOnBits(4) = CLng(31)
m_lOnBits(5) = CLng(63)
m_lOnBits(6) = CLng(127)
m_lOnBits(7) = CLng(255)
m_lOnBits(8) = CLng(511)
m_lOnBits(9) = CLng(1023)
m_lOnBits(10) = CLng(2047)
m_lOnBits(11) = CLng(4095)
m_lOnBits(12) = CLng(8191)
m_lOnBits(13) = CLng(16383)
m_lOnBits(14) = CLng(32767)
m_lOnBits(15) = CLng(65535)
m_lOnBits(16) = CLng(131071)
m_lOnBits(17) = CLng(262143)
m_lOnBits(18) = CLng(524287)
m_lOnBits(19) = CLng(1048575)
m_lOnBits(20) = CLng(2097151)
m_lOnBits(21) = CLng(4194303)
m_lOnBits(22) = CLng(8388607)
m_lOnBits(23) = CLng(16777215)
m_lOnBits(24) = CLng(33554431)
m_lOnBits(25) = CLng(67108863)
m_lOnBits(26) = CLng(134217727)
m_lOnBits(27) = CLng(268435455)
m_lOnBits(28) = CLng(536870911)
m_lOnBits(29) = CLng(1073741823)
m_lOnBits(30) = CLng(2147483647)
m_l2Power(0) = CLng(1)
m_l2Power(1) = CLng(2)
m_l2Power(2) = CLng(4)
m_l2Power(3) = CLng(8)
m_l2Power(4) = CLng(16)
m_l2Power(5) = CLng(32)
m_l2Power(6) = CLng(64)
m_l2Power(7) = CLng(128)
m_l2Power(8) = CLng(256)
m_l2Power(9) = CLng(512)
m_l2Power(10) = CLng(1024)
m_l2Power(11) = CLng(2048)
m_l2Power(12) = CLng(4096)
m_l2Power(13) = CLng(8192)
m_l2Power(14) = CLng(16384)
m_l2Power(15) = CLng(32768)
m_l2Power(16) = CLng(65536)
m_l2Power(17) = CLng(131072)
m_l2Power(18) = CLng(262144)
m_l2Power(19) = CLng(524288)
m_l2Power(20) = CLng(1048576)
m_l2Power(21) = CLng(2097152)
m_l2Power(22) = CLng(4194304)
m_l2Power(23) = CLng(8388608)
m_l2Power(24) = CLng(16777216)
m_l2Power(25) = CLng(33554432)
m_l2Power(26) = CLng(67108864)
m_l2Power(27) = CLng(134217728)
m_l2Power(28) = CLng(268435456)
m_l2Power(29) = CLng(536870912)
m_l2Power(30) = CLng(1073741824)
End Sub
Private Function LShift(lValue, iShiftBits)
If iShiftBits = 0 Then
LShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And 1 Then
LShift = &H80000000
Else
LShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
If (lValue And m_l2Power(31 - iShiftBits)) Then
LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
Else
LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
End If
End Function
Private Function RShift(lValue, iShiftBits)
If iShiftBits = 0 Then
RShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And &H80000000 Then
RShift = 1
Else
RShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)
If (lValue And &H80000000) Then
RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
End If
End Function
Private Function RotateLeft(lValue, iShiftBits)
RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
End Function
Private Function AddUnsigned(lX, lY)
Dim lX4
Dim lY4
Dim lX8
Dim lY8
Dim lResult
lX8 = lX And &H80000000
lY8 = lY And &H80000000
lX4 = lX And &H40000000
lY4 = lY And &H40000000
lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)
If lX4 And lY4 Then
lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
ElseIf lX4 Or lY4 Then
If lResult And &H40000000 Then
lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
Else
lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
End If
Else
lResult = lResult Xor lX8 Xor lY8
End If
AddUnsigned = lResult
End Function
Private Function F(x, y, z)
F = (x And y) Or ((Not x) And z)
End Function
Private Function G(x, y, z)
G = (x And z) Or (y And (Not z))
End Function
Private Function H(x, y, z)
H = (x Xor y Xor z)
End Function
Private Function I(x, y, z)
I = (y Xor (x Or (Not z)))
End Function
Private Sub FF(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub GG(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub HH(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub II(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Function ConvertToWordArray(sMessage)
Dim lMessageLength
Dim lNumberOfWords
Dim lWordArray()
Dim lBytePosition
Dim lByteCount
Dim lWordCount
Const MODULUS_BITS = 512
Const CONGRUENT_BITS = 448
lMessageLength = Len(sMessage)
lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
ReDim lWordArray(lNumberOfWords - 1)
lBytePosition = 0
lByteCount = 0
Do Until lByteCount >= lMessageLength
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
lByteCount = lByteCount + 1
Loop
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)
lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)
ConvertToWordArray = lWordArray
End Function
Private Function WordToHex(lValue)
Dim lByte
Dim lCount
For lCount = 0 To 3
lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
Next
End Function
Public Function MD5(sMessage)
module_md5.SetUpArrays
Dim x
Dim k
Dim AA
Dim BB
Dim CC
Dim DD
Dim a
Dim b
Dim c
Dim d
Const S11 = 7
Const S12 = 12
Const S13 = 17
Const S14 = 22
Const S21 = 5
Const S22 = 9
Const S23 = 14
Const S24 = 20
Const S31 = 4
Const S32 = 11
Const S33 = 16
Const S34 = 23
Const S41 = 6
Const S42 = 10
Const S43 = 15
Const S44 = 21
x = ConvertToWordArray(sMessage)
a = &H67452301
b = &HEFCDAB89
c = &H98BADCFE
d = &H10325476
For k = 0 To UBound(x) Step 16
AA = a
BB = b
CC = c
DD = d
FF a, b, c, d, x(k + 0), S11, &HD76AA478
FF d, a, b, c, x(k + 1), S12, &HE8C7B756
FF c, d, a, b, x(k + 2), S13, &H242070DB
FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
FF d, a, b, c, x(k + 5), S12, &H4787C62A
FF c, d, a, b, x(k + 6), S13, &HA8304613
FF b, c, d, a, x(k + 7), S14, &HFD469501
FF a, b, c, d, x(k + 8), S11, &H698098D8
FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
FF b, c, d, a, x(k + 11), S14, &H895CD7BE
FF a, b, c, d, x(k + 12), S11, &H6B901122
FF d, a, b, c, x(k + 13), S12, &HFD987193
FF c, d, a, b, x(k + 14), S13, &HA679438E
FF b, c, d, a, x(k + 15), S14, &H49B40821
GG a, b, c, d, x(k + 1), S21, &HF61E2562
GG d, a, b, c, x(k + 6), S22, &HC040B340
GG c, d, a, b, x(k + 11), S23, &H265E5A51
GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
GG a, b, c, d, x(k + 5), S21, &HD62F105D
GG d, a, b, c, x(k + 10), S22, &H2441453
GG c, d, a, b, x(k + 15), S23, &HD8A1E681
GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
GG d, a, b, c, x(k + 14), S22, &HC33707D6
GG c, d, a, b, x(k + 3), S23, &HF4D50D87
GG b, c, d, a, x(k + 8), S24, &H455A14ED
GG a, b, c, d, x(k + 13), S21, &HA9E3E905
GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
GG c, d, a, b, x(k + 7), S23, &H676F02D9
GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A
HH a, b, c, d, x(k + 5), S31, &HFFFA3942
HH d, a, b, c, x(k + 8), S32, &H8771F681
HH c, d, a, b, x(k + 11), S33, &H6D9D6122
HH b, c, d, a, x(k + 14), S34, &HFDE5380C
HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
HH a, b, c, d, x(k + 13), S31, &H289B7EC6
HH d, a, b, c, x(k + 0), S32, &HEAA127FA
HH c, d, a, b, x(k + 3), S33, &HD4EF3085
HH b, c, d, a, x(k + 6), S34, &H4881D05
HH a, b, c, d, x(k + 9), S31, &HD9D4D039
HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
HH b, c, d, a, x(k + 2), S34, &HC4AC5665
II a, b, c, d, x(k + 0), S41, &HF4292244
II d, a, b, c, x(k + 7), S42, &H432AFF97
II c, d, a, b, x(k + 14), S43, &HAB9423A7
II b, c, d, a, x(k + 5), S44, &HFC93A039
II a, b, c, d, x(k + 12), S41, &H655B59C3
II d, a, b, c, x(k + 3), S42, &H8F0CCC92
II c, d, a, b, x(k + 10), S43, &HFFEFF47D
II b, c, d, a, x(k + 1), S44, &H85845DD1
II a, b, c, d, x(k + 8), S41, &H6FA87E4F
II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
II c, d, a, b, x(k + 6), S43, &HA3014314
II b, c, d, a, x(k + 13), S44, &H4E0811A1
II a, b, c, d, x(k + 4), S41, &HF7537E82
II d, a, b, c, x(k + 11), S42, &HBD3AF235
II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
II b, c, d, a, x(k + 9), S44, &HEB86D391
a = AddUnsigned(a, AA)
b = AddUnsigned(b, BB)
c = AddUnsigned(c, CC)
d = AddUnsigned(d, DD)
Next
MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
End Function
Have you tried:
ifconfig 10:35978f0 down
As the physical interface is 10
and the virtual aspect is after the colon :
.
See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/
SQL Error: ORA-30926: unable to get a stable set of rows in the source tables
30926. 00000 - "unable to get a stable set of rows in the source tables"
*Cause: A stable set of rows could not be got because of large dml
activity or a non-deterministic where clause.
*Action: Remove any non-deterministic where clauses and reissue the dml.
This Error occurred for me because of duplicate records(16K)
I tried with unique it worked .
but again when I tried merge without unique same proble occurred Second time it was due to commit
after merge if commit is not done same Error will be shown.
Without unique, Query will work if commit is given after each merge operation.
Adding to the mentions of jwplayer and possible TOS violations, I would like to to link to the following repository on github: YouTube Audio Player Generation Library, that allows to generate the following output:
Library has the support for the playlists and PHP autorendering given the video URL and the configuration options.
In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.
To convert a NSDictionary to a NSString:
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Wildcard method: Add the following entry into your DNS server and change the domain and IP address accordingly.
*.example.com IN A 1.2.3.4
I think the short answer is no. For a more generic case in n
dimensions, I came up with this:
# For 2-dimensional data, 4 values
a = np.array([[0, 1, 2], [3, 2, 1]])
z = np.zeros(list(a.shape) + [4])
z[list(np.indices(z.shape[:-1])) + [a]] = 1
I am wondering if there is a better solution -- I don't like that I have to create those lists in the last two lines. Anyway, I did some measurements with timeit
and it seems that the numpy
-based (indices
/arange
) and the iterative versions perform about the same.
Hardcoding the size or using reflection to get the value of status_bar_height
is considered bad practice. Chris Banes talked about this in at the Droidcon New York. The recommended way of getting the status bar size is via the OnApplyWindowInsetsListener:
myView.setOnApplyWindowInsetsListener { view, insets -> {
val statusBarSize = insets.systemWindowInsetTop
return insets
}
This was added in API 20 and is also backported via ViewAppCompat.
Instead of using the ScrimInsetsFrameLayout
... Isn't it easier to just add a view with a fixed height of 24dp
and a background of primaryColor
?
I understand that this involves adding a dummy view in the hierarchy, but it seems cleaner to me.
I already tried it and it's working well.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_base_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- THIS IS THE VIEW I'M TALKING ABOUT... -->
<View
android:layout_width="match_parent"
android:layout_height="24dp"
android:background="?attr/colorPrimary" />
<android.support.v7.widget.Toolbar
android:id="@+id/activity_base_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="2dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark" />
<FrameLayout
android:id="@+id/activity_base_content_frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<fragment
android:id="@+id/activity_base_drawer_fragment"
android:name="com.myapp.drawer.ui.DrawerFragment"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:elevation="4dp"
tools:layout="@layout/fragment_drawer" />
</android.support.v4.widget.DrawerLayout>
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
Try this
// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);
// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);
If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)
Also keep in mind that decimalFormat.parse
can throw a ParseException
so you need to handle it (with try/catch) or throw it and let another part of your program handle it
Parsing JSON is painful in a shell script. With a more appropriate language, create a tool that extracts JSON attributes in a way consistent with shell scripting conventions. You can use your new tool to solve the immediate shell scripting problem and then add it to your kit for future situations.
For example, consider a tool jsonlookup such that if I say jsonlookup access token id
it will return the attribute id defined within the attribute token defined within the attribute access from stdin, which is presumably JSON data. If the attribute doesn't exist, the tool returns nothing (exit status 1). If the parsing fails, exit status 2 and a message to stderr. If the lookup succeeds, the tool prints the attribute's value.
Having created a unix tool for the precise purpose of extracting JSON values you can easily use it in shell scripts:
access_token=$(curl <some horrible crap> | jsonlookup access token id)
Any language will do for the implementation of jsonlookup. Here is a fairly concise python version:
#!/usr/bin/python
import sys
import json
try: rep = json.loads(sys.stdin.read())
except:
sys.stderr.write(sys.argv[0] + ": unable to parse JSON from stdin\n")
sys.exit(2)
for key in sys.argv[1:]:
if key not in rep:
sys.exit(1)
rep = rep[key]
print rep
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("tr1").show();
$("tr1").hide();
From the node.js documentation, "To have a module execute code multiple times, export a function, and call that function", you could use node.js module.export and have a single file to manage the db connections.You can find more at Node.js documentation. Let's say db.js file be like:
const mysql = require('mysql');
var connection;
module.exports = {
dbConnection: function () {
connection = mysql.createConnection({
host: "127.0.0.1",
user: "Your_user",
password: "Your_password",
database: 'Your_bd'
});
connection.connect();
return connection;
}
};
Then, the file where you are going to use the connection could be like useDb.js:
const dbConnection = require('./db');
var connection;
function callDb() {
try {
connection = dbConnectionManager.dbConnection();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (!error) {
let response = "The solution is: " + results[0].solution;
console.log(response);
} else {
console.log(error);
}
});
connection.end();
} catch (err) {
console.log(err);
}
}
Try phoneNumber.setVisibility(View.GONE);
Google has threatened to remove apps from the Play Store if they use accessibility services for non-accessibility purposes. However, this is reportedly being reconsidered.
AccessibilityService
AccessibilityService
.onAccessibilityEvent
callback, check for the TYPE_WINDOW_STATE_CHANGED
event type to determine when the current window changes.PackageManager.getActivityInfo()
.GET_TASKS
permission.AccessibilityService
, they can't press the OK button if an app has placed an overlay on the screen. Some apps that do this are Velis Auto Brightness and Lux. This can be confusing because the user might not know why they can't press the button or how to work around it. AccessibilityService
won't know the current activity until the first change of activity.public class WindowChangeDetectingService extends AccessibilityService {
@Override
protected void onServiceConnected() {
super.onServiceConnected();
//Configure these here for compatibility with API 13 and below.
AccessibilityServiceInfo config = new AccessibilityServiceInfo();
config.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
if (Build.VERSION.SDK_INT >= 16)
//Just in case this helps
config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
setServiceInfo(config);
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
if (event.getPackageName() != null && event.getClassName() != null) {
ComponentName componentName = new ComponentName(
event.getPackageName().toString(),
event.getClassName().toString()
);
ActivityInfo activityInfo = tryGetActivity(componentName);
boolean isActivity = activityInfo != null;
if (isActivity)
Log.i("CurrentActivity", componentName.flattenToShortString());
}
}
}
private ActivityInfo tryGetActivity(ComponentName componentName) {
try {
return getPackageManager().getActivityInfo(componentName, 0);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
@Override
public void onInterrupt() {}
}
Merge this into your manifest:
<application>
<service
android:label="@string/accessibility_service_name"
android:name=".WindowChangeDetectingService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/accessibilityservice"/>
</service>
</application>
Put this in res/xml/accessibilityservice.xml
:
<?xml version="1.0" encoding="utf-8"?>
<!-- These options MUST be specified here in order for the events to be received on first
start in Android 4.1.1 -->
<accessibility-service
xmlns:tools="http://schemas.android.com/tools"
android:accessibilityEventTypes="typeWindowStateChanged"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagIncludeNotImportantViews"
android:description="@string/accessibility_service_description"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:ignore="UnusedAttribute"/>
Each user of the app will need to explicitly enable the AccessibilityService
in order for it to be used. See this StackOverflow answer for how to do this.
Note that the user won't be able to press the OK button when trying to enable the accessibility service if an app has placed an overlay on the screen, such as Velis Auto Brightness or Lux.
seems like in Angular 1.3.12 you do not need the inner ng-repeat anymore, the outer loop returns the values of the collection is a single map entry
$('#elm').removeAttr('class');
no longer class attr wil be present in "elm".
The cross browser way to do is to use childNodes
to get NodeList
, then make an array of all nodes with nodeType
ELEMENT_NODE.
/**
* Return direct children elements.
*
* @param {HTMLElement}
* @return {Array}
*/
function elementChildren (element) {
var childNodes = element.childNodes,
children = [],
i = childNodes.length;
while (i--) {
if (childNodes[i].nodeType == 1) {
children.unshift(childNodes[i]);
}
}
return children;
}
This is especially easy if you are using a utility library such as lodash:
/**
* Return direct children elements.
*
* @param {HTMLElement}
* @return {Array}
*/
function elementChildren (element) {
return _.where(element.childNodes, {nodeType: 1});
}
Future:
You can use querySelectorAll
in combination with :scope
pseudo-class (matches the element that is the reference point of the selector):
parentElement.querySelectorAll(':scope > *');
At the time of writing this :scope
is supported in Chrome, Firefox and Safari.
In some systems like your office system, there is sometimes a firewall/security client that is installed for security purpose. Try uninstalling that and then run the command again, it should start the download.
My system had Netskope Client installed and was blocking the ssl communication.
Search in finder -> uninstall netskope, run it, and try installing homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
PS: consider installing the security client.
Most of previous answers call the success of the promise in the on("data"), it is not the proper way to do it because if you receive a lot of data you will only get the first part. Instead you have to do it on the end event.
const { spawn } = require('child_process');
const pythonDir = (__dirname + "/../pythonCode/"); // Path of python script folder
const python = pythonDir + "pythonEnv/bin/python"; // Path of the Python interpreter
/** remove warning that you don't care about */
function cleanWarning(error) {
return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}
function callPython(scriptName, args) {
return new Promise(function(success, reject) {
const script = pythonDir + scriptName;
const pyArgs = [script, JSON.stringify(args) ]
const pyprog = spawn(python, pyArgs );
let result = "";
let resultError = "";
pyprog.stdout.on('data', function(data) {
result += data.toString();
});
pyprog.stderr.on('data', (data) => {
resultError += cleanWarning(data.toString());
});
pyprog.stdout.on("end", function(){
if(resultError == "") {
success(JSON.parse(result));
}else{
console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
const error = new Error(resultError);
console.error(error);
reject(resultError);
}
})
});
}
module.exports.callPython = callPython;
Call:
const pythonCaller = require("../core/pythonCaller");
const result = await pythonCaller.callPython("preprocessorSentiment.py", {"thekeyYouwant": value});
python:
try:
argu = json.loads(sys.argv[1])
except:
raise Exception("error while loading argument")
You are missing the border width and the border style properties in the Border shorthand property :
.circle {
border: 2px solid red;
background-color: #FFFFFF;
height: 100px;
border-radius:50%;
width: 100px;
}
_x000D_
<div class="circle"></div>
_x000D_
Also, You can use percentages for the border-radius property so that the value isn't dependent of the circle width/height. That is why I used 50% for border-radius (more info on border-radius in pixels and percent).
Side note : In your example, you didn't specify the border-radius property without vendor prefixes whitch you propably don't need as only browsers before chrome 4 safari 4 and Firefox 3.6 use them (see canIuse).
File permissions are restrictive on the Postgres db owned by the Mac OS. These permissions are reset after reboot, or restart of Postgres: e.g. serveradmin start postgres.
So, temporarily reset the permissions or ownership:
sudo chmod o+rwx /var/pgsql_socket/.s.PGSQL.5432
sudo chown "webUser" /var/pgsql_socket/.s.PGSQL.5432
Permissions resetting is not secure, so install a version of the db that you own for a solution.
You can not access the docker's IP from outside of that host machine.
If your browser is on another machine better to map the host port to container port by passing -p 8080:8080
to run command.
Passing -p
you can map host port to container port and a proxy is set to forward all traffix for said host port to designated container port.
Basically it would be the wrong thing to do.
There are two ways this could be implemented:
Keep hold of the lock, only releasing it at the end of the block.
This is a really bad idea as you don't know how long the asynchronous operation is going to take. You should only hold locks for minimal amounts of time. It's also potentially impossible, as a thread owns a lock, not a method - and you may not even execute the rest of the asynchronous method on the same thread (depending on the task scheduler).
Release the lock in the await, and reacquire it when the await returns
This violates the principle of least astonishment IMO, where the asynchronous method should behave as closely as possible like the equivalent synchronous code - unless you use Monitor.Wait
in a lock block, you expect to own the lock for the duration of the block.
So basically there are two competing requirements here - you shouldn't be trying to do the first here, and if you want to take the second approach you can make the code much clearer by having two separated lock blocks separated by the await expression:
// Now it's clear where the locks will be acquired and released
lock (foo)
{
}
var result = await something;
lock (foo)
{
}
So by prohibiting you from awaiting in the lock block itself, the language is forcing you to think about what you really want to do, and making that choice clearer in the code that you write.
Don't set height AND width. Use one or the other and the correct aspect ratio will be maintained.
.widthSet {_x000D_
max-width: 64px;_x000D_
}_x000D_
_x000D_
.heightSet {_x000D_
max-height: 64px;_x000D_
}
_x000D_
<img src="http://placehold.it/200x250" />_x000D_
_x000D_
<img src="http://placehold.it/200x250" width="64" />_x000D_
_x000D_
<img src="http://placehold.it/200x250" height="64" />_x000D_
_x000D_
<img src="http://placehold.it/200x250" class="widthSet" />_x000D_
_x000D_
<img src="http://placehold.it/200x250" class="heightSet" />
_x000D_
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document
) and will be executed when an event reaches that element having originated on an element matching the selector.
This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id
element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.
The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.
By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id
element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.
Easiest way to check if they are authenticated is Request.User.IsAuthenticated
I think (from memory)
If you're using concatenate method then don't forget to trim the string if you're working with if else method.
If someone is having trouble with installing php-mbstring
package in ubuntu do following
sudo apt-get install libapache2-mod-php5
I've written a little proof of concept for Tim Downs proposal here with off-screen textarea. And here goes the code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script language="JavaScript">
$(document).ready(function()
{
var ctrlDown = false;
var ctrlKey = 17, vKey = 86, cKey = 67;
$(document).keydown(function(e)
{
if (e.keyCode == ctrlKey) ctrlDown = true;
}).keyup(function(e)
{
if (e.keyCode == ctrlKey) ctrlDown = false;
});
$(".capture-paste").keydown(function(e)
{
if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)){
$("#area").css("display","block");
$("#area").focus();
}
});
$(".capture-paste").keyup(function(e)
{
if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)){
$("#area").blur();
//do your sanitation check or whatever stuff here
$("#paste-output").text($("#area").val());
$("#area").val("");
$("#area").css("display","none");
}
});
});
</script>
</head>
<body class="capture-paste">
<div id="paste-output"></div>
<div>
<textarea id="area" style="display: none; position: absolute; left: -99em;"></textarea>
</div>
</body>
</html>
Just copy and paste the whole code into one html file and try to paste (using ctrl-v) text from clipboard anywhere on the document.
I've tested it in IE9 and new versions of Firefox, Chrome and Opera. Works quite well. Also it's good that one can use whatever key combination he prefers to triger this functionality. Of course don't forget to include jQuery sources.
Feel free to use this code and if you come with some improvements or problems please post them back. Also note that I'm no Javascript developer so I may have missed something (=>do your own testign).
You can also use -join
E.g.
$var = -join("Hello", " ", "world");
Would assign "Hello world" to $var.
So to output, in one line:
Write-Host (-join("Hello", " ", "world"))
I like @Thomas's answer, and I do some modifications.
features:
git config --get-regexp ^.
)# .gitconfig
[alias]
show-cmd = "!f() { \
sep="?" ;\
name=${1:-alias};\
echo -n -e '\\033[48;2;255;255;01m' ;\
echo -n -e '\\033[38;2;255;0;01m' ;\
echo "$name"; \
echo -n -e '\\033[m' ;\
git config --get-regexp ^$name\\..*$2+ | \
cut -c 1-40 | \
sed -e s/^$name.// \
-e s/\\ /\\ $(printf $sep)--\\>\\ / | \
column -t -s $(printf $sep) | \
sort -k 1 ;\
}; f"
git show-cmd
list aliasgit show-cmd "" st
list alias, and it should contain the string st
git show-cmd i18n
show i18n
settinggit show-cmd core editor
show core
setting, and it should contain editor
It's working fine on windows too
you can write the long script on .gitconfig
use the syntax as below:
[alias]
your-cmd = "!f() { \
\
}; f"
name=${1:-alias}
same as name = $1 if $1 else -alias
echo -n -e
(see more echo)
'\\033[38;2;255;0;01m'
(see more SGR parameters)
\\033[48;
: 48 means background color.\\033[38;2;255;0;0m
: 38 means fore color. 255;0;0 = Redcut -c 1-40
To avoid your command is too long, so take 40 char only.
sed -e 's/be_replace_string/new_string/'
replace string to new string. (if you want to put the special-char(such as space
, >
...) should add \\
as the prefix.
column -t -s $(printf $sep)
formats all lines into an evenly spaced column table.
sort -k 1
sorts all lines based on the value in the first column
I just found the solution and yea it was easier than I thought :)
so here is the solution:
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1¶m2=value2¶m3=value3";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}
it works like charm :)
Big O notation is useful because it's easy to work with and hides unnecessary complications and details (for some definition of unnecessary). One nice way of working out the complexity of divide and conquer algorithms is the tree method. Let's say you have a version of quicksort with the median procedure, so you split the array into perfectly balanced subarrays every time.
Now build a tree corresponding to all the arrays you work with. At the root you have the original array, the root has two children which are the subarrays. Repeat this until you have single element arrays at the bottom.
Since we can find the median in O(n) time and split the array in two parts in O(n) time, the work done at each node is O(k) where k is the size of the array. Each level of the tree contains (at most) the entire array so the work per level is O(n) (the sizes of the subarrays add up to n, and since we have O(k) per level we can add this up). There are only log(n) levels in the tree since each time we halve the input.
Therefore we can upper bound the amount of work by O(n*log(n)).
However, Big O hides some details which we sometimes can't ignore. Consider computing the Fibonacci sequence with
a=0;
b=1;
for (i = 0; i <n; i++) {
tmp = b;
b = a + b;
a = tmp;
}
and lets just assume the a and b are BigIntegers in Java or something that can handle arbitrarily large numbers. Most people would say this is an O(n) algorithm without flinching. The reasoning is that you have n iterations in the for loop and O(1) work in side the loop.
But Fibonacci numbers are large, the n-th Fibonacci number is exponential in n so just storing it will take on the order of n bytes. Performing addition with big integers will take O(n) amount of work. So the total amount of work done in this procedure is
1 + 2 + 3 + ... + n = n(n-1)/2 = O(n^2)
So this algorithm runs in quadradic time!
To go one step further, I assume you want to do something with these dtypes.
df.dtypes.to_dict()
comes in handy.
my_type = 'float64' #<---
dtypes = dataframe.dtypes.to_dict()
for col_nam, typ in dtypes.items():
if (typ != my_type): #<---
raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")
You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype
will succeed when .dtype==np.float64
.
In Django 3.0 auto_now_add
seems to work with auto_now
reg_date=models.DateField(auto_now=True,blank=True)
Use Projections to specify which columns you would like to return.
Example
SQL Query
SELECT user.id, user.name FROM user;
Hibernate Alternative
Criteria cr = session.createCriteria(User.class)
.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id")
.add(Projections.property("Name"), "Name"))
.setResultTransformer(Transformers.aliasToBean(User.class));
List<User> list = cr.list();
REST webservice: (http://localhost:8080/your-app/rest/data/post)
package com.yourorg.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/data")
public class JSONService {
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
String result = "Data post: "+data;
return Response.status(201).entity(result).build();
}
Client send a post:
package com.yourorg.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");
String input = "{\"message\":\"Hello\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my solution of converting string to sha1. It works well in my Android app:
private static String encryptPassword(String password)
{
String sha1 = "";
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
sha1 = byteToHex(crypt.digest());
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
return sha1;
}
private static String byteToHex(final byte[] hash)
{
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
Although this code is likely beyond the understanding of a novice, it can be done in one line using a regex with positive and negative look-aheads:
boolean ok =
password.matches("^(?=.*[A-Z])(?=.*[!@#$%^&*])(?=.*\\d)(?!.*(AND|NOT)).*[a-z].*");
The warning is due to you attempting to add an integer (int shift = 3
) to a character value. You can change the data type to char
if you want to avoid that.
A char
is 16 bits, an int
is 32.
char shift = 3;
// ...
eMessage[i] = (message[i] + shift) % (char)letters.length;
As an aside, you can simplify the following:
char[] message = {'o', 'n', 'c', 'e', 'u', 'p', 'o', 'n', 'a', 't', 'i', 'm', 'e'};
To:
char[] message = "onceuponatime".toCharArray();
You need to check one if you have two
if(rbMale.Checked)
{
}
else
{
}
You need to check all the checkboxes if more then two
if(rb1.Checked)
{
}
else if(rb2.Checked)
{
}
else if(rb3.Checked)
{
}
Wanted to add a solution for IE8 and below (as low as IE5.5 I think), which cannot use background-size
div{
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=
'/path/to/img.jpg', sizingMethod='scale');
}
head:
head - output the first part of files
head [OPTION]... [FILE]...
Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
-c, --bytes=[-]N
print the first N bytes of each file; with the leading '-', print all but the last N bytes of each file
Since Docker 1.5 you can now expose a range of ports to other linked containers using:
The Dockerfile EXPOSE command:
EXPOSE 7000-8000
or The Docker run command:
docker run --expose=7000-8000
Or instead you can publish a range of ports to the host machine via Docker run command:
docker run -p 7000-8000:7000-8000
public string GetDomainName<T>()
{
var dnAttribute = typeof(T).GetCustomAttributes(
typeof(DomainNameAttribute), true
).FirstOrDefault() as DomainNameAttribute;
if (dnAttribute != null)
{
return dnAttribute.Name;
}
return null;
}
UPDATE:
This method could be further generalized to work with any attribute:
public static class AttributeExtensions
{
public static TValue GetAttributeValue<TAttribute, TValue>(
this Type type,
Func<TAttribute, TValue> valueSelector)
where TAttribute : Attribute
{
var att = type.GetCustomAttributes(
typeof(TAttribute), true
).FirstOrDefault() as TAttribute;
if (att != null)
{
return valueSelector(att);
}
return default(TValue);
}
}
and use like this:
string name = typeof(MyClass)
.GetAttributeValue((DomainNameAttribute dna) => dna.Name);
could you please try below code
<c:forEach var="hash" items="${map['key']}">
<option><c:out value="${hash}"/></option>
</c:forEach>
In order to get the MySQL Database item in the Choose Data Source window, one should install the MySQL for Visual Studio package available here (the last version today is 1.2.6):
context
is where this
refers to in your iterator function. For example:
var person = {};
person.friends = {
name1: true,
name2: false,
name3: true,
name4: true
};
_.each(['name4', 'name2'], function(name){
// this refers to the friends property of the person object
alert(this[name]);
}, person.friends);
That’s a typo. You’ve accidently set "user.mail" with no "e". Fix it by setting "user.email" in the global configuration with
git config --global user.email "[email protected]"
Found solution here
(but not really...)
HTML 5's <video>
tag is protocol agnostic—it does not care. You place the protocol in the src
attribute as part of the URL. E.g.:
<video src="rtp://myserver.com/path/to/stream">
Your browser does not support the VIDEO tag and/or RTP streams.
</video>
or maybe
<video src="http://myserver.com:1935/path/to/stream/myPlaylist.m3u8">
Your browser does not support the VIDEO tag and/or RTP streams.
</video>
That said, the implementation of the <video>
tag is browser specific. Since it is early days for HTML 5, I expect frequently changing support (or lack of support).
From the W3C's HTML5 spec (The video element):
User agents may support any video and audio codecs and container formats
A very simple, non-technical rule-of-thumb would be that clustered indexes are usually used for your primary key (or, at least, a unique column) and that non-clustered are used for other situations (maybe a foreign key). Indeed, SQL Server will by default create a clustered index on your primary key column(s). As you will have learnt, the clustered index relates to the way data is physically sorted on disk, which means it's a good all-round choice for most situations.