This is caused by node v12.11.0 due to the way it deals regular location there two ways to solve this problem
Method I
You can downgrade to node v12.10.0 this will apply the correct way to deal with parsing error
Method II
You can correctly terminate the regular expression in you case by changing the file located a:
\node_modules\metro-config\src\defaults\blacklist.js
From:
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
To:
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
Other answers state how to pass in the command line variables but not how to access them, so if you do:
--extra-vars "version=1.23.45 other_variable=foo"
In your yml file you assign these to scoped ansible variables by doing something like:
vars:
my_version: "{{ version }}"
my_other_variable: {{ other_variable }}
An alternative to using command line args is to utilise environmental variables that are already defined within your session, you can reference these within your ansible yml files like this:
vars:
my_version: "{{ lookup('env', 'version') }}"
my_other_variable: {{ lookup('env', 'other_variable') }}
You can pass array of variables to the compact as an arguement eg:
return view('yourView', compact(['var1','var2',....'varN']));
in view: if var1 is an object you can use it something like this
@foreach($var1 as $singleVar1)
{{$singleVar1->property}}
@endforeach
incase of single variable you can simply
{{$var2}}
i have done this several times without any issues
$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /Applications/MAMP/htdocs/bashrushAPI/composer.phar
$ alias composer='/Applications/MAMP/htdocs/bashrushAPI/composer.phar'
$ composer --version
Composer version 1.7.2 2018-08-16 16:57:12
$ ls
CONTRIBUTING.md docker-compose.yml templates README.md logs tests composer.json phpunit.xml vendor composer.lock public composer.phar src
$ composer.phar update
Loading composer repositories with package information Updating dependencies (including require-dev) Nothing to install or update Generating autoload files
$ php composer.phar start
php -S localhost:8080 -t public [Thu Sep 27 03:16:11 2018] ::1:51177 [200]: / [Thu Sep 27 03:16:11 2018] ::1:51178 [404]: /favicon.ico - No such file or directory
Just use
composer require {package/packagename}
like
composer require phpmailer/phpmailer
if the package is not in the vendor folder.. composer installs it and if the package exists, composer update package to the latest version.
Is there a way to get it via $event->getComposer()->getRepositoryManager()->getAllPackages()
For deleting untracked files:
git clean -f
For deleting untracked directories as well, use:
git clean -f -d
For preventing any cardiac arrest, use
git clean -n -f -d
Just use the --verbose flag when execute phpunit.
$ phpunit --verbose -c phpunit.xml
The advantage of this method is that you don't need to change the test code, you can print strings, var_dump's o anything you wish always and it will be shown in the console only when verbose mode is set.
I hope this helps.
I find req.protocol works when I am using express (have not tested without but I suspect it works). using current node 0.10.22 with express 3.4.3
app.use(function(req,res,next) {
if (!/https/.test(req.protocol)){
res.redirect("https://" + req.headers.host + req.url);
} else {
return next();
}
});
factory_bot sounds like it will do what you are trying to achieve. You can define all the common attributes in the default definition and then override them at creation time. You can also pass an id to the factory:
Factory.define :theme do |t|
t.background_color '0x000000'
t.title_text_color '0x000000',
t.component_theme_color '0x000000'
t.carrier_select_color '0x000000'
t.label_text_color '0x000000',
t.join_upper_gradient '0x000000'
t.join_lower_gradient '0x000000'
t.join_text_color '0x000000',
t.cancel_link_color '0x000000'
t.border_color '0x000000'
t.carrier_text_color '0x000000'
t.public true
end
Factory(:theme, :id => 1, :name => "Lite", :background_color => '0xC7FFD5')
Factory(:theme, :id => 2, :name => "Metallic", :background_color => '0xC7FFD5')
Factory(:theme, :id => 3, :name => "Blues", :background_color => '0x0060EC')
When used with faker it can populate a database really quickly with associations without having to mess about with Fixtures (yuck).
I have code like this in a rake task.
100.times do
Factory(:company, :address => Factory(:address), :employees => [Factory(:employee)])
end
Just change the SqlCommand.CommandText
instead of creating a new SqlCommand
every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
Just with the above answer I hope it was the problem.
$_POST['search']
instead of $_post['search']
And again use LIKE '%$name%'
instead of LIKE '%{$name}%'
I asked in #machomebrew and learned that you can switch between versions using brew switch.
$ brew switch libfoo mycopy
to get version mycopy of libfoo.
You don't need to pass the parameter, you can get it using .attr()
method
$(function(){
$('elements-to-match').click(function(){
alert("The id is "+ $(this).attr("id") );
});
});
In my opinion this is a design flaw of pytz library. It should be more reliable to specify a timezone using the offset, e.g.
pytz.construct("UTC-07:00")
which gives you Canada/Pacific timezone.
$(".location table tbody tr td:first-child").addClass("black");
$(".location table tbody tr td:nth-child(2)").addClass("black");
To satisfy my need to insert a variable/alias/function into a Regular Expression, this is what I came up with:
oldre = /xx\(""\)/;
function newre(e){
return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};
String.prototype.replaceAll = this.replace(newre(oldre), "withThis");
where 'oldre' is the original regexp that I want to insert a variable, 'xx' is the placeholder for that variable/alias/function, and 'yy' is the actual variable name, alias, or function.
You can do the following:
<script type='text/javascript'>
document.body.onclick(function(){
var myVariable = <?php echo(json_encode($myVariable)); ?>;
};
</script>
The only thing that worked for me was to clone the repo using the HTTPS link instead of the SSH link.
another way would be to use dplyr
package:
x = c(1,1,2,3,4,4,4)
dplyr::distinct(as.data.frame(x))
According to my interpretation of the implementation of unicode-escape
and the unicode repr
in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string)
and unicode_string.encode('unicode-escape')
is the inclusion of wrapping quotes and escaping whichever quote was used.
They are both driven by the same function, unicodeescape_string
. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.
Above Solutions will only convert dictionary into string but you can't convert back that string to dictionary. For that it is the better way.
Convert to String
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:yourDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@",myString);
Convert Back to Dictionary
NSError * err;
NSData *data =[myString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * response;
if(data!=nil){
response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}
CustomFragment dialog = (CustomDataFragment) getSupportFragmentManager().findFragmentByTag("Fragment_TAG");
if (dialog != null) {
dialog.dismiss();
}
I tried all of the above and if that doesn't work for you try the below CSS resolved the issue for me. Which just tells the browsers to not add any padding or margin.
* {
padding:0px;
margin:0px;
}
Please try this:
byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);
This is default by iOS7 design. try to do the below:
[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
You can set the 'Separator Inset' from the storyboard:
Please try the following:
import re
name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]
# Match names.
for element in name:
m = re.match("(^[A-Z]\d[A-Z]\d)", element)
if m:
print(m.groups())
you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM
1 10 * * * php -f /var/www/package/index.php controller function
30 14 * * * php -f /var/www/package/index.php controller function
but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30
.
30 10,14 * * * php -f /var/www/package/index.php controller function
The simplest approach is to use a multitouch JavaScript library like Hammer.js. Then you can write code like:
canvas
.hammer({prevent_default: true})
.bind('doubletap', function(e) { // And double click
// Zoom-in
})
.bind('dragstart', function(e) { // And mousedown
// Get ready to drag
})
.bind('drag', function(e) { // And mousemove when mousedown
// Pan the image
})
.bind('dragend', function(e) { // And mouseup
// Finish the drag
});
And you can keep going. It supports tap, double tap, swipe, hold, transform (i.e., pinch) and drag. The touch events also fire when equivalent mouse actions happen, so you don't need to write two sets of event handlers. Oh, and you need the jQuery plugin if you want to be able to write in the jQueryish way as I did.
On the face of it, it looks okay - if you call eraseCookie()
on each cookie that is read from document.cookie
, then all of your cookies will be gone.
Try this:
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
eraseCookie(cookies[i].split("=")[0]);
All of this with the following caveat:
This is what worked for me:
Enter the command:
osql -S localhost\SQLEXPRESS -E
(or change localhost to whatever your PC is called).
At the prompt type the following commands:
CREATE LOGIN my_Login_here WITH PASSWORD = 'my_Password_here'
go
sp_addsrvrolemember 'my_Login_here', 'sysadmin'
go
quit
Stop the "SQL Server (SQLEXPRESS)" service.
Remove the "-m" from the Start parameters field (if still there).
Start the service.
In Management Studio, use the login and password you just created. This should give it admin permission.
UIButton responds to addTarget:action:forControlEvents: since it inherits from UIControl. But it does not respond to addTarget:action:withObject:forControlEvents:
see reference for the method and for UIButton
You could extend UIButton with a category to implement that method, thought.
here is another solution
Container(
height: MediaQuery.of(context).size.height * 0.10,
width: MediaQuery.of(context).size.width,
child: ButtonTheme(
minWidth: MediaQuery.of(context).size.width * 0.75,
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(25.0),
side: BorderSide(color: Colors.blue)),
onPressed: () async {
// do something
},
color: Colors.red[900],
textColor: Colors.white,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Button Text,
style: TextStyle(fontSize: 24)),
),
),
),
),
IPython
has a magic command %pwd
to get the present working directory. It can be used in following way:
from IPython.terminal.embed import InteractiveShellEmbed
ip_shell = InteractiveShellEmbed()
present_working_directory = ip_shell.magic("%pwd")
On IPython Jupyter Notebook %pwd
can be used directly as following:
present_working_directory = %pwd
Into Preferences > Settings - Users
File : Preferences.sublime-settings
Write this :
"show_encoding" : true,
It's explain on the release note date 17 December 2013. Build 3059. Official site Sublime Text 3
Try this
while (true) { // loops forever until break
try { // checks code for exceptions
WebElement ele=
(WebElement)wait.until(ExpectedConditions.elementToBeClickable((By.xpath(Xpath))));
break; // if no exceptions breaks out of loop
}
catch (org.openqa.selenium.StaleElementReferenceException e1) {
Thread.sleep(3000); // you can set your value here maybe 2 secs
continue; // continues to loop if exception is found
}
}
ListViewItem.IsSelected = true;
ListViewItem.Focus();
Other type of format :
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
For the listed three conditions only, these expressions might work also:
^\d{5}[-\s]?(?:\d{4})?$
^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
^\[0-9]{5}[-\s]?(?:\d{4})?$
^\d{5}[-\s]?(?:[0-9]{4})?$
If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:
123451234
12345 1234
12345 1234
this expression for instance would be a secondary option with less constraints:
^\d{5}([-]|\s*)?(\d{4})?$
jex.im visualizes regular expressions:
const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;_x000D_
const str = `12345_x000D_
12345-6789_x000D_
12345 1234_x000D_
123451234_x000D_
12345 1234_x000D_
12345 1234_x000D_
1234512341_x000D_
123451`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
// This is necessary to avoid infinite loops with zero-width matches_x000D_
if (m.index === regex.lastIndex) {_x000D_
regex.lastIndex++;_x000D_
}_x000D_
_x000D_
// The result can be accessed through the `m`-variable._x000D_
m.forEach((match, groupIndex) => {_x000D_
console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
});_x000D_
}
_x000D_
Prefix the string with the +
operator.
console.log(+'a') // NaN
console.log(+'1') // 1
console.log(+1) // 1
Your datatype for @location nchar(20)
should be @location nvarchar(20)
, since nChar has a fixed length (filled with Spaces).
If Location is nchar too you will have to convert it:
... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...
To enable nullable parameters with and AND
condition just use IsNull or Coalesce for comparison, which is not needed in your example using OR
.
e.g. if you would like to compare for Location AND Date and Time.
@location nchar(20),
@time time,
@date date
as
select DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from Vechile, DonationsTruck
where Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+IsNull(@location,Location)+'%')) and [Date]=IsNUll(@date,date) and [Time] = IsNull(@time,Time))
Merge them in two steps, df1
and df2
first, and then the result of that to df3
.
In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])
I dropped year from df3 since you don't need it for the last join.
In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
how='left', on=['Week', 'Colour'])
In [40]: df
Out[40]:
Year Week Colour Val1 Val2 Val3
0 2014 A Red 50 NaN NaN
1 2014 B Red 60 NaN 60
2 2014 B Black 70 100 10
3 2014 C Red 10 20 NaN
4 2014 D Green 20 NaN 20
[5 rows x 6 columns]
This command:
git ls-tree --full-tree -r --name-only HEAD
lists all of the already committed files being tracked by your git repo.
O(1) means the time to access something is independent of the number of items in the collection.
O(N) would mean the time to access an item is a proportional to the number (N) of items in the collection.
Write unit tests. You can test a lot of things in Cocoa that might be harder in other frameworks. For example, with UI code, you can generally verify that things are connected as they should be and trust that they'll work when used. And you can set up state & invoke delegate methods easily to test them.
You also don't have public vs. protected vs. private method visibility getting in the way of writing tests for your internals.
Fun problem! I'm going to have to rename a lot of apps soon, so I did a dry run.
This method allows progress to be made in atomic steps, to minimise disruption for other developers working on the app you're renaming.
See the link at the bottom of this answer for working example code.
name
and label
to defaults).INSTALLED_APPS
.db_table
to the current value.db_table
was "always" explicitly defined.Change the app label:
label
in app config to new app name.<app_label>/<model_name>_<suffix>.html
)Run raw SQL to fix migrations and content_types
app (unfortunately, some raw SQL is unavoidable). You can not run this in a migration.
UPDATE django_migrations
SET app = 'catalogue'
WHERE app = 'shop';
UPDATE django_content_type
SET app_label = 'catalogue'
WHERE app_label = 'shop';
Ensure no migrations are required (checks previous step).
db_table
.makemigrations
so django can rename the table "to the default".name
.INSTALLED_APPS
references the app config.INSTALLED_APPS
.Example solution: I've created app-rename-example, an example project where you can see how I renamed an app, one commit at a time.
The example uses Python 2.7 and Django 1.8, but I'm confident the same process will work on at least Python 3.6 and Django 2.1.
This will work if you wish to simply return an integer:
DECLARE @ResultForPos INT
EXEC @ResultForPos = storedprocedureName 'InputParameter'
SELECT @ResultForPos
Possibly not cross browser but I managed get this: http://jsfiddle.net/QexkH/
basically it requires a fixed height header and footer. and it absolute positions the table.
table {
width: 50%;
height: 50%;
border-spacing: 0;
position:absolute;
}
td {
border: 1px solid black;
}
#content {
position:absolute;
width:100%;
left:0px;
top:20px;
bottom:20px;
overflow: hidden;
}
Use the DateTime.ToUniversalTime
method.
How about this?
for item in mylist:
if item in checklist:
pass
else:
# do something
print item
int screenResolution = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(""+screenResolution);
Following @Michelle Tilley solution, apparently it didn't work for me at first. Not sure why, maybe I am using chrome and different version of node. After did some minor tweaks, it is working for me now.
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
In case someone facing similar issue as mine, this might be helpful.
Some time when we use Environ()
function we may get the Library or property not found error. Use VBA.Environ()
or VBA.Environ$()
to avoid the error.
For Windows check the StackWalk64() API (also on 32bit Windows). For UNIX you should use the OS' native way to do it, or fallback to glibc's backtrace(), if availabe.
Note however that taking a Stacktrace in native code is rarely a good idea - not because it is not possible, but because you're usally trying to achieve the wrong thing.
Most of the time people try to get a stacktrace in, say, an exceptional circumstance, like when an exception is caught, an assert fails or - worst and most wrong of them all - when you get a fatal "exception" or signal like a segmentation violation.
Considering the last issue, most of the APIs will require you to explicitly allocate memory or may do it internally. Doing so in the fragile state in which your program may be currently in, may acutally make things even worse. For example, the crash report (or coredump) will not reflect the actual cause of the problem, but your failed attempt to handle it).
I assume you're trying to achive that fatal-error-handling thing, as most people seem to try that when it comes to getting a stacktrace. If so, I would rely on the debugger (during development) and letting the process coredump in production (or mini-dump on windows). Together with proper symbol-management, you should have no trouble figuring the causing instruction post-mortem.
Alternatively you can create a new scope and pass through params via the scope option
var scope = $rootScope.$new();
scope.params = {editId: $scope.editId};
$modal.open({
scope: scope,
templateUrl: 'template.html',
controller: 'Controller',
});
In your modal controller pass in $scope, you then do not need to pass in and itemsProvider or what ever resolve you named it
modalController = function($scope) {
console.log($scope.params)
}
You can use the logical 'OR' operator in place of the Elvis operator:
For example displayname = user.name || "Anonymous"
.
But Javascript currently doesn't have the other functionality. I'd recommend looking at CoffeeScript if you want an alternative syntax. It has some shorthand that is similar to what you are looking for.
For example The Existential Operator
zip = lottery.drawWinner?().address?.zipcode
Function shortcuts
()-> // equivalent to function(){}
Sexy function calling
func 'arg1','arg2' // equivalent to func('arg1','arg2')
There is also multiline comments and classes. Obviously you have to compile this to javascript or insert into the page as <script type='text/coffeescript>'
but it adds a lot of functionality :) . Using <script type='text/coffeescript'>
is really only intended for development and not production.
This is an old post, but it may help some people searching on this error to try setting "Enable 32-Bit Applications" to True for the app pool. That is what resolved the error for me. I came upon this solution by reading some the comments to @beckelmw's answer.
Check this out:
SELECT TABLE_SCHEMA ,
TABLE_NAME ,
COLUMN_NAME ,
ORDINAL_POSITION ,
COLUMN_DEFAULT ,
DATA_TYPE ,
CHARACTER_MAXIMUM_LENGTH ,
NUMERIC_PRECISION ,
NUMERIC_PRECISION_RADIX ,
NUMERIC_SCALE ,
DATETIME_PRECISION
FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA in ('dbo','meta')
and table_name in (select name from sys.tables)
order by TABLE_SCHEMA , TABLE_NAME ,ORDINAL_POSITION
you can give some id to the columns and name it uniquely.
It's not true SOAPpy does not work with Python 2.5 - it works, although it's very simple and really, really basic. If you want to talk to any more complicated webservice, ZSI is your only friend.
The really useful demo I found is at http://www.ebi.ac.uk/Tools/webservices/tutorials/python - this really helped me to understand how ZSI works.
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<String> ls =new ArrayList<String>();
for(product cj:cities.getList()) {
ls.add(cj);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", cj.id);
formDetailsJson.put("name", cj.name);
jsonArray.put(formDetailsJson);
}
responseDetailsJson.put("Cities", jsonArray);
return responseDetailsJson;
I found that I needed to group by the month and year so neither of the above worked for me. Instead I used date_format
SELECT date
FROM blog
GROUP BY DATE_FORMAT(date, "%m-%y")
ORDER BY YEAR(date) DESC, MONTH(date) DESC
I solved this problem without deleting any keys. Here's how:
You may also want to look at Async Http Client.
With the new ValueTuple
from C# 7 (VS 2017 and above), there is a new solution:
List<(int,string)> mylist= new List<(int,string)>();
Which creates a list of ValueTuple type. If you're targeting .Net Framework 4.7+ or .Net Core, it's native, otherwise you have to get the ValueTuple package from nuget.
It's a struct opposing to Tuple
, which is a class. It also has the advantage over the Tuple
class that you could create a named tuple, like this:
var mylist = new List<(int myInt, string myString)>();
That way you can access like mylist[0].myInt
and mylist[0].myString
The unix setup should be like the following:
0 */3 * * * sh cron/update_old_citations.sh
good reference for how to set various settings in cron at: http://www.thegeekstuff.com/2011/07/cron-every-5-minutes/
You can use this (or any variant):
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Also, I'd recommend using File.separator
or /
instead of \\
to make it compliant across multiple OS, question/answer on this available here.
Since you're not sure how to temporarily store files, take a look at ArrayList
:
List<File> files = new ArrayList();
files.add(foundFile);
To move a List
of files into a single directory:
List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
Files.copy(file.toPath(),
(new File(path + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
You should inject Router in your constructor like this;
constructor(private router: Router) { }
then you can do this anywhere you want;
this.router.navigate(['/product-list']);
It’s because you tried to update a table without a WHERE that uses a KEY column.
The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :
SET SQL_SAFE_UPDATES=0;
Or
close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .
BTW you can use TRUNCATE TABLE tablename;
to delete all the records .
Generally Server JDK version will be lower than the deployed application (built with higher jdk version)
If you want to take control of /usr/bin/
You will need to reboot your system:
Right after the boot sound, Hold down Command-R to boot into the Recovery System
Click the Utilities menu and select Terminal
Type csrutil disable and press return
Click the ? menu and select Restart
Once you have committed your changes, make sure to re-enable SIP! It does a lot to protect your system. (Same steps as above except type: csrutil enable)
A possibly simpler alternative to editing the ssh config file (as suggested in all other answers), is to configure an individual repository to use a different (e.g. non-default) ssh key.
Inside the repository for which you want to use a different key, run:
git config core.sshCommand 'ssh -i ~/.ssh/id_rsa_anotheraccount'
If your key is passhprase-protected and you don't want to type your password every time, you have to add it to the ssh-agent. Here's how to do it for ubuntu and here for macOS.
It should also be possible to scale this approach to multiple repositories using global git config and conditional includes (see example).
I saw the answers here and although helpful, they weren't exactly what I wanted since I had to alter a lot of my code.
What worked out for me, was doing something like this:
function isSession(selector) {
//line added for the var that will have the result
var result = false;
$.ajax({
type: "POST",
url: '/order.html',
data: ({ issession : 1, selector: selector }),
dataType: "html",
//line added to get ajax response in sync
async: false,
success: function(data) {
//line added to save ajax response in var result
result = data;
},
error: function() {
alert('Error occured');
}
});
//line added to return ajax response
return result;
}
Hope helps someone
anakin
Just put window.open(website url)
, it works every time.
Yes, you can do this by creating a DoubleStream
from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:
double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]
If you want to filter a reference array that is not an Object[]
you will need to use the toArray
method which takes an IntFunction
to get an array of the original type as the result:
String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);
Here is a function that will flatten an object or array. Use this only if you are sure your keys are unique. If you have keys with the same name they will be overwritten. You will need to place this in a class and replace "Functions" with the name of your class. Enjoy...
function flatten($array, $preserve_keys=1, &$out = array(), $isobject=0) {
# Flatten a multidimensional array to one dimension, optionally preserving keys.
#
# $array - the array to flatten
# $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
# $out - internal use argument for recursion
# $isobject - is internally set in order to remember if we're using an object or array
if(is_array($array) || $isobject==1)
foreach($array as $key => $child)
if(is_array($child))
$out = Functions::flatten($child, $preserve_keys, $out, 1); // replace "Functions" with the name of your class
elseif($preserve_keys + is_string($key) > 1)
$out[$key] = $child;
else
$out[] = $child;
if(is_object($array) || $isobject==2)
if(!is_object($out)){$out = new stdClass();}
foreach($array as $key => $child)
if(is_object($child))
$out = Functions::flatten($child, $preserve_keys, $out, 2); // replace "Functions" with the name of your class
elseif($preserve_keys + is_string($key) > 1)
$out->$key = $child;
else
$out = $child;
return $out;
}
tail -f /var/log/syslog | grep process_name
where process_name
is the name of the process we are interested in
You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do
pip install -U scikit-learn
If you are on windows you might want to check out these pages.
For a lambda-avoiding method, first define your own function:
def MyFn(a):
return a[1]
then:
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=MyFn)
I know it's a bit too late but how about this?
var obj = function(){
var pr = "private";
var prt = Object.getPrototypeOf(this);
if(!prt.hasOwnProperty("showPrivate")){
prt.showPrivate = function(){
console.log(pr);
}
}
}
var i = new obj();
i.showPrivate();
console.log(i.hasOwnProperty("pr"));
If you need to scroll to a point of an element. You can use Jquery function to scroll it up/down.
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 'slow');
I had the same problem with eclipse, the WA solution was to copy the libs to WEB-INF/lib
document.write()
will only work while the page is being originally parsed and the DOM is being created. Once the browser gets to the closing </body>
tag and the DOM is ready, you can't use document.write()
anymore.
I wouldn't say using document.write()
is correct or incorrect, it just depends on your situation. In some cases you just need to have document.write()
to accomplish the task. Look at how Google analytics gets injected into most websites.
After DOM ready, you have two ways to insert dynamic HTML (assuming we are going to insert new HTML into <div id="node-id"></div>
):
Using innerHTML on a node:
var node = document.getElementById('node-id');
node.innerHTML('<p>some dynamic html</p>');
Using DOM methods:
var node = document.getElementById('node-id');
var newNode = document.createElement('p');
newNode.appendChild(document.createTextNode('some dynamic html'));
node.appendChild(newNode);
Using the DOM API methods might be the purist way to do stuff, but innerHTML
has been proven to be much faster and is used under the hood in JavaScript libraries such as jQuery.
Note: The <script>
will have to be inside your <body>
tag for this to work.
Is there a user account entry in the DB for root@localhost? In MySQL you can set different user account permissions by host. There could be several different accounts with the same name combined with the host they are connecting from. The most common are [email protected] and root@localhost. These can have different passwords and permissions. Make sure root@localhost exist and has the settings you expect.
I am willing to bet, based on your explanation, that this is the problem. Connecting from another PC uses a different account than root@localhost and the command line I think connects using [email protected].
In your Case you can write the following jquery code:
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").attr("readonly", false);
}
else{
$("#no_of_staff").attr("readonly", true);
}
});
});
Here is the Fiddle: http://jsfiddle.net/P4QWx/3/
You can enable the CURLOPT_VERBOSE
option:
curl_setopt($curlhandle, CURLOPT_VERBOSE, true);
When CURLOPT_VERBOSE
is set, output is written to STDERR or the file specified using CURLOPT_STDERR
. The output is very informative.
You can also use tcpdump or wireshark to watch the network traffic.
Use LISTAGG function,
ex. SELECT LISTAGG(colmn) FROM table_name;
In my case with the given code, I was able to parse the value of the passed parameter in this way.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
//url/par1=val1&par2=val2
let val1= req.body.par1;
let val2 = req.body.par2;
_x000D_
I just use 'new-password'
instead 'off'
on autocomplete.
and I also have try using this code and works (at least on my end), I use WP and GravityForm for your information
$('input').attr('autocomplete','new-password');
When I faced a similar issue, the only thing that seemed to work was:
I have found Adobe Dreamweaver to be quite good at that. However, it's not free.
use flask 0.9 instead
use the following commands
sudo pip uninstall flask
sudo pip install flask==0.9
SQL self-join simply is a normal join which is used to join a table to itself.
Example:
Select *
FROM Table t1, Table t2
WHERE t1.Id = t2.ID
These examples also work in bash no need to use sed:
#!/bin/bash
MYVAR=ho02123ware38384you443d34o3434ingtod38384day
MYVAR=${MYVAR//[a-zA-Z]/X}
echo ${MYVAR//[0-9]/N}
you can also use the character class bracket expressions
#!/bin/bash
MYVAR=ho02123ware38384you443d34o3434ingtod38384day
MYVAR=${MYVAR//[[:alpha:]]/X}
echo ${MYVAR//[[:digit:]]/N}
output
XXNNNNNXXXXNNNNNXXXNNNXNNXNNNNXXXXXXNNNNNXXX
What @Lanaru wanted to know however, if I understand the question correctly, is why the "full" or PCRE extensions \s\S\w\W\d\D
etc don't work as supported in php ruby python etc. These extensions are from Perl-compatible regular expressions (PCRE) and may not be compatible with other forms of shell based regular expressions.
These don't work:
#!/bin/bash
hello=ho02123ware38384you443d34o3434ingtod38384day
echo ${hello//\d/}
#!/bin/bash
hello=ho02123ware38384you443d34o3434ingtod38384day
echo $hello | sed 's/\d//g'
output with all literal "d" characters removed
ho02123ware38384you44334o3434ingto38384ay
but the following does work as expected
#!/bin/bash
hello=ho02123ware38384you443d34o3434ingtod38384day
echo $hello | perl -pe 's/\d//g'
output
howareyoudoingtodday
Hope that clarifies things a bit more but if you are not confused yet why don't you try this on Mac OS X which has the REG_ENHANCED flag enabled:
#!/bin/bash
MYVAR=ho02123ware38384you443d34o3434ingtod38384day;
echo $MYVAR | grep -o -E '\d'
On most flavours of *nix you will only see the following output:
d
d
d
nJoy!
Create a PHP file outside your document root. If your document root is
/var/www/html/
create the a file named minify.php one level above it
/var/www/minify.php
Copy paste the following PHP code into it
<?php function minify_output($buffer){ $search = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s'); $replace = array('>','<','\\1'); if (preg_match("/\<html/i",$buffer) == 1 && preg_match("/\<\/html\>/i",$buffer) == 1) { $buffer = preg_replace($search, $replace, $buffer); } return $buffer; } ob_start("minify_output");?>
Save the minify.php file and open the php.ini file. If it is a dedicated server/VPS search for the following option, on shared hosting with custom php.ini add it.
auto_prepend_file = /var/www/minify.php
Reference: http://websistent.com/how-to-use-php-to-minify-html-output/
Total number of results
$this->db->count_all_results('table name');
How's this for a work around (using an actual table)?
table {
border-collapse: collapse;
}
tr.row {
border-bottom: solid white 30px; /* change "white" to your background color */
}
It's not as dynamic, since you have to explicitly set the color of the border (unless there's a way around that too), but this is something I'm experimenting with on a project of my own.
Edit to include comments regarding transparent
:
tr.row {
border-bottom: 30px solid transparent;
}
Tuples will be (are) in .Net 4.0 Until then, you can also use a
Dictionary<key1, Dictionary<key2, TypeObject>>
or, creating a custom collection class to represent this...
public class TwoKeyDictionary<K1, K2, T>:
Dictionary<K1, Dictionary<K2, T>> { }
or, with three keys...
public class ThreeKeyDictionary<K1, K2, K3, T> :
Dictionary<K1, Dictionary<K2, Dictionary<K3, T>>> { }
you don't need this code
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
?>
Instead, you can check whether the form is submitted by checking the post variables using isset
.
here goes the code
if(isset($_POST)){
echo "hello ".$_POST['studentname'];
}
click here for the php manual for isset
First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.
Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.
There are various methods to do this depending on your DBMS:
SQL-Server 2008 and later:
SELECT CAST(CURRENT_TIMESTAMP AS DATE)
SQL-Server 2005 and Earlier
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SQLite
SELECT DATE(NOW())
Oracle
SELECT TRUNC(CURRENT_TIMESTAMP)
Postgresql
SELECT CURRENT_TIMESTAMP::DATE
If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.
Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.
If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)
) before sending to report services and handle it as described above.
Complete example of encrypting/Decrypting a huge video without throwing Java OutOfMemoryException
and using Java SecureRandom
for Initialization Vector generation. Also depicted storing key bytes to database and then reconstructing same key from those bytes.
According to the Java Virtual Machine Specification (Java SE 8), JVM §4.3.2. Field Descriptors:
FieldType term | Type | Interpretation -------------- | --------- | -------------- L ClassName ; | reference | an instance of class ClassName [ | reference | one array dimension ... | ... | ...
the expression [Ljava.lang.String;@45a877
means this is an array ( [
) of class java.lang.String ( Ljava.lang.String;
). And @45a877
is the address where the String object is stored in memory.
It is same as above answers, but is simple in steps
c:\SRC\folder1
c:\SRC\folder2
c:\SRC\folder3
c:\SRC\folder4
to copy all above folders to c:\DST\ except folder1 and folder2.
Step1: create a file c:\list.txt with below content, one folder name per one line
folder1\
folder2\
Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt
If you don't want your data to be seen by the user, use a PHP session.
Data in a post request is still accessible (and manipulable) by the user.
Checkout this tutorial on PHP Sessions.
try Array.prototype.some()
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
You are inserting not Updating the result. You can define the name column in primary column or set it is unique.
Below are a few extra steps on a fresh Mac that some people might need. This adds a little to @jnovack's excellent answer.
Update: A few other notes when setting this up:
Make sure your admin user has a password. A blank password won't work when trying to enable a root user.
System Preferences > Users and Groups > (select user) > Change password
Then to enable root, run dsenableroot
in a terminal:
$ dsenableroot
username = mac_admin_user
user password:
root password:
verify root password:
dsenableroot:: ***Successfully enabled root user.
Type in the admin user's password, then the new enabled root password twice.
Next type:
sudo gcc
or
sudo make
It will respond with something like the following:
WARNING: Improper use of the sudo command could lead to data loss
or the deletion of important system files. Please double-check your
typing when using sudo. Type "man sudo" for more information.
To proceed, enter your password, or type Ctrl-C to abort.
Password:
You have not agreed to the Xcode license agreements. You must agree to
both license agreements below in order to use Xcode.
Press enter when it prompts to show you the license agreement.
Hit the Enter key to view the license agreements at
'/Applications/Xcode.app/Contents/Resources/English.lproj/License.rtf'
IMPORTANT: BY USING THIS SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE
FOLLOWING APPLE TERMS:
//...
Press q
to exit the license agreement view.
By typing 'agree' you are agreeing to the terms of the software license
agreements. Type 'print' to print them or anything else to cancel,
[agree, print, cancel]
Type agree
. And then it will end with:
clang: error: no input files
Which basically means that you didn't give make
or gcc
any input files.
Here is what the check looked like:
$ xcode-select -p
/Applications/Xcode.app/Contents/Developer
With Mavericks, it is a little different now.
When the tools were NOT found, this is what the command pkgutil
command returned:
$ pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
To install the command line tools, this works nicely from the Terminal, with a nice gui and everything.
$ xcode-select --install
http://macops.ca/installing-command-line-tools-automatically-on-mavericks/
When they were found, this is what the pkgutil
command returned:
$ pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
package-id: com.apple.pkg.CLTools_Executables
version: 5.0.1.0.1.1382131676
volume: /
location: /
install-time: 1384149984
groups: com.apple.FindSystemFiles.pkg-group com.apple.DevToolsBoth.pkg-group com.apple.DevToolsNonRelocatableShared.pkg-group
This command returned the same before and after the install.
$ pkgutil --pkg-info=com.apple.pkg.DeveloperToolsCLI
No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.
Also I had the component for the CLT selected and installed in xcode's downloads section before, but it seems like it didn't make it to the terminal...
Hope that helps.
Try something like:
Add to html:
<link id="shortcutIcon" rel="shortcut icon" type="image/x-icon">
<link id="icon" rel="icon" type="image/x-icon">
Add minified script after tag:
<script type="text/javascript">
(function(b,c,d,a){a=c+d+b,document.getElementById('shortcutIcon').href=a,document.getElementById('icon').href=a;}(Math.random()*100,(document.querySelector('base')||{}).href,'/assets/images/favicon.ico?v='));
</script>
where
Before test clear history: (ctr + shfit + del)
A literally insane answer, but if you have some kind of replication system set up (for a system with a billion rows, I hope you do), you can use a rough-estimator (like MAX(pk)
), divide that value by the number of slaves you have, run several queries in parallel.
For the most part, you'd partition the queries across slaves based on the best key (or the primary key I guess), in such a way (we're going to use 250000000 as our Rows / Slaves):
-- First slave
SELECT COUNT(pk) FROM t WHERE pk < 250000000
-- Ith slave where 2 <= I <= N - 1
SELECT COUNT(pk) FROM t WHERE pk >= I*250000000 and pk < (I+1)*250000000
-- Last slave
SELECT COUNT(pk) FROM t WHERE pk > (N-1)*250000000
But you need SQL only. What a bust. Ok, so let's say you're a sadomasochist. On the master (or closest slave) you'd most likely need to create a table for this:
CREATE TABLE counter_table (minpk integer, maxpk integer, cnt integer, slaveid integer)
So instead of only having the selects running in your slaves, you'd have to do an insert, akin to this:
INSERT INTO counter_table VALUES (I*25000000, (I+1)*250000000, (SELECT COUNT(pk) FROM ... ), @@SLAVE_ID)
You may run into issues with slaves writing to a table on master. You may need to get even more sadis- I mean, creative:
-- A table per slave!
INSERT INTO counter_table_slave_I VALUES (...)
You should in the end have a slave that exists last in the path traversed by the replication graph, relative to the first slave. That slave should now have all other counter values, and should have its own values. But by the time you've finished, there probably are rows added, so you'd have to insert another one compensating for the recorded max pk in your counter_table and the current max pk.
At that point, you'd have to do an aggregate function to figure out what the total rows are, but that's easier since you'd be running it on at most the "number of slaves you have and change" rows.
If you're in the situation where you have separate tables in the slaves, you can UNION
to get all the rows you need.
SELECT SUM(cnt) FROM (
SELECT * FROM counter_table_slave_1
UNION
SELECT * FROM counter_table_slave_2
UNION
...
)
Or you know, be a bit less insane and migrate your data to a distributed processing system, or maybe use a Data Warehousing solution (which will give you awesome data crunching in the future too).
Do note, this does depend on how well your replication is set up. Since the primary bottleneck will most likely be persistent storage, if you have cruddy storage or poorly segregated data stores with heavy neighbor noise, this will probably run you slower than just waiting for a single SELECT COUNT(*) ...
But if you have good replication, then your speed gains should be directly related to the number or slaves. In fact, if it takes 10 minutes to run the counting query alone, and you have 8 slaves, you'd cut your time to less than a couple minutes. Maybe an hour to iron out the details of this solution.
Of course, you'd never really get an amazingly accurate answer since this distributed solving introduces a bit of time where rows can be deleted and inserted, but you can try to get a distributed lock of rows at the same instance and get a precise count of the rows in the table for a particular moment in time.
Actually, this seems impossible, since you're basically stuck with an SQL-only solution, and I don't think you're provided a mechanism to run a sharded and locked query across multiple slaves, instantly. Maybe if you had control of the replication log file... which means you'd literally be spinning up slaves for this purpose, which is no doubt slower than just running the count query on a single machine anyway.
So there's my two 2013 pennies.
Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply
method as well as lambda
and converting datetime format. Line if x != '' else x
will take care of all empty spaces or nulls accordingly.
df['Date'] = df['Date'].fillna('')
df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)
To add to the response from @Anish, if you are having issues with not seeing the text when exporting the SVG to an image, you can create a recursive function to loop through the children of the SVGDocument, try to cast it to a SvgText if possible (add your own error checking) and set the font family and style.
foreach(var child in svgDocument.Children)
{
SetFont(child);
}
public void SetFont(SvgElement element)
{
foreach(var child in element.Children)
{
SetFont(child); //Call this function again with the child, this will loop
//until the element has no more children
}
try
{
var svgText = (SvgText)parent; //try to cast the element as a SvgText
//if it succeeds you can modify the font
svgText.Font = new Font("Arial", 12.0f);
svgText.FontSize = new SvgUnit(12.0f);
}
catch
{
}
}
Let me know if there are questions.
The other answers here have demonstrated how to define structs inside of classes. There’s another way to do this, and that’s to declare the struct inside the class, but define it outside. This can be useful, for example, if the struct is decently complex and likely to be used standalone in a way that would benefit from being described in detail somewhere else.
The syntax for this is as follows:
class Container {
...
struct Inner; // Declare, but not define, the struct.
...
};
struct Container::Inner {
/* Define the struct here. */
};
You more commonly would see this in the context of defining nested classes rather than structs (a common example would be defining an iterator type for a collection class), but I thought for completeness it would be worth showing off here.
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
Simply, static functions function independently of the class where they belong.
$this means, this is an object of this class. It does not apply to static functions.
class test {
public function sayHi($hi = "Hi") {
$this->hi = $hi;
return $this->hi;
}
}
class test1 {
public static function sayHi($hi) {
$hi = "Hi";
return $hi;
}
}
// Test
$mytest = new test();
print $mytest->sayHi('hello'); // returns 'hello'
print test1::sayHi('hello'); // returns 'Hi'
This is a good way to copy a file in one line of code using streams:
var fs = require('fs');
fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));
In Node.js v8.5.0, copyFile was added.
const fs = require('fs');
// File destination.txt will be created or overwritten by default.
fs.copyFile('source.txt', 'destination.txt', (err) => {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
});
with below code you can listen SpaceBar pressing , in middle of your console execution and pause until another key is pressed and also listen for EscapeKey for breaking the main loop
static ConsoleKeyInfo cki = new ConsoleKeyInfo();
while(true) {
if (WaitOrBreak()) break;
//your main code
}
private static bool WaitOrBreak(){
if (Console.KeyAvailable) cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Spacebar)
{
Console.Write("waiting..");
while (Console.KeyAvailable == false)
{
Thread.Sleep(250);Console.Write(".");
}
Console.WriteLine();
Console.ReadKey(true);
cki = new ConsoleKeyInfo();
}
if (cki.Key == ConsoleKey.Escape) return true;
return false;
}
Try this one it will work
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.add("Nokia");
adapter.notifyDataSetChanged();
}
}
Since it is basically a javascript shell, you can also use toArray()
:
db.collection.find().toArray()
However, this will print all the documents of the collection unlike pretty()
that will allow you to iterate.
Refer: http://docs.mongodb.org/manual/reference/method/cursor.toArray/
Besides the usages that JAiro mentioned, I like this one:
def getConnectionProps = {
( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}
If someone needs all connection properties, he can do:
val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps
If you need just a host and a port, you can do:
val ( host, port, _, _ ) = getConnectionProps
I purge derivedData often enough that I have an alias for it. It can fix build problems. I have the following in /Users/Myusername/.bash_profile
alias purgeallbuilds='rm -rf ~/Library/Developer/Xcode/DerivedData/*'
Then in terminal, I type purgeallbuilds, and all subfolders of DerivedData are deleted.
This can be done programmatically by making a replica:
loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
[loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
loginButton.backgroundColor = [UIColor whiteColor];
loginButton.layer.borderColor = [UIColor blackColor].CGColor;
loginButton.layer.borderWidth = 0.5f;
loginButton.layer.cornerRadius = 10.0f;
edit: of course, you'd have to #import <QuartzCore/QuartzCore.h>
edit: to all new readers, you should also consider a few options added as "another possibility". for you consideration.
As this is an old answer, I strongly recommend reading comments for troubleshooting
You may get the following error while creating an optimized production build when using query-string module.
Failed to minify the code from this file: ./node_modules/query-string/index.js:8
To overcome this, kindly use the alternative module called stringquery which does the same process well without any issues while running the build.
import querySearch from "stringquery";
var query = querySearch(this.props.location.search);
From the MDN documentation:
[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table
In other words, the margin
property is not applicable to display:table-cell
elements.
Consider using the border-spacing
property instead.
Note it should be applied to a parent element with a display:table
layout and border-collapse:separate
.
For example:
HTML
<div class="table">
<div class="row">
<div class="cell">123</div>
<div class="cell">456</div>
<div class="cell">879</div>
</div>
</div>
CSS
.table {display:table;border-collapse:separate;border-spacing:5px;}
.row {display:table-row;}
.cell {display:table-cell;padding:5px;border:1px solid black;}
Different margin horizontally and vertically
As mentioned by Diego Quirós, the border-spacing
property also accepts two values to set a different margin for the horizontal and vertical axes.
For example
.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */
You are not indicating what to include in the archive.
Go one level outside your folder and try:
sudo tar -cvjSf folder.tar.bz2 folder
Or from the same folder try
sudo tar -cvjSf folder.tar.bz2 *
Cheers!
http://www.mathworks.com/help/techdoc/ref/rand.html
n = 13 + (rand(1) * 7);
new_data <- data %>% filter_all(any_vars(is.na(.)))
This should create a new data frame (new_data
) with only the missing values in it.
Works best to keep a track of values that you might later drop because they had some columns with missing observations (NA).
Everyone has a setTimeout/setInterval solution already. I think that it is important to note that you can pass functions to setInterval, not just strings. Its actually probably a little "safer" to pass real functions instead of strings that will be "evaled" to those functions.
// example 1
function test() {
alert('called');
}
var interval = setInterval(test, 10000);
Or:
// example 2
var counter = 0;
var interval = setInterval(function() { alert("#"+counter++); }, 5000);
Your proposed doCalculationsAndUpdateUIs
does data processing and dispatches UI updates to the main queue. I presume that you have dispatched doCalculationsAndUpdateUIs
to a background queue when you first called it.
While technically fine, that's a little fragile, contingent upon your remembering to dispatch it to the background every time you call it: I would, instead, suggest that you do your dispatch to the background and dispatch back to the main queue from within the same method, as it makes the logic unambiguous and more robust, etc.
Thus it might look like:
- (void)doCalculationsAndUpdateUIs {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{
// DATA PROCESSING 1
dispatch_async(dispatch_get_main_queue(), ^{
// UI UPDATION 1
});
/* I expect the control to come here after UI UPDATION 1 */
// DATA PROCESSING 2
dispatch_async(dispatch_get_main_queue(), ^{
// UI UPDATION 2
});
/* I expect the control to come here after UI UPDATION 2 */
// DATA PROCESSING 3
dispatch_async(dispatch_get_main_queue(), ^{
// UI UPDATION 3
});
});
}
In terms of whether you dispatch your UI updates asynchronously with dispatch_async
(where the background process will not wait for the UI update) or synchronously with dispatch_sync
(where it will wait for the UI update), the question is why would you want to do it synchronously: Do you really want to slow down the background process as it waits for the UI update, or would you like the background process to carry on while the UI update takes place.
Generally you would dispatch the UI update asynchronously with dispatch_async
as you've used in your original question. Yes, there certainly are special circumstances where you need to dispatch code synchronously (e.g. you're synchronizing the updates to some class property by performing all updates to it on the main queue), but more often than not, you just dispatch the UI update asynchronously and carry on. Dispatching code synchronously can cause problems (e.g. deadlocks) if done sloppily, so my general counsel is that you should probably only dispatch UI updates synchronously if there is some compelling need to do so, otherwise you should design your solution so you can dispatch them asynchronously.
In answer to your question as to whether this is the "best way to achieve this", it's hard for us to say without knowing more about the business problem being solved. For example, if you might be calling this doCalculationsAndUpdateUIs
multiple times, I might be inclined to use my own serial queue rather than a concurrent global queue, in order to ensure that these don't step over each other. Or if you might need the ability to cancel this doCalculationsAndUpdateUIs
when the user dismisses the scene or calls the method again, then I might be inclined to use a operation queue which offers cancelation capabilities. It depends entirely upon what you're trying to achieve.
But, in general, the pattern of asynchronously dispatching a complicated task to a background queue and then asynchronously dispatching the UI update back to the main queue is very common.
Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.
There's an easy way to do that. Very easy. Since I noticed that
$scope.yourModel = [];
removes all $scope.yourModel array list you can do like this
function deleteAnObjectByKey(objects, key) {
var clonedObjects = Object.assign({}, objects);
for (var x in clonedObjects)
if (clonedObjects.hasOwnProperty(x))
if (clonedObjects[x].id == key)
delete clonedObjects[x];
$scope.yourModel = clonedObjects;
}
The $scope.yourModel will be updated with the clonedObjects.
Hope that helps.
The node-csv project that you are referencing is completely sufficient for the task of transforming each row of a large portion of CSV data, from the docs at: http://csv.adaltas.com/transform/:
csv()
.from('82,Preisner,Zbigniew\n94,Gainsbourg,Serge')
.to(console.log)
.transform(function(row, index, callback){
process.nextTick(function(){
callback(null, row.reverse());
});
});
From my experience, I can say that it is also a rather fast implementation, I have been working with it on data sets with near 10k records and the processing times were at a reasonable tens-of-milliseconds level for the whole set.
Rearding jurka's stream based solution suggestion: node-csv IS stream based and follows the Node.js' streaming API.
Here is an example of using flex that also works in Internet Explorer 11 and Chrome.
HTML
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >_x000D_
<title>Flex Test</title>_x000D_
<style>_x000D_
html, body {_x000D_
margin: 0px;_x000D_
padding: 0px;_x000D_
height: 100vh;_x000D_
}_x000D_
.main {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-ms-flex-direction: row;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
min-height: 100vh;_x000D_
}_x000D_
_x000D_
.main::after {_x000D_
content: '';_x000D_
height: 100vh;_x000D_
width: 0;_x000D_
overflow: hidden;_x000D_
visibility: hidden;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.left {_x000D_
width: 200px;_x000D_
background: #F0F0F0;_x000D_
flex-shrink: 0;_x000D_
}_x000D_
_x000D_
.right {_x000D_
flex-grow: 1;_x000D_
background: yellow;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="main">_x000D_
<div class="left">_x000D_
<div style="height: 300px;">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="right">_x000D_
<div style="height: 1000px;">_x000D_
test test test_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
So Why not use powershell to create the list of source files for you. Take a look at this script
param (
[Parameter(Mandatory=$True)]
[string]$root
)
if (-not (Test-Path -Path $root)) {
throw "Error directory does not exist"
}
#get the full path of the root
$rootDir = get-item -Path $root
$fp=$rootDir.FullName;
$files = Get-ChildItem -Path $root -Recurse -File |
Where-Object { ".cpp",".cxx",".cc",".h" -contains $_.Extension} |
Foreach {$_.FullName.replace("${fp}\","").replace("\","/")}
$CMakeExpr = "set(SOURCES "
foreach($file in $files){
$CMakeExpr+= """$file"" " ;
}
$CMakeExpr+=")"
return $CMakeExpr;
Suppose you have a folder with this structure
C:\Workspace\A
--a.cpp
C:\Workspace\B
--b.cpp
Now save this file as "generateSourceList.ps1" for example, and run the script as
~>./generateSourceList.ps1 -root "C:\Workspace" > out.txt
out.txt file will contain
set(SOURCE "A/a.cpp" "B/b.cpp")
This method works for both Windows and Linux:
#include <stdio.h>
#include <string>
#ifdef _WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#elif __linux__
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
std::string GetCurrentWorkingDir()
{
char buff[FILENAME_MAX];
GetCurrentDir(buff, FILENAME_MAX);
std::string current_working_dir(buff);
return current_working_dir;
}
You can push current branch with command
git push origin HEAD
(took from here)
If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:
div#wrapper {
position: absolute;
width: 100%;
text-align: center;
}
Remember that in order to position an element absolutely, the parent element must be positioned relatively.
Or even simpler:
import time
a = 0
while True:
print (a, end="\r")
a += 1
time.sleep(0.1)
end="\r"
will overwrite from the beginning [0:] of the first print.
Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.
I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.
import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")
usage
$ python3 script.py -f
After parsing when checked with args.f it returns true,
args = parser.parse_args()
print(args.f)
>>>true
You can access the src property of the iframe but that will only give you the initially loaded URL. If the user is navigating around in the iframe via you'll need to use an HTA to solve the security problem.
http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx
Check out the link, using an HTA and setting the "application" property of an iframe will allow you to access the document.href property and parse out all of the information you want, including DOM elements and their values if you so choose.
Best way:
<Button
android:text="OK"
android:id="@+id/buttonok"
android:background="@drawable/buttonok"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
If you want to DUMP your inserts into an .sql file:
cd
to the location which you want to .sql
file to be locatedpg_dump --column-inserts --data-only --table=<table> <database> > my_dump.sql
Note the > my_dump.sql
command. This will put everything into a sql file named my_dump
You can use the spool
command (SQL*Plus documentation, but one of many such commands SQL Developer also supports) to write results straight to disk. Each spool
can change the file that's being written to, so you can have several queries writing to different files just by putting spool
commands between them:
spool "\path\to\spool1.txt"
select /*csv*/ * from employees;
spool "\path\to\spool2.txt"
select /*csv*/ * from locations;
spool off;
You'd need to run this as a script (F5, or the second button on the command bar above the SQL Worksheet). You might also want to explore some of the formatting options and the set
command, though some of those do not translate to SQL Developer.
Since you mentioned CSV in the title I've included a SQL Developer-specific hint that does that formatting for you.
A downside though is that SQL Developer includes the query in the spool file, which you can avoid by having the commands and queries in a script file that you then run as a script.
No need to use sub query, just Try this,Its working fine:
DB::table('orders')->orderBy('id', 'desc')->first();
Most of the previous answer didn't work for me in Firefox 38.0.5. This did...
<div style='padding: 3px; width: 130px; word-break: break-all; word-wrap: break-word;'>
// Content goes here
</div>
Documentation:
To get the current time in UTC in Python 3.2+:
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2015-01-27T05:57:31.399861+00:00'
To get local time in Python 3.3+:
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).astimezone().isoformat()
'2015-01-27T06:59:17.125448+01:00'
Explanation: datetime.now(timezone.utc)
produces a timezone aware datetime
object in UTC time. astimezone()
then changes the timezone of the datetime
object, to the system's locale timezone if called with no arguments. Timezone aware datetime
objects then produce the correct ISO format automatically.
Check out XML2 from http://www.ofb.net/~egnor/xml2/ which converts XML to a line-oriented format.
Well, all could be temporary hacks, but there is no way to get mobile number of a user. It is against ethical policy.
For eg, one of the answers above suggests getting all accounts and extracting from there. And it doesn't work anymore! All of these are hacks only.
Only way to get user's mobile number is going through operator. If you have a tie-up with mobile operators like Aitel, Vodafone, etc, you can get user's mobile number in header of request from mobile handset when connected via mobile network internet.
Not sure if any manufacturer tie ups to get specific permissions can help - not explored this area, but nothing documented atleast.
And here is a quick benchmark for both #sample
and #rand
:
irb(main):014:0* Benchmark.bm do |x|
irb(main):015:1* x.report('sample') { 1_000_000.times { (1..100).to_a.sample } }
irb(main):016:1> x.report('rand') { 1_000_000.times { rand(1..100) } }
irb(main):017:1> end
user system total real
sample 3.870000 0.020000 3.890000 ( 3.888147)
rand 0.150000 0.000000 0.150000 ( 0.153557)
So, doing rand(a..b)
is the right thing
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
For macOS with zshrc:
ANDROID_HOME is depreciated, use ANDROID_SDK_ROOT instead
/Users/<USER>/Library/Android/sdk
echo 'export ANDROID_SDK_ROOT=/Users/<USER>/Library/Android/sdk' >> ~/.zshenv
source ~/.zshrc
echo $ANDROID_SDK_ROOT
env
You can apply this process to every environment variable beeing installed on your macOS system. It took me a while to comprehend it for myself
No one mentioned the keyring extension. It will save the username and password into the system keyring, which is far more secure than storing your passwords in a static file as mentioned above. Perform the steps below and you should be good to go. I had this up and running on Ubuntu in about 2 minutes.
>> sudo apt-get install python-pip
>> sudo pip install keyring
>> sudo pip install mercurial_keyring
**Edit your .hgrc file to include the extension**
[extensions]
mercurial_keyring =
You just need to drag and drop an ImageView
, create the outlet action, link it, and provide an image (Xcode is going to look in your assets
folder for the name you provided (here: "toronto"))
In yourProject/ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imgView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imgView.image = UIImage(named: "toronto")
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set up notitle
requestWindowFeature(Window.FEATURE_NO_TITLE);
//set up full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
Most basic example (live example here):
CSS:
#wrapper {
width: 500px;
margin: 0 auto;
}
HTML:
<body>
<div id="wrapper">
Piece of text inside a 500px width div centered on the page
</div>
</body>
How the principle works:
Create your wrapper and assign it a certain width. Then apply an automatic horizontal margin to it by using margin: 0 auto;
or margin-left: auto; margin-right: auto;
. The automatic margins make sure your element is centered.
All algorithms can be defined recursively. That makes it much, much easier to visualize and prove.
Some algorithms (e.g., the Ackermann Function) cannot (easily) be specified iteratively.
A recursive implementation will use more memory than a loop if tail call optimization can't be performed. While iteration may use less memory than a recursive function that can't be optimized, it has some limitations in its expressive power.
You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!
This is a warning which I faced in PHP 7, the easy fix to this is by initializing the variable before using it
$myObj=new \stdClass();
Once you have intialized it then you can use it for objects
$myObj->mesg ="Welcome back - ".$c_user;
I believe it would be like this
takedata.match(/(\[.+\])/g);
the g
at the end means global, so it doesn't stop at the first match.
Thanks to author of this blog: https://bigdata-etl.com/solved-how-to-connect-from-android-emulator-to-application-on-localhost/
Defining network security config in xml
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">10.0.2.2</domain>
</domain-config>
</network-security-config>
And setting it on AndroidManifest.xml
<application
android:networkSecurityConfig="@xml/network_security_config"
</application>
Solved issue for me!
Please refer: https://developer.android.com/training/articles/security-config
You can use the is function
if( $('#cartContent').is(':empty') ) { }
or use the length
if( $('#cartContent:empty').length ) { }
You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.
Best practice for RESTful API design is that path params are used to identify a specific resource or resources, while query parameters are used to sort/filter those resources.
Here's an example. Suppose you are implementing RESTful API endpoints for an entity called Car. You would structure your endpoints like this:
GET /cars
GET /cars/:id
POST /cars
PUT /cars/:id
DELETE /cars/:id
This way you are only using path parameters when you are specifying which resource to fetch, but this does not sort/filter the resources in any way.
Now suppose you wanted to add the capability to filter the cars by color in your GET requests. Because color is not a resource (it is a property of a resource), you could add a query parameter that does this. You would add that query parameter to your GET /cars
request like this:
GET /cars?color=blue
This endpoint would be implemented so that only blue cars would be returned.
As far as syntax is concerned, your URL names should be all lowercase. If you have an entity name that is generally two words in English, you would use a hyphen to separate the words, not camel case.
Ex. /two-words
VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.
Here is how to install it:
C:\Windows
called MSJAVA.DLL
. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.SETUP.EXE
, select Run As Administrator
.C:\Program Files\Microsoft Visual Studio\VB98\
After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.
Edit: Updated dead link to point to a different page with the same instructions
Edit: Updated the answer with the actual instructions in the post as the link kept dying
First shift the column:
df['gdp'] = df['gdp'].shift(-1)
Second remove the last row which contains an NaN Cell:
df = df[:-1]
Third reset the index:
df = df.reset_index(drop=True)
You didn't specify a GradientType
:
background: #f0f0f0; /* Old browsers */
background: -moz-linear-gradient(top, #ffffff 0%, #eeeeee 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* W3C */
Just to add up my bit:
Remember, you're gonna need to have at least 2 areas in your MVC application to get the routeValues: { area="" }
working; otherwise the area value will be used as a query-string parameter and you link will look like this: /?area=
If you don't have at least 2 areas, you can fix this behavior by:
1. editing the default route in RouteConfig.cs
like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
OR
2. Adding a dummy area to your MVC project.
On Raspberry pi II, I had the same problem. After trying the following, I solved the problem. The solution is:
sudo apt-get update
sudo apt-get install libjpeg-dev
Try this one-shot solution that should figure out where ImageMagick is, if you have access to it...
This found all versions on my Godaddy hosting.
Upload this file to your server and call it ImageMagick.php
or something then run it. You will get all the info you need... hopefully...
Good luck.
<?
/*
// This file will run a test on your server to determine the location and versions of ImageMagick.
//It will look in the most commonly found locations. The last two are where most popular hosts (including "Godaddy") install ImageMagick.
//
// Upload this script to your server and run it for a breakdown of where ImageMagick is.
//
*/
echo '<h2>Test for versions and locations of ImageMagick</h2>';
echo '<b>Path: </b> convert<br>';
function alist ($array) { //This function prints a text array as an html list.
$alist = "<ul>";
for ($i = 0; $i < sizeof($array); $i++) {
$alist .= "<li>$array[$i]";
}
$alist .= "</ul>";
return $alist;
}
exec("convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"
echo '<br>';
echo '<b>This should test for ImageMagick version 5.x</b><br>';
echo '<b>Path: </b> /usr/bin/convert<br>';
exec("/usr/bin/convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"
echo '<br>';
echo '<b>This should test for ImageMagick version 6.x</b><br>';
echo '<b>Path: </b> /usr/local/bin/convert<br>';
exec("/usr/local/bin/convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version";
?>
If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before
//HTML
<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
<div class="morph-button morph-button-overlay morph-button-fixed">
<button id="user-interface" type="button">MORE INFO</button>
<!--a id="user-interface" href="javascript:void(0)">popup</a-->
<div class="morph-content">
<div>
<div class="content-style-overlay">
<span class="icon icon-close">Close the overlay</span>
<h2>About Parsley</h2>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
</div>
</div>
</div>
</div>
</div>
//CSS
/* Blur - doesn't work on IE */
.blur-on, .blur-element {
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);
filter: blur(10px);
-webkit-transition: all 5s linear;
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
.blur-off {
-webkit-filter: blur(0px) !important;
-moz-filter : blur(0px) !important;
-o-filter : blur(0px) !important;
-ms-filter : blur(0px) !important;
filter : blur(0px) !important;
}
.blur-bgimage:before {
content: "";
position: absolute;
height: 20%; width: 20%;
background-size: cover;
background: inherit;
z-index: -1;
transform: scale(5);
transform-origin: top left;
filter: blur(2px);
-moz-transform: scale(5);
-moz-transform-origin: top left;
-moz-filter: blur(2px);
-webkit-transform: scale(5);
-webkit-transform-origin: top left;
-webkit-filter: blur(2px);
-o-transform: scale(5);
-o-transform-origin: top left;
-o-filter: blur(2px);
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
//Javascript
function blurBehindPopup() {
if(blurredElements.length == 0) {
for(var i=0; i < document.body.children.length; i++) {
var element = document.body.children[i];
if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
classie.addClass( element, 'blur-element' );
blurredElements.push(element);
}
}
} else {
for(var i=0; i < blurredElements.length; i++) {
classie.addClass( blurredElements[i], 'blur-element' );
}
}
}
function unblurBehindPopup() {
for(var i=0; i < blurredElements.length; i++) {
classie.removeClass( blurredElements[i], 'blur-element' );
}
}
Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Demo {
public static final String PRIVATE_KEY="/home/user/private.der";
public static final String PUBLIC_KEY="/home/user/public.der";
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
//get the private key
File file = new File(PRIVATE_KEY);
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) file.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
System.out.println("Exponent :" + privKey.getPrivateExponent());
System.out.println("Modulus" + privKey.getModulus());
//get the public key
File file1 = new File(PUBLIC_KEY);
FileInputStream fis1 = new FileInputStream(file1);
DataInputStream dis1 = new DataInputStream(fis1);
byte[] keyBytes1 = new byte[(int) file1.length()];
dis1.readFully(keyBytes1);
dis1.close();
X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
KeyFactory kf1 = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);
System.out.println("Exponent :" + pubKey.getPublicExponent());
System.out.println("Modulus" + pubKey.getModulus());
}
}
Make sure you have your maven bin directory in the path and the JAVA_HOME property set
I hope this query will help you
INSERT INTO `dTable` (`field1`, `field2`)
SELECT field1, field2 FROM `sTable`
WHERE `sTable`.`field1` NOT IN (SELECT `field1` FROM `dTable`)
do wget -r -l0 www.oldsite.com
Then just find www.oldsite.com
would reveal all urls, I believe.
Alternatively, just serve that custom not-found page on every 404 request! I.e. if someone used the wrong link, he would get the page telling that page wasn't found, and making some hints about site's content.
To be able to call notify() you need to synchronize on the same object.
synchronized (someObject) {
someObject.wait();
}
/* different thread / object */
synchronized (someObject) {
someObject.notify();
}
In drawable assets there was an image format which was an unsupported image. When i removed the image every thing started working fine.
Use:
InputStream in = /* Your InputStream */;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;
while ((read=br.readLine()) != null) {
//System.out.println(read);
sb.append(read);
}
br.close();
return sb.toString();
I called SelectAll inside MouseUp event and it worked fine for me.
private bool _tailTextBoxFirstClick = false;
private void textBox1_MouseUp(object sender, MouseEventArgs e)
{
if(_textBoxFirstClick)
textBox1.SelectAll();
_textBoxFirstClick = false;
}
private void textBox1_Leave(object sender, EventArgs e)
{
_textBoxFirstClick = true;
textBox1.Select(0, 0);
}
If you are facing this issue on you Mac. Follow these steps
First checking who is owner of this file by using below command
ls -la /usr/local/lib/node_modules
you will find some file like below one of them is below
drwxr-xr-x 3 root wheel 768 May 29 02:21 node_modules
have you notice that above file is own by root, for make changes inside for you need to change owner ship of path.
you can use check who is current user by this command
id -un (in my case user is yamsol)
and then you can change by calling this command (just replace your user name with ownerName)
sudo chown -R ownerName: /usr/local/lib/node_modules
in my case as you know user is "yamsol" i will call this command in this way
sudo chown -R yamsol: /usr/local/lib/node_modules
thats it.
You can append the values in the query string for the next page to see and process. You can wrap them inside the link tags:
<a href="your_page.php?var1=value1&var2=value2">
You separate each of those values with the &
sign.
Or you can create this on a button click like this:
<input type="button" onclick="document.location.href = 'your_page.php?var1=value1&var2=value2';">
The answer is in here :
To declare a bounded type parameter, list the type parameter's name, followed by the
extends
keyword, followed by its upper bound […]. Note that, in this context, extends is used in a general sense to mean eitherextends
(as in classes) orimplements
(as in interfaces).
So there you have it, it's a bit confusing, and Oracle knows it.
List indexes of -x mean the xth item from the end of the list, so n[-1]
means the last item in the list n
. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1]
to access the last item of a list.
I know this post is a few years old, but what I do is add this line to the top of your class and you will still be able to user Server.MapPath
Dim Server = HttpContext.Current.Server
or u can make a function
Public Function MapPath(sPath as String)
return HttpContext.Current.Server.MapPath(sPath)
End Function
I am all about making things easier. I have also added it to my Utilities class just in case i run into this again.
Have you tried .editorconfig? You can create this file in the root of your project and configure indentation for different file types. Your code will be automatically formatted. Here's the example:
# top-most EditorConfig file
root = true
# matches all files
[*]
indent_style = tab
indent_size = 4
# only json
[*.json]
indent_style = space
indent_size = 2
On windows 10 I managed to get there with:
cd "C:\Users\<your username>\AppData\Local\Programs\Python\Python37-32"
python -m pip install --upgrade pip <-- upgrading from 10.something to 19.2.2.
pip3 uninstall pillow
pip3 uninstall PIL
pip3 install image
after which in python (python 3.7 in my case) this works fine...
import PIL
from PIL import image
Do not forget to verify if your text editor encodes properly your code in UTF-8.
Otherwise, you may have invisible characters that are not interpreted as UTF-8.
I had the same issue on my windows 10. This is what fixed my problem
bower_components
in your root folder.bowerrc
file in the root{"directory" : "public/bower_components"}
bower install
You should see bower_components folder in your public folder now
Just wanted to update this thread for future developers.
JQuery >1.12 Now supports being able to change every little piece of the request through JQuery.post ($.post({...}). see second function signature in https://api.jquery.com/jquery.post/
If You have got this error while running composer install command,
don't worry.
Steps to be followed and requirements:
Just go to php.ini file and uncomment the line
From:
;extension=php_intl.dll
To:
extension=php_intl.dll
Note: If you don't find any of the file named as php_intl.dll, then you need to upgrade the PHP version.
MongoDB has what is called capped collections
and tailable cursors
that allows MongoDB to push data to the listeners.
A capped collection
is essentially a collection that is a fixed size and only allows insertions. Here's what it would look like to create one:
db.createCollection("messages", { capped: true, size: 100000000 })
Ruby
coll = db.collection('my_collection')
cursor = Mongo::Cursor.new(coll, :tailable => true)
loop do
if doc = cursor.next_document
puts doc
else
sleep 1
end
end
PHP
$mongo = new Mongo();
$db = $mongo->selectDB('my_db')
$coll = $db->selectCollection('my_collection');
$cursor = $coll->find()->tailable(true);
while (true) {
if ($cursor->hasNext()) {
$doc = $cursor->getNext();
print_r($doc);
} else {
sleep(1);
}
}
Python (by Robert Stewart)
from pymongo import Connection
import time
db = Connection().my_db
coll = db.my_collection
cursor = coll.find(tailable=True)
while cursor.alive:
try:
doc = cursor.next()
print doc
except StopIteration:
time.sleep(1)
Perl (by Max)
use 5.010;
use strict;
use warnings;
use MongoDB;
my $db = MongoDB::Connection->new;
my $coll = $db->my_db->my_collection;
my $cursor = $coll->find->tailable(1);
for (;;)
{
if (defined(my $doc = $cursor->next))
{
say $doc;
}
else
{
sleep 1;
}
}
An article talking about tailable cursors in more detail.
PHP, Ruby, Python, and Perl examples of using tailable cursors.
I see that BigDecimal has an inflate() method on equals() method. What does inflate() do actually?
Basically, inflate()
calls BigInteger.valueOf(intCompact)
if necessary, i.e. it creates the unscaled value that is stored as a BigInteger
from long intCompact
. If you don't need that BigInteger
and the unscaled value fits into a long
BigDecimal
seems to try to save space as long as possible.
Use reverse iterators and loop from rbegin()
to rend()
When you type, if caplock is on, it could automatically convert the current char to lowercase. That way even if caplocks is on, it will not behave like it is on the current page. To inform your users you could display a text saying that caplocks is on, but that the form entries are converted.
for bootstrap 4 this work with me good
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').find(".form-control:first").addClass('is-invalid');
},
unhighlight: function(element) {
$(element).closest('.form-group').find(".form-control:first").removeClass('is-invalid');
$(element).closest('.form-group').find(".form-control:first").addClass('is-valid');
},
errorElement: 'span',
errorClass: 'invalid-feedback',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
hope it will help !
Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave.
What are you trying to do? Perhaps you should use sys.exit()
or return
instead?
Try this example.
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<GridView
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/grid"
android:background="#fff7ff"
/>
</LinearLayout>
grid_single.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="@+id/grid_image"
android:layout_width="60dp"
android:layout_height="60dp"
>
</ImageView>
<TextView
android:id="@+id/grid_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textSize="9sp"
android:textColor="#3a0fff">
</TextView>
</LinearLayout>
CustomGrid.java:
package com.example.lalit.gridtest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomGrid extends BaseAdapter {
private Context mContext;
private final String[] web;
private final int[] Imageid;
public CustomGrid(Context c, String[] web, int[] Imageid) {
mContext = c;
this.Imageid = Imageid;
this.web = web;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return web.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
textView.setText(web[position]);
imageView.setImageResource(Imageid[position]);
} else {
grid = (View) convertView;
}
return grid;
}
}
MainActivity.java:
package com.example.lalit.gridtest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
GridView grid;
String[] web = {
"Mom",
"Mahendra",
"Narayan",
"Bhai",
"Deepak",
"Sanjay",
"Navdeep",
"Lovesh",
};
int[] imageId = {
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id){
if (web[position].toString().equals("Mom")) {
try {
String uri ="te:"+ "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if (web[position].toString().equals("Mahendra")) {
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Narayan")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Bhai")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Deepak")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Sanjay")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Navdeep")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Lovesh")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
});
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lalit.gridtest" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.
Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.
Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.
ETA 24 Apr 17
I wanted to simplify this a bit with some async
/await
magic, as it makes it a lot more succinct:
Using the same promisified-observable:
const startObservable = (domNode) => {
var targetNode = domNode;
var observerConfig = {
attributes: true,
childList: true,
characterData: true
};
return new Promise((resolve) => {
var observer = new MutationObserver(function (mutations) {
// For the sake of...observation...let's output the mutation to console to see how this all works
mutations.forEach(function (mutation) {
console.log(mutation.type);
});
resolve(mutations)
});
observer.observe(targetNode, observerConfig);
})
}
Your calling function can be as simple as:
const waitForMutation = async () => {
const button = document.querySelector('.some-button')
if (button !== null) button.click()
try {
const results = await startObservable(someDomNode)
return results
} catch (err) {
console.error(err)
}
}
If you wanted to add a timeout, you could use a simple Promise.race
pattern as demonstrated here:
const waitForMutation = async (timeout = 5000 /*in ms*/) => {
const button = document.querySelector('.some-button')
if (button !== null) button.click()
try {
const results = await Promise.race([
startObservable(someDomNode),
// this will throw after the timeout, skipping
// the return & going to the catch block
new Promise((resolve, reject) => setTimeout(
reject,
timeout,
new Error('timed out waiting for mutation')
)
])
return results
} catch (err) {
console.error(err)
}
}
Original
You can do this without libraries, but you'd have to use some ES6 stuff, so be cognizant of compatibility issues (i.e., if your audience is mostly Amish, luddite or, worse, IE8 users)
First, we'll use the MutationObserver API to construct an observer object. We'll wrap this object in a promise, and resolve()
when the callback is fired (h/t davidwalshblog)david walsh blog article on mutations:
const startObservable = (domNode) => {
var targetNode = domNode;
var observerConfig = {
attributes: true,
childList: true,
characterData: true
};
return new Promise((resolve) => {
var observer = new MutationObserver(function (mutations) {
// For the sake of...observation...let's output the mutation to console to see how this all works
mutations.forEach(function (mutation) {
console.log(mutation.type);
});
resolve(mutations)
});
observer.observe(targetNode, observerConfig);
})
}
Then, we'll create a generator function
. If you haven't used these yet, then you're missing out--but a brief synopsis is: it runs like a sync function, and when it finds a yield <Promise>
expression, it waits in a non-blocking fashion for the promise to be fulfilled (Generators do more than this, but this is what we're interested in here).
// we'll declare our DOM node here, too
let targ = document.querySelector('#domNodeToWatch')
function* getMutation() {
console.log("Starting")
var mutations = yield startObservable(targ)
console.log("done")
}
A tricky part about generators is they don't 'return' like a normal function. So, we'll use a helper function to be able to use the generator like a regular function. (again, h/t to dwb)
function runGenerator(g) {
var it = g(), ret;
// asynchronously iterate over generator
(function iterate(val){
ret = it.next( val );
if (!ret.done) {
// poor man's "is it a promise?" test
if ("then" in ret.value) {
// wait on the promise
ret.value.then( iterate );
}
// immediate value: just send right back in
else {
// avoid synchronous recursion
setTimeout( function(){
iterate( ret.value );
}, 0 );
}
}
})();
}
Then, at any point before the expected DOM mutation might happen, simply run runGenerator(getMutation)
.
Now you can integrate DOM mutations into a synchronous-style control flow. How bout that.
You may be using old version of Mysql but surely you can use
DELETE FROM konta WHERE taken <> ''
But there are many other options available. You can try the following ones
DELETE * from konta WHERE strcmp(taken, '') <> 0;
DELETE * from konta where NOT (taken = '');
If you simply want to see the column names this one line should provide it without changing any settings:
describe database.tablename;
However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:
use database;
describe tablename;
You can use $last
variable within ng-repeat
directive. Take a look at doc.
You can do it like this:
<div ng-repeat="file in files" ng-class="computeCssClass($last)">
{{file.name}}
</div>
Where computeCssClass
is function of controller
which takes sole argument and returns 'last'
or null
.
Or
<div ng-repeat="file in files" ng-class="{'last':$last}">
{{file.name}}
</div>
$('.update-cart').click(function(e) {
updateCartWidget();
e.stopPropagation();
e.preventDefault();
});
$('.update-cart').click(function() {
updateCartWidget();
return false;
});
The following methods achieve the exact same thing.
From the official JAR File Specification (link goes to the Java 7 version, but the text hasn't changed since at least v1.3):
The META-INF directory
The following files/directories in the META-INF directory are recognized and interpreted by the Java 2 Platform to configure applications, extensions, class loaders and services:
MANIFEST.MF
The manifest file that is used to define extension and package related data.
INDEX.LIST
This file is generated by the new "
-i
" option of the jar tool, which contains location information for packages defined in an application or extension. It is part of the JarIndex implementation and used by class loaders to speed up their class loading process.
x.SF
The signature file for the JAR file. 'x' stands for the base file name.
x.DSA
The signature block file associated with the signature file with the same base file name. This file stores the digital signature of the corresponding signature file.
services/
This directory stores all the service provider configuration files.
Ok If I understand what your asking you would do this;
You have your DIV container called #main-container
and .my-element
that is within it. Use this to get you started;
#main-container {
position:relative;
}
/*To make the element absolute - floats above all else within the parent container do this.*/
.my-element {
position:absolute;
top:0;
right:10px;
}
/*To make the element apart of elements, something tangible that affects the position of other elements on the same level within the parent then do this;*/
.my-element {
float:right;
margin-right:10px;
}
By the way, it better practice to use classes if you referencing a lower level element within a page (I assume you are hence my name change above.
npm start --prefix path/to/your/app
& inside package.json add the following script
"scripts": {
"preinstall":"cd $(pwd)"
}
1. How to get 'refresh_token' ?
Solution: access_type='offline' option should be used when generating authURL. source : Using OAuth 2.0 for Web Server Applications
2. But even with 'access_type=offline', I am not getting the 'refresh_token' ?
Solution: Please note that you will get it only on the first request, so if you are storing it somewhere and there is a provision to overwrite this in your code when getting new access_token after previous expires, then make sure not to overwrite this value.
From Google Auth Doc : (this value = access_type)
This value instructs the Google authorization server to return a refresh token and an access token the first time that your application exchanges an authorization code for tokens.
If you need 'refresh_token' again, then you need to remove access for your app as by following the steps written in Rich Sutton's answer.
When dealing with a hash {}
, use both the key and value to the block inside the ||
.
details.map {|key,item|"" == item}
=>[false, false, true, false, false]