If the variable is re-used within the same RUN
instruction, one could simply set a shell variable. I really like how they approached this with the official Ruby Dockerfile.
You are looking for the SO_KEEPALIVE socket option.
The Java Socket API exposes "keep-alive" to applications via the setKeepAlive
and getKeepAlive
methods.
EDIT: SO_KEEPALIVE is implemented in the OS network protocol stacks without sending any "real" data. The keep-alive interval is operating system dependent, and may be tuneable via a kernel parameter.
Since no data is sent, SO_KEEPALIVE can only test the liveness of the network connection, not the liveness of the service that the socket is connected to. To test the latter, you need to implement something that involves sending messages to the server and getting a response.
You can install other builds but not Appstore build.
From Xcode 8.2,drag and drop the build to simulator for the installation.
SET JAVA_HOME=C:\Applications\java\java_8
SET PATH=%PATH%;C:\Applications\java\java_8\bin
SET JAVA_OPTIONS=-d64 -Xms128g -Xmx128g
I think a quick and dirty way is to create a pipe between child and parent. When parent exits, children will receive a SIGPIPE.
To have access to stuff provided by math
module, like pi
. You need to import the module first:
import math
print (math.pi)
You have to invoke this class on the top of your page or class :
using System.Configuration;
Then you can use this Method that returns the connection string to be ready to passed to the sqlconnection object to continue your work as follows:
private string ReturnConnectionString()
{
// Put the name the Sqlconnection from WebConfig..
return ConfigurationManager.ConnectionStrings["DBWebConfigString"].ConnectionString;
}
Just to make a clear clarification this is the value in the web Config:
<add name="DBWebConfigString" connectionString="....." /> </connectionStrings>
Delete
operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirementsInsert
for arrays is basically Set
as mentioned in the beginningNone of the above worked for me using JQM 1.2.0
This did work for me:
.ui-page.ui-body-c {
background: url(bg.png);
background-repeat:no-repeat;
background-position:center center;
background-size:cover;
}
You can use ngHide (or ngShow) directive. It doesn't create child scope as ngIf does.
<div ng-hide="testa">
Just use your text editor with a plugin.
Your editor quite possibly has a package/plugin to handle this for you. For example, in Emacs, you can install markdown-toc TOC generator. Then as you edit, just repeatedly call M-x markdown-toc-generate-or-refresh-toc
. That's worth a key binding if you want to do it often. It's good at generating a simple TOC without polluting your doc with HTML anchors.
Other editors have similar plugins, so the popular list is something like:
I have the same problem but i tried this one to solve my problem. it returns large image. It is not the perfect fix but you can try this one.
https://graph.facebook.com/v2.0/OBJECT_ID/picture?access_token=XXXXX
Even loading bootstrap after jquery-ui, I was able to fix using this:
.ui-dialog-titlebar-close:after {
content: 'X' !important;
position: absolute;
top: -2px;
right: 3px;
}
I fixed this error by installing babel-polyfill
npm install babel-polyfill --save
then I imported it in my app entry point
import http from 'http';
import config from 'dotenv';
import 'babel-polyfill';
import { register } from 'babel-core';
import app from '../app';
for testing I included --require babel-polyfill in my test script
"test": "export NODE_ENV=test|| SET NODE_ENV=test&& mocha --compilers
js:babel-core/register --require babel-polyfill server/test/**.js --exit"
But you can open the folder with the .SLN in to edit the code in the project, which will detect the .SLN to select the library that provides Intellisense.
just for the record you can always compare using JSON.stringify
const arr = [1,2,3];
expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3]));
expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));
It's all meter of taste, this will also work for complex literal objects
you can use OnClick="document.getElementById('formID_NOT_NAME').SUBMIT()"
I would choose Sequelize because of it's excellent documentation. It's just a honest opinion (I never really used MySQL with Node that much).
Typically a .sh file is a shell script which you can execute in a terminal. Specifically, the script you mentioned is a bash script, which you can see if you open the file and look in the first line of the file, which is called the shebang or magic line.
Shortest answer, given your timezone being TZ
:
LocalDateTime start = LocalDate.now(TZ).atStartOfDay()
LocalDateTime end = start.plusDays(1)
Compare using isAfter()
and isBefore()
methods, or convert it using toEpochSecond()
or toInstant()
methods.
Right-click the table in DB2 Control Center and chose Generate DDL... That will give you everything you need and more.
Unless you have more style sheets than that, you've messed up your break points:
#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)
The 3rd media query is probably meant to be min-width: 901px
. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.
Edit for updated question:
(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)
Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width
for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:
(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)
Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.
Use this for your code
<ul class="nav nav-tabs" style="margin-top:10em;">
<li class="active" data-toggle="tab"><a href="#">Assign</a></li>
<li data-toggle="tab"><a href="#">Two</a></li>
<li data-toggle="tab"><a href="#">Three</a></li>
+1 to @MartinNuc, you can run the mysql
client in batch mode and then you won't see the long stream of "OK" lines.
The amount of time it takes to import a given SQL file depends on a lot of things. Not only the size of the file, but the type of statements in it, how powerful your server server is, and how many other things are running at the same time.
@MartinNuc says he can load 4GB of SQL in 4-5 minutes, but I have run 0.5 GB SQL files and had it take 45 minutes on a smaller server.
We can't really guess how long it will take to run your SQL script on your server.
Re your comment,
@MartinNuc is correct you can choose to make the mysql client print every statement. Or you could open a second session and run mysql> SHOW PROCESSLIST
to see what's running. But you probably are more interested in a "percentage done" figure or an estimate for how long it will take to complete the remaining statements.
Sorry, there is no such feature. The mysql client doesn't know how long it will take to run later statements, or even how many there are. So it can't give a meaningful estimate for how much time it will take to complete.
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
$ find . -name \*.exe -o -name \*.dll -o -print
The first two -name options have no -print option, so they skipped. Everything else is printed.
I resolved this of following way:
here the code:
var deferred = $q.defer(),
self = this,
onConnect = function(status){
if (status === Strophe.Status.CONNECTING) {
deferred.notify({status: 'connecting'});
} else if (status === Strophe.Status.CONNFAIL) {
self.connected = false;
deferred.notify({status: 'fail'});
} else if (status === Strophe.Status.DISCONNECTING) {
deferred.notify({status: 'disconnecting'});
} else if (status === Strophe.Status.DISCONNECTED) {
self.connected = false;
deferred.notify({status: 'disconnected'});
} else if (status === Strophe.Status.CONNECTED) {
self.connection.send($pres().tree());
self.connected = true;
deferred.resolve({status: 'connected'});
} else if (status === Strophe.Status.ATTACHED) {
deferred.resolve({status: 'attached'});
self.connected = true;
}
},
output = function(data){
if (self.connected){
var rid = $(data).attr('rid'),
sid = $(data).attr('sid'),
storage = {};
if (localStorageService.cookie.get('day_bind')){
storage = localStorageService.cookie.get('day_bind');
}else{
storage = {};
}
storage[$window.name] = sid + '-' + rid;
localStorageService.cookie.set('day_bind', angular.toJson(storage));
}
};
if ($window.name){
var storage = localStorageService.cookie.get('day_bind'),
value = storage[$window.name].split('-')
sid = value[0],
rid = value[1];
self.connection = new Strophe.Connection(BoshService);
self.connection.xmlOutput = output;
self.connection.attach('bosh@' + BoshDomain + '/' + $window.name, sid, parseInt(rid, 10) + 1, onConnect);
}else{
$window.name = 'web_' + (new Date()).getTime();
self.connection = new Strophe.Connection(BoshService);
self.connection.xmlOutput = output;
self.connection.connect('bosh@' + BoshDomain + '/' + $window.name, '123456', onConnect);
}
I hope help you
Your second approach doesn't work because {name: 'someothername'}
equals {name: 'someothername', age: undefined}
, so theundefined
would overwrite original age value.
When it comes to change state in nested objects, a good approach would be Immutable.js
this.state = {
jasper: Record({name: 'jasper', age: 28})
}
const {jasper} = this.state
this.setState({jasper: jasper.set(name, 'someothername')})
Check parameters from URL string or as :param
in your routeConfig
downstream.component.ts
...
import {Router,ActivatedRoute} from '@angular/router';
...
export class DownstreamComponent {
constructor(
private route: ActivatedRoute,
private router: Router
) {
if(this.route.snapshot.queryParams)
console.log(this.route.snapshot.params); // e.g. :param1 in routeConfig
if(this.route.snapshot.queryParamMap.get('param1'))
console.log(this.route.snapshot.queryParamMap.get('param1')); // e.g. in URI ?param1=blah
}
}
I implemented a rooted tree as a dictionary {child:parent}
. So for instance with the root node 0
, a tree might look like that:
tree={1:0, 2:0, 3:1, 4:2, 5:3}
This structure made it quite easy to go upward along a path from any node to the root, which was relevant for the problem I was working on.
Try this:
@echo off
set /p id="Enter ID: "
You can then use %id%
as a parameter to another batch file like jstack %id%
.
For example:
set /P id=Enter id:
jstack %id% > jstack.txt
For this you can simply use the redirect
function that is included in flask
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/')
def hello():
return redirect("https://www.exampleURL.com", code = 302)
if __name__ == "__main__":
app.run()
Another useful tip(as you're new to flask), is to add app.debug = True
after initializing the flask object as the debugger output helps a lot while figuring out what's wrong.
I saw the above result and query will work fine if you need to check single column value which are duplicate. For example email.
But if you need to check with more columns and would like to check the combination of the result so this query will work fine:
SELECT COUNT(CONCAT(name,email)) AS tot,
name,
email
FROM users
GROUP BY CONCAT(name,email)
HAVING tot>1 (This query will SHOW the USER list which ARE greater THAN 1
AND also COUNT)
Just my 2 cents. I would create a solution which records exactly what changed, very similar to transient's solution.
My ChangesTable would simple be:
DateTime | WhoChanged | TableName | Action | ID |FieldName | OldValue
1) When an entire row is changed in the main table, lots of entries will go into this table, BUT that is very unlikely, so not a big problem (people are usually only changing one thing) 2) OldVaue (and NewValue if you want) have to be some sort of epic "anytype" since it could be any data, there might be a way to do this with RAW types or just using JSON strings to convert in and out.
Minimum data usage, stores everything you need and can be used for all tables at once. I'm researching this myself right now, but this might end up being the way I go.
For Create and Delete, just the row ID, no fields needed. On delete a flag on the main table (active?) would be good.
It do nothing, just provide a common template that will be shared for it's subclass
Use the somewhat hidden security feature:
pip install requests[security]
or
pip install pyOpenSSL ndg-httpsclient pyasn1
Both commands install following extra packages:
Please note that this is not required for python-2.7.9+.
If pip install
fails with errors, check whether you have required development packages for libffi
, libssl
and python
installed in your system using distribution's package manager:
Debian/Ubuntu - python-dev
libffi-dev
libssl-dev
packages.
Fedora - openssl-devel
python-devel
libffi-devel
packages.
Distro list above is incomplete.
Workaround (see the original answer by @TomDotTom):
In case you cannot install some of the required development packages, there's also an option to disable that warning:
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
If your pip
itself is affected by InsecurePlatformWarning
and cannot install anything from PyPI, it can be fixed with this step-by-step guide to deploy extra python packages manually.
urllib2 does not verify server certificate by default. Check this documentation.
Edit: As pointed out in below comment, this is not true anymore for newer versions (seems like >= 2.7.9) of Python. Refer the below ANSWER
open your browser,check whether Tomcat homepage is visible by below command.
http://ipaddress:portnumber
also check this
According to the UI dialog documentation, the dialog plugin generates something like this:
<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable">
<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
<span id="ui-dialog-title-dialog" class="ui-dialog-title">Dialog title</span>
<a class="ui-dialog-titlebar-close ui-corner-all" href="#"><span class="ui-icon ui-icon-closethick">close</span></a>
</div>
<div class="ui-dialog-content ui-widget-content" id="dialog_style1">
<p>One content</p>
</div>
</div>
That means what you can add to any class to exactly to first or second dialog using jQuery's closest() method. For example:
$('#dialog_style1').closest('.ui-dialog').addClass('dialog_style1');
$('#dialog_style2').closest('.ui-dialog').addClass('dialog_style2');
and then CSS it.
I hit this same issue and eventually just solved it by a simple string replace, replacing the word GO with a semi-colon (;)
All seems to be working fine while executing scripts with in-line comments, block comments, and GO commands
public static bool ExecuteExternalScript(string filePath)
{
using (StreamReader file = new StreamReader(filePath))
using (SqlConnection conn = new SqlConnection(dbConnStr))
{
StringBuilder sql = new StringBuilder();
string line;
while ((line = file.ReadLine()) != null)
{
// replace GO with semi-colon
if (line == "GO")
sql.Append(";");
// remove inline comments
else if (line.IndexOf("--") > -1)
sql.AppendFormat(" {0} ", line.Split(new string[] { "--" }, StringSplitOptions.None)[0]);
// just the line as it is
else
sql.AppendFormat(" {0} ", line);
}
conn.Open();
SqlCommand cmd = new SqlCommand(sql.ToString(), conn);
cmd.ExecuteNonQuery();
}
return true;
}
It's necessary to mention that returning copy or view depends on kind of indexing.
The pandas documentation says:
Returning a view versus a copy
The rules about when a view on the data is returned are entirely dependent on NumPy. Whenever an array of labels or a boolean vector are involved in the indexing operation, the result will be a copy. With single label / scalar indexing and slicing, e.g. df.ix[3:6] or df.ix[:, 'A'], a view will be returned.
Window > Preferences, go to the Run/Debug > Console section >> "Limit console output.>>Console buffer size(characters):" (This option can be seen in Eclipse Indigo ,but it limits buffer size at 1,000,000 )
I had a similar problem on a raspberry pi.
The problem was that http requires SSL and so I needed to force it to use https to get around this requirement.
sudo pip install --upgrade pip --index-url=https://pypi.python.org/simple
or
sudo pip-3.2 --upgrade pip --index-url=https://pypi.python.org/simple/
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
if the map is short you can do:
ImmutableMap.of(key, value, key2, value2); // ...up to five k-v pairs
If it is longer then:
ImmutableMap.builder()
.put(key, value)
.put(key2, value2)
// ...
.build();
Use the FormBorderStyle
property of your Form
:
this.FormBorderStyle = FormBorderStyle.FixedDialog;
Use this:
myFunction.bookName = 'mybook';
myFunction.bookdesc = 'new';
Or, if you are using jQuery:
$(myFunction).extend({
bookName:'mybook',
bookdesc: 'new'
});
The push
method is wrong because it belongs to the Array.prototype
object.
To create a named object, try this:
var myObj = function(){
this.property = 'foo';
this.bar = function(){
}
}
myObj.prototype.objProp = true;
var newObj = new myObj();
Below is the sample code to read a line in Standard input using Java Scanner class.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println(s);
scan.close();
}
}
Input:
Hello World
Output:
Hello World
You need to use an explicit color value (e.g. #000
or blue
) for the color
-property. none
is invalid here. The initial value is browser-specific and cannot be restored using CSS. Keep in mind that there are some other pseudo-classes than :active
, too.
I've used Wiredesignz's MY_Language class with great success.
I've just published it on github, as I can't seem to find a trace of it anywhere.
https://github.com/meigwilym/CI_Language
My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.
The for
attribute shows that this label stands for related input field, or check box or radio button or any other data entering field associated with it.
for example
<li>
<label>{translate:blindcopy}</label>
<a class="" href="#" title="{translate:savetemplate}" onclick="" ><i class="fa fa-list" class="button" ></i></a>  
<input type="text" id="BlindCopy" name="BlindCopy" class="splitblindcopy" />
</li>
Whenever I need to get a class from a list of classes or a part of a class name or id, I always use split() then either get it specifically with the array index or, most often in my case, pop() to get the last element or shift() to get the first.
This example gets the div's classes "gallery_148 ui-sortable" and returns the gallery id 148.
var galleryClass = $(this).parent().prop("class"); // = gallery_148 ui-sortable
var galleryID = galleryClass.split(" ").shift(); // = gallery_148
galleryID = galleryID.split("_").pop(); // = 148
//or
galleryID = galleryID.substring(8); // = 148 also, but less versatile
I'm sure it could be compacted into less lines but I left it expanded for readability.
When calling a promise defined in a service or in a factory make sure to use service as I could not get response from a promise defined in a factory. This is how I call a promise defined in a service.
myApp.service('serverOperations', function($http) {
this.get_data = function(user) {
return $http.post('http://localhost/serverOperations.php?action=get_data', user);
};
})
myApp.controller('loginCtrl', function($http, $q, serverOperations, user) {
serverOperations.get_data(user)
.then( function(response) {
console.log(response.data);
}
);
})
A less elegant solution is taking the log 'manually' from the user data dir:
Set the user data dir to a fixed place:
options = new ChromeOptions();
capabilities = DesiredCapabilities.chrome();
options.addArguments("user-data-dir=/your_path/");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
Get the text from the log file chrome_debug.log located in the path you've entered above.
I use this method since RemoteWebDriver
had problems getting the console logs remotely. If you run your test locally that can be easy to retrieve.
You can use the environment variable NUMBER_OF_PROCESSORS
for the total number of processors:
echo %NUMBER_OF_PROCESSORS%
I searched for a solution to the same problem, and found one just worked !! - with almost no extra code..
see https://medium.com/wdstack/bootstrap-equal-height-columns-d07bc934eb27 for a good disuccuion, and with the resposne you want in the bottom, with a link.
https://www.codeply.com/go/EskIjvun4B
this was the correct responsive way to for me... a quote: ... 3 — Use flexbox (best!)
As of 2017, the best (and easiest) way to make equal height columns in a responsive design is using CSS3 flexbox.
.row.display-flex {
display: flex;
flex-wrap: wrap;
}
.row.display-flex > [class*='col-'] {
display: flex;
flex-direction: column;
}
and simply use:
div class="container">
<div class="row display-flex .... etc..
There is a simple and clean way of doing this with only directives.
<div ng-class="{'class-name': clicked}" ng-click="clicked = !clicked"></div>
Important difference if you use dynamic import Webpack mode eager
:
if (normalCondition) {
// this will be included to bundle, whether you use it or not
import(...);
}
if (process.env.SOMETHING === 'true') {
// this will not be included to bundle, if SOMETHING is not 'true'
import(...);
}
latest
is really designed to work with date fields (it probably does work with other total-ordered types too, but not sure). And the only way you can use it without specifying the field name is by setting the get_latest_by
meta attribute, as mentioned here.
Here's a variation of Oscar's first version that doesn't use a for-each loop.
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == 'q') {
// do something
break;
}
}
You could have a boolean variable that gets set to false before the loop, then make "do something" set the variable to true, which you could test for after the loop. The loop could also be wrapped in a function call then just use 'return true' instead of the break, and add a 'return false' statement after the for loop.
package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
It describes a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.It contains the following properties.
{
"name": "mobileapp",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@angular-devkit/architect": {
"version": "0.11.4",
"resolved": "https://registry.npmjs.org/@angular- devkit/architect/-/architect-0.11.4.tgz",
"integrity": "sha512-2zi6S9tPlk52vyqNFg==",
"dev": true,
"requires": {
"@angular-devkit/core": "7.1.4",
"rxjs": "6.3.3"
}
},
}
Heroku sometimes has a problem with database load balancing.
André Laszlo
, markshiz
and me all reported dealing with that in comments on the question.
To save you the support call, here's the response I got from Heroku Support for a similar issue:
Hello,
One of the limitations of the hobby tier databases is unannounced maintenance. Many hobby databases run on a single shared server, and we will occasionally need to restart that server for hardware maintenance purposes, or migrate databases to another server for load balancing. When that happens, you'll see an error in your logs or have problems connecting. If the server is restarting, it might take 15 minutes or more for the database to come back online.
Most apps that maintain a connection pool (like ActiveRecord in Rails) can just open a new connection to the database. However, in some cases an app won't be able to reconnect. If that happens, you can heroku restart your app to bring it back online.
This is one of the reasons we recommend against running hobby databases for critical production applications. Standard and Premium databases include notifications for downtime events, and are much more performant and stable in general. You can use pg:copy to migrate to a standard or premium plan.
If this continues, you can try provisioning a new database (on a different server) with heroku addons:add, then use pg:copy to move the data. Keep in mind that hobby tier rules apply to the $9 basic plan as well as the free database.
Thanks, Bradley
Console.WriteLine(string.Join<TYPE>("\n", someObjectList));
The most important use case is probably exception checking.
While junit4 includes the expected element for checking if an exception occurred, it seems like it isn't part of the newer junit5. Another advantage of using fail()
over the expected
is that you can combine it with finally
allowing test-case cleanup.
dao.insert(obj);
try {
dao.insert(obj);
fail("No DuplicateKeyException thrown.");
} catch (DuplicateKeyException e) {
assertEquals("Error code doesn't match", 123, e.getErrorCode());
} finally {
//cleanup
dao.delete(obj);
}
As noted in another comment. Having a test to fail until you can finish implementing it sounds reasonable as well.
Taking advantage of the fact that a click will always follow a touch event, here is what I did to get rid of the "ghost click" without having to use timeouts or global flags.
$('#buttonId').on('touchstart click', function(event){
if ($(this).data("already")) {
$(this).data("already", false);
return false;
} else if (event.type == "touchstart") {
$(this).data("already", true);
}
//your code here
});
Basically whenever an ontouchstart
event fires on the element, a flag a set and then subsequently removed (and ignored), when the click comes.
Apparently running sudo chmod -R a+rw
on your home folder causes this to happen as well.
check http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html
one needs to use something like
cmd.CommandText = "BEGIN foo@v; END;"
worked for me in vb.net, c#
Did some tests with one of my co-workers here, and found out most of the solutions don't work for numbers under 0.
public int GetFirstDigit(int number)
{
number = Math.Abs(number); <- makes sure you really get the digit!
if (number < 10)
{
return number;
}
return GetFirstDigit((number - (number % 10)) / 10);
}
TMTWWTDI: Perl has a file size operator (-s)
perl -lne '$t+=-s;END{print $t}' files.txt
DTO classes are used to serialize/deserialize data from different sources. When you want to deserialize a object from a source, does not matter what external source it is: service, file, database etc. you may be only want to use some part of that but you want an easy way to deserialize that data to an object. after that you copy that data to the XModel you want to use. A serializer is a beautiful technology to load DTO objects. Why? you only need one function to load (deserialize) the object.
Another solution for class based vanilla JS using a distance threshold
private initDetectDrag(element) {
let clickOrigin = { x: 0, y: 0 };
const dragDistanceThreshhold = 20;
element.addEventListener('mousedown', (event) => {
this.isDragged = false
clickOrigin = { x: event.clientX, y: event.clientY };
});
element.addEventListener('mousemove', (event) => {
if (Math.sqrt(Math.pow(clickOrigin.y - event.clientY, 2) + Math.pow(clickOrigin.x - event.clientX, 2)) > dragDistanceThreshhold) {
this.isDragged = true
}
});
}
Add inside the class (SOMESLIDER_ELEMENT can also be document to be global):
private isDragged: boolean;
constructor() {
this.initDetectDrag(SOMESLIDER_ELEMENT);
this.doSomeSlideStuff(SOMESLIDER_ELEMENT);
element.addEventListener('click', (event) => {
if (!this.sliderIsDragged) {
console.log('was clicked');
} else {
console.log('was dragged, ignore click or handle this');
}
}, false);
}
It's python source parser failure on sum.up=False
named argument as sum.up is not valid argument name (you can't use dots -- only alphanumerics and underscores in argument names).
you can use like this. it's better than
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
<!--[if IE 7]><link rel="stylesheet" type="text/css" media="screen" href="css/ie7.css" /><![endif]-->
<!--[if IE 6]><link rel="stylesheet" type="text/css" media="screen" href="css/ie6.css" /><![endif]-->
-------------------------------------------------------------
<!--[if lt IE 7 ]> <body class="ie6"> <![endif]-->
<!--[if IE 7 ]> <body class="ie7"> <![endif]-->
<!--[if IE 8 ]> <body class="ie8"> <![endif]-->
<!--[if !IE]>--> <body> <!--<![endif]-->
div.foo { color: inherit;} .ie7 div.foo { color: #ff8000; }
If you use relative links to images then the images won't display as all folder structures are not preserved after the iOS app is compiled. What you can do is convert your local web folder into a bundle instead by adding the '.bundle' filename extension.
So if you local website is contained in a folder "www", this should be renamed to "www.bundle". This allows the image folders and directory structure to be preserved. Then load the 'index.html' file into the WebView as an HTML string with 'baseURL' (set to www.bundle path) to enable loading relative image links.
NSString *mainBundlePath = [[NSBundle mainBundle] resourcePath];
NSString *wwwBundlePath = [mainBundlePath stringByAppendingPathComponent:@"www.bundle"];
NSBundle *wwwBundle = [NSBundle bundleWithPath:wwwBundlePath];
if (wwwBundle != nil) {
NSURL *baseURL = [NSURL fileURLWithPath:[wwwBundle bundlePath]];
NSError *error = nil;
NSString *page = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSString *pageSource = [NSString stringWithContentsOfFile:page encoding:NSUTF8StringEncoding error:&error];
[self.webView loadHTMLString:pageSource baseURL:baseURL];
}
1-liner, takes a XML string text
and YourType
as the expected object type. not very different from other answers, just compressed to 1 line:
var result = (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));
The APPLY operator in SQL 2005 and higher works for this:
select
t.id ,
t.somedate ,
t.somevalue ,
rt.runningTotal
from TestTable t
cross apply (select sum(somevalue) as runningTotal
from TestTable
where somedate <= t.somedate
) as rt
order by t.somedate
When you read from a binary file, a data type called bytes is used. This is a bit like list or tuple, except it can only store integers from 0 to 255.
Try:
file_size = fin.read(4)
file_size0 = file_size[0]
file_size1 = file_size[1]
file_size2 = file_size[2]
file_size3 = file_size[3]
Or:
file_size = list(fin.read(4))
Instead of:
file_size = int(fin.read(4))
np.append needs the array as the first argument and the list you want to append as the second:
mean_data = np.append(mean_data, [ur, ua, np.mean(data[samepoints,-1])])
You can use commercial tools like Sisulizer. It will create satellite assembly for each language. Only thing you should pay attention is not to obfuscate form class names (if you use obfuscator).
While the EGit plugin for Eclipse is a good option, an even better one would be to learn to use git bash -- i.e., git from the command line. It isn't terribly difficult to learn the very basics of git, and it is often very beneficial to understand some basic operations before relying on a GUI to do it for you. But to answer your question:
First things first, download git from http://git-scm.com/. Then go to http://github.com/ and create an account and repository.
On your machine, first you will need to navigate to the project folder using git bash. When you get there you do:
git init
which initiates a new git repository in that directory.
When you've done that, you need to register that new repo with a remote (where you'll upload -- push -- your files to), which in this case will be github. This assumes you have already created a github repository. You'll get the correct URL from your repo in GitHub.
git remote add origin https://github.com/[username]/[reponame].git
You need to add you existing files to your local commit:
git add . # this adds all the files
Then you need to make an initial commit, so you do:
git commit -a -m "Initial commit" # this stages your files locally for commit.
# they haven't actually been pushed yet
Now you've created a commit in your local repo, but not in the remote one. To put it on the remote, you do the second line you posted:
git push -u origin --all
Recently I've been in a trouble with Visual Studio 2012 with same error description: "The process cannot access the file because it is being used by another process..."
To fix this first of all you need to understand the application which still use it. I've shutdown all processes like "MSBuild" and "MSBuild host". But this is not enough. If you have installed "Code Contracts" and turned on then it sometimes takes your DLLs for checking and hanging up on this operation.
So, you need to stop all processes of "CCCheck.exe" and that's all.
Finally, to understand that process is using your DLL you always may try to just Delete "obj" folder in your File Manager and this operation will fail, you may see the "Message Window" with description of the hanging operation. Also, as a variant, you can try to use "Sys Internals Suite" application.
You could also mount a local directory into your docker image and source the script in your .bashrc
. Don't forget the script has to consist of functions unless you want it to execute on every new shell. (This is outdated see the update notice.)
I'm using this solution to be able to update the script outside of the docker instance. This way I don't have to rerun the image if changes occur, I just open a new shell. (Got rid of reopening a shell - see the update notice)
Here is how you bind your current directory:
docker run -it -v $PWD:/scripts $my_docker_build /bin/bash
Now your current directory is bound to /scripts
of your docker instance.
(Outdated)
To save your .bashrc
changes commit your working image with this command:
docker commit $container_id $my_docker_build
To solve the issue to open up a new shell for every change I now do the following:
In the dockerfile itself I add RUN echo "/scripts/bashrc" > /root/.bashrc"
. Inside zshrc
I export the scripts directory to the path. The scripts directory now contains multiple files instead of one. Now I can directly call all scripts without having open a sub shell on every change.
BTW you can define the history file outside of your container too. This way it's not necessary to commit on a bash change anymore.
You can just use the query directly within the remove function, so:
FBFriendModel.remove({ id: 333}, function(err){});
I had this issue in Android Studio 3.1 :
I only have on board graphics. Went to Tools -> AVD Manager -> (Edit this AVD) under Actions -> Emulated Performance (Graphics): select "Software GLES 2.0".
Long story short: Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.
A few tips in order
npm install typescript -g
If it still doesn't work run npm config get prefix
to see where npm install -g is putting files (append bin
to the output) and make sure that they are in the path (the node js setup does this. Maybe you forgot to tick that option).
Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.
Unfortunately, it is in the com.android.internal.preference
package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).
Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).
You can then add it to your preferences.xml
like any other Preference. Example:
<com.example.myapp.YesNoPreference
android:dialogMessage="Are you sure you want to revert all settings to their default values?"
android:key="com.example.myapp.pref_reset_settings_key"
android:summary="Revert all settings to their default values."
android:title="Reset Settings" />
Which looks like this:
To be clear: The accepted answer is correct. Try it first. However, it may be unnecessarily complex for some use cases, particularly if you encounter obnoxious errors such as 'fatal: bad revision --prune-empty', or really don't care about the history of your repo.
An alternative would be:
This will of course remove all commit history branches, and issues from both your github repo, and your local git repo. If this is unacceptable you will have to use an alternate approach.
Call this the nuclear option.
I have used an emulator for API Level 23, which does not take keyboard input for installed apk. So I have created new emulator for API Level 29, and then it works. Following is the step to install new emulator.
An alternative approach would be to "emulate" bold text via text-shadow. This has the bonus (/malus, depending on your case) to work also on font icons.
nav li a:hover {
text-decoration: none;
text-shadow: 0 0 1px; /* "bold" */
}
Kinda hacky, although it saves you from duplicating text (which is useful if it is a lot, as it was in my case).
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String cunvertCurrentDate="06/09/2015";
Date date = new Date();
date = df.parse(cunvertCurrentDate);
This is what I found as I was plotting only 3 cells from each 4 columns lumped together. My chart has a merged cell with the date which is my x axis. The problem: BC26-BE27 are plotting as ZERO on my chart. enter image description here
I click on the filter on the side of the chart and found where it is showing all the columns for which the data points are charted. I unchecked the boxes that do not have values. enter image description here
It worked for me.
class Program
{
Variable va = new Variable();
static void Main(string[] args)
{
va.name = "Stackoverflow";
}
}
It only worked for me in Firefox when accessing it from the window
object.
Example...
window.onload = function()
{
window.localStorage.clear();
}
This indicates the linux has delivered a SIGTERM
to your process. This is usually at the request of some other process (via kill()
) but could also be sent by your process to itself (using raise()
). This signal requests an orderly shutdown of your process.
If you need a quick cheatsheet of signal numbers, open a bash shell and:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
You can determine the sender by using an appropriate signal handler like:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
info->si_pid);
exit(0);
}
int main (void)
{
struct sigaction action = {
.sa_handler = NULL,
.sa_sigaction = sigterm_handler,
.sa_mask = 0,
.sa_flags = SA_SIGINFO,
.sa_restorer = NULL
};
sigaction(SIGTERM, &action, NULL);
sleep(60);
return 0;
}
Notice that the signal handler also includes a call to exit()
. It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).
int count = -1;
String[] content = new String[200];
while(inFile1.hasNext()){
content[++count] = inFile1.nextLine();
}
EDIT
Looks like you want to create a float array, for that create a float array
int count = -1;
Float[] content = new Float[200];
while(inFile1.hasNext()){
content[++count] = Float.parseFloat(inFile1.nextLine());
}
then your float array would look like
content[0] = 70.3
content[1] = 70.8
content[2] = 73.8
content[3] = 77.0 and so on
As Tyler points out, there's no way to do what you require "directly and reliably", since a given FD may correspond to 0 filenames (in various cases) or > 1 (multiple "hard links" is how the latter situation is generally described). If you do still need the functionality with all the limitations (on speed AND on the possibility of getting 0, 2, ... results rather than 1), here's how you can do it: first, fstat the FD -- this tells you, in the resulting struct stat
, what device the file lives on, how many hard links it has, whether it's a special file, etc. This may already answer your question -- e.g. if 0 hard links you will KNOW there is in fact no corresponding filename on disk.
If the stats give you hope, then you have to "walk the tree" of directories on the relevant device until you find all the hard links (or just the first one, if you don't need more than one and any one will do). For that purpose, you use readdir (and opendir &c of course) recursively opening subdirectories until you find in a struct dirent
thus received the same inode number you had in the original struct stat
(at which time if you want the whole path, rather than just the name, you'll need to walk the chain of directories backwards to reconstruct it).
If this general approach is acceptable, but you need more detailed C code, let us know, it won't be hard to write (though I'd rather not write it if it's useless, i.e. you cannot withstand the inevitably slow performance or the possibility of getting != 1 result for the purposes of your application;-).
You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-
last_list.append(p.last)
if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.
Mount the certs onto the Docker container using -v
:
docker run -v /host/path/to/certs:/container/path/to/certs -d IMAGE_ID "update-ca-certificates"
Yes, window.onfocus
and window.onblur
should work for your scenario:
http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
There is one characteristic about inline-block which may not be straight-forward though. That is that the default value for vertical-align in CSS is baseline. This may cause some unexpected alignment behavior. Look at this article.
http://www.brunildo.org/test/inline-block.html
Instead, when you do a float:left, the divs are independent of each other and you can align them using margin easily.
This tends to happen particularly with vscode as I'd assume because of how one configures the launch.json
.
Based on this answer I had to reconfigure the base path the configuration is being searched for to that of DLL's path, and since the default setting was optional it was hard to track this down on a .net core 3.1 & net 5.0 app. Here's how I've reconfigured
Program.cs
:
using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace API
{
public class Program
{
public static int Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
return 0;
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(c =>
{
var codeBase = Assembly.GetExecutingAssembly().Location;
var uri = new UriBuilder(codeBase);
var path = Uri.UnescapeDataString(uri.Path);
var assembyDirectory = Path.GetDirectoryName(path);
c.SetBasePath(assembyDirectory);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
;
}
}
}
I could access the configuration fine in Startup.cs
:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Model;
namespace API
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var myOptions = Configuration.To<ApiConfig>();
services.AddAuthentication(myOptions.Secret);
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}
Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.
As a very blunt hammer, useful for testing, you can use the enable_seqscan
and enable_indexscan
parameters. See:
These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_
params and walk away.
Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?
See also this old newsgroup post.
Another option would be to use a procedure with output parameters - Using a Stored Procedure with Output Parameters
You can use like bellow:
(( var0 = var1<98?9:21 ))
the same as
if [ "$var1" -lt 98 ]; then
var0=9
else
var0=21
fi
extends
condition?result-if-true:result-if-false
I found the interested thing on the book "Advanced Bash-Scripting Guide"
Following code shows how to upload a file to a SFTP server using our Rebex SFTP component.
// create client, connect and log in
Sftp client = new Sftp();
client.Connect(hostname);
client.Login(username, password);
// upload the 'test.zip' file to the current directory at the server
client.PutFile(@"c:\data\test.zip", "test.zip");
client.Disconnect();
You can write a complete communication log to a file using a LogWriter property as follows. Examples output (from FTP component but the SFTP output is similar) can be found here.
client.LogWriter = new Rebex.FileLogWriter(
@"c:\temp\log.txt", Rebex.LogLevel.Debug);
or intercept the communication using events as follows:
Sftp client = new Sftp();
client.CommandSent += new SftpCommandSentEventHandler(client_CommandSent);
client.ResponseRead += new SftpResponseReadEventHandler(client_ResponseRead);
client.Connect("sftp.example.org");
//...
private void client_CommandSent(object sender, SftpCommandSentEventArgs e)
{
Console.WriteLine("Command: {0}", e.Command);
}
private void client_ResponseRead(object sender, SftpResponseReadEventArgs e)
{
Console.WriteLine("Response: {0}", e.Response);
}
For more info see tutorial or download a trial and check samples.
Here's a complete working example based on your testing. Compare it to what you have currently to figure out where you are going wrong.
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(1000).fadeOut();
});
</script>
</head>
<body>
<div id=deletesuccess > hiiiiiiiiiii </div>
</body>
</html>
Using the AWS Management Console
While
constructs are terminated not with an End While
but with a Wend
.
While counter < 20
counter = counter + 1
Wend
Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.
Also in the VBA help file:
Tip The
Do...Loop
statement provides a more structured and flexible way to perform looping.
If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces
still configured for eth0.
Diagnose:
ethtool -i eth0
Cannot get driver information: no such device
Find your interfaces:
ls /sys/class/net
eth1 eth2 lo
Fix it:
Edit /etc/networking/interfaces
and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)
:%s/eth0/eth2/g
If you are on SQL Server 2008 you can also use
CRYPT_GEN_RANDOM(2) % 10000
Which seems somewhat simpler (it is also evaluated once per row as newid
is - shown below)
DECLARE @foo TABLE (col1 FLOAT)
INSERT INTO @foo SELECT 1 UNION SELECT 2
UPDATE @foo
SET col1 = CRYPT_GEN_RANDOM(2) % 10000
SELECT * FROM @foo
Returns (2 random probably different numbers)
col1
----------------------
9693
8573
Mulling the unexplained downvote the only legitimate reason I can think of is that because the random number generated is between 0-65535 which is not evenly divisible by 10,000 some numbers will be slightly over represented. A way around this would be to wrap it in a scalar UDF that throws away any number over 60,000 and calls itself recursively to get a replacement number.
CREATE FUNCTION dbo.RandomNumber()
RETURNS INT
AS
BEGIN
DECLARE @Result INT
SET @Result = CRYPT_GEN_RANDOM(2)
RETURN CASE
WHEN @Result < 60000
OR @@NESTLEVEL = 32 THEN @Result % 10000
ELSE dbo.RandomNumber()
END
END
The PowerShell is almost exactly the same.
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)
I know maybe it is unnecessary, but I made a function which converts float to string:
#include <stdio.h>
/** Number on countu **/
int n_tu(int number, int count)
{
int result = 1;
while(count-- > 0)
result *= number;
return result;
}
/*** Convert float to string ***/
void float_to_string(float f, char r[])
{
long long int length, length2, i, number, position, sign;
float number2;
sign = -1; // -1 == positive number
if (f < 0)
{
sign = '-';
f *= -1;
}
number2 = f;
number = f;
length = 0; // Size of decimal part
length2 = 0; // Size of tenth
/* Calculate length2 tenth part */
while( (number2 - (float)number) != 0.0 && !((number2 - (float)number) < 0.0) )
{
number2 = f * (n_tu(10.0, length2 + 1));
number = number2;
length2++;
}
/* Calculate length decimal part */
for (length = (f > 1) ? 0 : 1; f > 1; length++)
f /= 10;
position = length;
length = length + 1 + length2;
number = number2;
if (sign == '-')
{
length++;
position++;
}
for (i = length; i >= 0 ; i--)
{
if (i == (length))
r[i] = '\0';
else if(i == (position))
r[i] = '.';
else if(sign == '-' && i == 0)
r[i] = '-';
else
{
r[i] = (number % 10) + '0';
number /=10;
}
}
}
CTRL+SHIFT+I brings up the developers tools.
I'd probably use all.equal
and which
to get the information you want. It's not recommended to use all.equal
in an if...else
block for some reason, so we wrap it in isTRUE()
. See ?all.equal
for more:
foo <- function(A,B){
if (!isTRUE(all.equal(A,B))){
mismatches <- paste(which(A != B), collapse = ",")
stop("error the A and B does not match at the following columns: ", mismatches )
} else {
message("Yahtzee!")
}
}
And in use:
> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) :
error the A and B does not match at the following columns: 2,4
NullPointerException with JSP can also happen if:
A getter returns a non-public inner class.
This code will fail if you remove Getters's access modifier or make it private or protected.
JAVA:
package com.myPackage;
public class MyClass{
//: Must be public or you will get:
//: org.apache.jasper.JasperException:
//: java.lang.NullPointerException
public class Getters{
public String
myProperty(){ return(my_property); }
};;
//: JSP EL can only access functions:
private Getters _get;
public Getters get(){ return _get; }
private String
my_property;
public MyClass(String my_property){
super();
this.my_property = my_property;
_get = new Getters();
};;
};;
JSP
<%@ taglib uri ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
MyClass inst = new MyClass("[PROP_VALUE]");
pageContext.setAttribute("my_inst", inst );
%><html lang="en"><body>
${ my_inst.get().myProperty() }
</body></html>
Swift 5.3
let infoDictionaryKey = kCFBundleVersionKey as String
guard let currentVersion = Bundle.main.object(forInfoDictionaryKey: infoDictionaryKey) as? String
else { fatalError("Expected to find a bundle version in the info dictionary") }
Try with following:
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
sqlConn.Close();
return dt;
}
Hope it is helpful.
bootstrap 3 has a class to align the text within a div
<div class="text-right">
will align the text on the right
<div class="pull-right">
will pull to the right all the content not only the text
First off, rmaddy's answer (above) is right: implementing NSCoding
doesn't help. However, you need to implement NSCoding
to use NSKeyedArchiver
and all that, so it's just one more step... converting via NSData
.
Example methods
- (NSUserDefaults *) defaults {
return [NSUserDefaults standardUserDefaults];
}
- (void) persistObj:(id)value forKey:(NSString *)key {
[self.defaults setObject:value forKey:key];
[self.defaults synchronize];
}
- (void) persistObjAsData:(id)encodableObject forKey:(NSString *)key {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:encodableObject];
[self persistObj:data forKey:key];
}
- (id) objectFromDataWithKey:(NSString*)key {
NSData *data = [self.defaults objectForKey:key];
return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
So you can wrap your NSCoding
objects in an NSArray
or NSDictionary
or whatever...
<script type="text/javascript"
src="https://rawgithub.com/stacktracejs/stacktrace.js/master/stacktrace.js"></script>
<script type="text/javascript">
try {
// error producing code
} catch(e) {
var trace = printStackTrace({e: e});
alert('Error!\n' + 'Message: ' + e.message + '\nStack trace:\n' + trace.join('\n'));
// do something else with error
}
</script>
this script will show the error
I got recently this error and i used the solution which is proposed by @SirPaul. But the error was existing on the other configuration pages of the WordPress like update-core.php
.
The solution that i have found, which resolved all the permission problems, was to deactivate iThemes Security plugin
and update it and reactivate it.
String value = "True";
boolean result = value.equalsIgnoreCase("true") ? true : false;
Change the rule on your <a>
element from:
.navigation ul a {
color: #000;
display: block;
padding: 0 65px 0 0;
text-decoration: none;
}?
to
.navigation ul a {
color: #000;
display: block;
padding: 0 65px 0 0;
text-decoration: none;
width:100%;
text-align:center;
}?
Just add two new rules (width:100%;
and text-align:center;
). You need to make the anchor expand to take up the full width of the list item and then text-align center it.
For me
Adding this line
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
Before this line.
<script id="microloader" type="text/javascript" src=".sencha/app/microloader/development.js"></script>
worked
SELECT DATENAME(DW,CONVERT(VARCHAR(20),GETDATE(),101))
There's no way to specify a StringComparer
at the point where you try to get a value. If you think about it, "foo".GetHashCode()
and "FOO".GetHashCode()
are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.
You can, however, create a case-insensitive dictionary in the first place using:-
var comparer = StringComparer.OrdinalIgnoreCase;
var caseInsensitiveDictionary = new Dictionary<string, int>(comparer);
Or create a new case-insensitive dictionary with the contents of an existing case-sensitive dictionary (if you're sure there are no case collisions):-
var oldDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var newDictionary = new Dictionary<string, int>(oldDictionary, comparer);
This new dictionary then uses the GetHashCode()
implementation on StringComparer.OrdinalIgnoreCase
so comparer.GetHashCode("foo")
and comparer.GetHashcode("FOO")
give you the same value.
Alternately, if there are only a few elements in the dictionary, and/or you only need to lookup once or twice, you can treat the original dictionary as an IEnumerable<KeyValuePair<TKey, TValue>>
and just iterate over it:-
var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var value = myDictionary.FirstOrDefault(x => String.Equals(x.Key, myKey, comparer)).Value;
Or if you prefer, without the LINQ:-
var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
int? value;
foreach (var element in myDictionary)
{
if (String.Equals(element.Key, myKey, comparer))
{
value = element.Value;
break;
}
}
This saves you the cost of creating a new data structure, but in return the cost of a lookup is O(n) instead of O(1).
A random number is generated by some operation on previous value.
If there is no previous value then the current time is taken as previous value automatically. We can provide this previous value by own using random.seed(x)
where x
could be any number or string etc.
Hence random.random()
is not actually perfect random number, it could be predicted via random.seed(x)
.
import random
random.seed(45) #seed=45
random.random() #1st rand value=0.2718754143840908
0.2718754143840908
random.random() #2nd rand value=0.48802820785090784
0.48802820785090784
random.seed(45) # again reasign seed=45
random.random()
0.2718754143840908 #matching with 1st rand value
random.random()
0.48802820785090784 #matching with 2nd rand value
Hence, generating a random number is not actually random, because it runs on algorithms. Algorithms always give the same output based on the same input. This means, it depends on the value of the seed. So, in order to make it more random, time is automatically assigned to seed()
.
use this:for creating unique number in javascript
var uniqueNumber=(new Date().getTime()).toString(36);
It really works. :)
The $.ajax() function returns a XMLHttpRequest object. Store that in a variable that's accessible from the Submit button's "OnClick" event. When a submit click is processed check to see if the XMLHttpRequest variable is:
1) null, meaning that no request has been sent yet
2) that the readyState value is 4 (Loaded). This means that the request has been sent and returned successfully.
In either of those cases, return true and allow the submit to continue. Otherwise return false to block the submit and give the user some indication of why their submit didn't work. :)
I find that the problem only seems to happen when freeze panes is turned on, which will normally be on in most apps as you will place your command buttons etc in a location where they do not scroll out of view.
The solution that has worked for be is to group the controls but also ensuring that the group extends beyond the freeze panes area. I do this by adding a control outside the freeze panes area, add it into the group but also hide the control so you don't see it.
I'd like to add to other answers involving dropping tables and not deleting the file, that you can also execute delete from sqlite_sequence
to reset auto-increment sequences.
Floating point numbers only have so many significant digits, but they can go much higher. If your app will ever handle large numbers, you will notice the epsilon value should be different.
0.001+0.001 = 0.002 BUT 12,345,678,900,000,000,000,000+1=12,345,678,900,000,000,000,000 if you are using floating point and double. It's not a good representation of money, unless you are damn sure you'll never handle more than a million dollars in this system.
You haven't actually converted your strings to ints. Or rather, you did, but then you didn't do anything with the results. What you want is:
list1 = ["1","10","3","22","23","4","2","200"]
list1 = [int(x) for x in list1]
list1.sort()
If for some reason you need to keep strings instead of ints (usually a bad idea, but maybe you need to preserve leading zeros or something), you can use a key function. sort
takes a named parameter, key
, which is a function that is called on each element before it is compared. The key function's return values are compared instead of comparing the list elements directly:
list1 = ["1","10","3","22","23","4","2","200"]
# call int(x) on each element before comparing it
list1.sort(key=int)
Try: Window -> Preferences -> Android -> LogCat. Change field "Show logcat view if ..." the value "VERBOSE". It helped me.
The solution is to put an N in front of both the type and the SQL string to indicate it is a double-byte character string:
DECLARE @SQL NVARCHAR(100)
SET @SQL = N'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL
Try width:inherit
to make the image take the width of it's container <div>
. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>
, it will size to fit the image height.
img {
width:inherit;
}
.item {
border:1px solid pink;
width: 120px;
float: left;
margin: 3px;
padding: 3px;
}
The most efficient and cleanest way I have found to deal with this problem is by using Github Packages
Create a simple empty public/private repository on GitHub as per your requirement whether you want your external jar to be publicly hosted or not.
Run below maven command to deploy you external jar in above created github repository
mvn deploy:deploy-file \
-DgroupId= your-group-id \
-DartifactId= your-artifact-id \
-Dversion= 1.0.0 -Dpackaging= jar -Dfile= path-to-file \
-DrepositoryId= id-to-map-on-server-section-of-settings.xml \
-Durl=https://maven.pkg.github.com/github-username/github-reponame-created-in-above-step
Above command will deploy you external jar in GitHub repository mentioned in -Durl=
.
You can refer this link on How to deploy dependencies as GitHub Packages GitHub
Package Deployment Tutorial
After that you can add the dependency using groupId
,artifactId
and version
mentioned in above step in maven pom.xml
and run mvn install
Maven will fetch the dependency of external jar from GitHub Packages registry and provide in your maven project.
For this to work you will also need to configure you maven's settings.xml
to fetch from GitHub Package registry.
Robert Martin has an excellent paper on the Liskov Substitution Principle. It discusses subtle and not-so-subtle ways in which the principle may be violated.
Some relevant parts of the paper (note that the second example is heavily condensed):
A Simple Example of a Violation of LSP
One of the most glaring violations of this principle is the use of C++ Run-Time Type Information (RTTI) to select a function based upon the type of an object. i.e.:
void DrawShape(const Shape& s) { if (typeid(s) == typeid(Square)) DrawSquare(static_cast<Square&>(s)); else if (typeid(s) == typeid(Circle)) DrawCircle(static_cast<Circle&>(s)); }
Clearly the
DrawShape
function is badly formed. It must know about every possible derivative of theShape
class, and it must be changed whenever new derivatives ofShape
are created. Indeed, many view the structure of this function as anathema to Object Oriented Design.Square and Rectangle, a More Subtle Violation.
However, there are other, far more subtle, ways of violating the LSP. Consider an application which uses the
Rectangle
class as described below:class Rectangle { public: void SetWidth(double w) {itsWidth=w;} void SetHeight(double h) {itsHeight=w;} double GetHeight() const {return itsHeight;} double GetWidth() const {return itsWidth;} private: double itsWidth; double itsHeight; };
[...] Imagine that one day the users demand the ability to manipulate squares in addition to rectangles. [...]
Clearly, a square is a rectangle for all normal intents and purposes. Since the ISA relationship holds, it is logical to model the
Square
class as being derived fromRectangle
. [...]
Square
will inherit theSetWidth
andSetHeight
functions. These functions are utterly inappropriate for aSquare
, since the width and height of a square are identical. This should be a significant clue that there is a problem with the design. However, there is a way to sidestep the problem. We could overrideSetWidth
andSetHeight
[...]But consider the following function:
void f(Rectangle& r) { r.SetWidth(32); // calls Rectangle::SetWidth }
If we pass a reference to a
Square
object into this function, theSquare
object will be corrupted because the height won’t be changed. This is a clear violation of LSP. The function does not work for derivatives of its arguments.[...]
static string GetdigitFromString(string str)
{
char[] refArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] inputArray = str.ToCharArray();
string ext = string.Empty;
foreach (char item in inputArray)
{
if (refArray.Contains(item))
{
ext += item.ToString();
}
}
return ext;
}
I use the following code to get the screen dimensions
getWindow().getDecorView().getWidth()
getWindow().getDecorView().getHeight()
How many thousands of users?
I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.
Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.
If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.
Edited to add details from the comment below...
If you're already thinking of multiple servers I'd take the following approach.
Use the free tools that I link
to and prove to yourself that you
can create a reasonable number of
connections onto your target OS
(beware of the Windows limits on
dynamic ports which may cause your
client connections to fail, search
for MAX_USER_PORT
).
during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html
Hope this helps someone in the future. My problem was that I was following the same tutorial as the OP to enable global CORS. However, I also set an Action specific CORS rule in my AccountController.cs file:
[EnableCors(origins: "", headers: "*", methods: "*")]
and was getting errors about the origin cannot be null or empty string. BUT the error was happening in the Global.asax.cs file of all places. Solution is to change it to:
[EnableCors(origins: "*", headers: "*", methods: "*")]
notice the * in the origins? Missing that was what was causing the error in the Global.asax.cs file.
Hope this helps someone.
I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important
property.
HTML
<a href="#" class="selected_btn" data-role="button">Button name</a>
CSS
.selected_btn
{
border:1px solid red;
text-decoration:none;
font-family:helvetica;
color:red !important;
background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}
Here is the demo
If you just need sampling without replacement:
>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]
random.sample takes a population and a sample size k
and returns k
random members of the population.
If you have to control for the case where k
is larger than len(population)
, you need to be prepared to catch a ValueError
:
>>> try:
... random.sample(range(1, 2), 3)
... except ValueError:
... print('Sample size exceeded population size.')
...
Sample size exceeded population size
When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.
But there are more important differences on the receiving side of things. When the receiver does a recv
(or read
) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.
Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.
int.from_bytes( bytes, byteorder, *, signed=False )
doesn't work with me I used function from this website, it works well
https://coderwall.com/p/x6xtxq/convert-bytes-to-int-or-int-to-bytes-in-python
def bytes_to_int(bytes):
result = 0
for b in bytes:
result = result * 256 + int(b)
return result
def int_to_bytes(value, length):
result = []
for i in range(0, length):
result.append(value >> (i * 8) & 0xff)
result.reverse()
return result
If you are using a third party library called apache commons-lang, the following solution can be useful:
Use StringUtils
class of apache commons-lang :
int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"
As StringUtils.leftPad()
is faster than String.format()
Try with this code:
InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
Many people prefer to use just .keep
since the convention has nothing to do with git.
Here is an alternative tr based solution that doesn't use echo, expressed as a one-liner.
for v in $(tr ',' '\n' <<< "$var") ; do something_with "$v" ; done
It feels tidier without echo but that is just my personal preference.
try {
String result = URLDecoder.decode(urlString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Name2 is a field. WPF binds only to properties. Change it to:
public string Name2 { get; set; }
Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:
partial class Window1 : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string _name2;
public string Name2
{
get { return _name2; }
set
{
if (value != _name2)
{
_name2 = value;
OnPropertyChanged("Name2");
}
}
}
}
You should consider moving this to a separate data object rather than on your Window class.
The above Answer solves our problem but in addition to that. if we are trying to decompress a uncompressed("not a zip format") byte[] . we will get "Not in GZIP format" exception message.
For solving that we can add addition code in our Class.
public static boolean isCompressed(final byte[] compressed) {
return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}
My Complete Compression Class with compress/decompress would look like:
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPCompression {
public static byte[] compress(final String str) throws IOException {
if ((str == null) || (str.length() == 0)) {
return null;
}
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(str.getBytes("UTF-8"));
gzip.flush();
gzip.close();
return obj.toByteArray();
}
public static String decompress(final byte[] compressed) throws IOException {
final StringBuilder outStr = new StringBuilder();
if ((compressed == null) || (compressed.length == 0)) {
return "";
}
if (isCompressed(compressed)) {
final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
outStr.append(line);
}
} else {
outStr.append(compressed);
}
return outStr.toString();
}
public static boolean isCompressed(final byte[] compressed) {
return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}
}
You can simply use loop of enumeration to get your desired result:
Swift 2:
for (index, element) in elements.enumerate() {
print("\(index): \(element)")
}
Swift 3 & 4:
for (index, element) in elements.enumerated() {
print("\(index): \(element)")
}
Or you can simply go through a for loop to get the same result:
for index in 0..<elements.count {
let element = elements[index]
print("\(index): \(element)")
}
Hope it helps.
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
Your code works well you just mistyped this line of code:
document.getElementbyId('lc').appendChild(element);
change it with this: (The "B" should be capitalized.)
document.getElementById('lc').appendChild(element);
HERE IS MY EXAMPLE:
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
var element = document.createElement("div");_x000D_
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();"> _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Just develop a normal app and then add a couple of lines to the app's manifest file.
First you need to add the following attribute to your activity:
android:launchMode="singleTask"
Then add two categories to the intent filter :
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
The result could look something like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dummy.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.dummy.app.MainActivity"
android:launchMode="singleTask"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</activity>
</application>
</manifest>
It's that simple!
Visual Studio 2017 Debug symbol "speed-up" options, assuming you haven't gone crazy on option-customization already:
Tools -> Options -> Debugging -> Symbols
C:\dbg_symbols
or %USERPROFILE%\dbg_symbols
1A and 2 are the most important steps. 1B and 1C are just helpful changes to help you keep track of your symbols.
After your app has loaded all the symbols at least once and debugging didn't prematurely terminate, those symbols should be quickly loaded the next time debug runs.
I've noticed that if I cancel a debug-run, I have to reload those symbols, as I'm guessing they're "cleaned" up if newly introduced and suddenly cancelled. I understand the core rationale for that kind of flow, but in this case it seems poorly thought out.
The process can differ depending on where and how the video is being hosted. Knowing that can help to answer the question in more detail.
As an example; this is how you can download videos with blob links on Vimeo.
Setting LeftBarButton with Original Image.
let menuButton = UIBarButtonItem(image: UIImage(named: "imagename").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(classname.functionname))
self.navigationItem.leftBarButtonItem = menuButton
It truly solved my problem using eval function.
single_quoted_dict_in_string = "{'key':'value', 'key2': 'value2'}"
desired_double_quoted_dict = eval(single_quoted_dict_in_string)
# Go ahead, now you can convert it into json easily
print(desired_double_quoted_dict)
It's already 2017, and you can now use Apache Commons Collections4
The usage:
for(Object obj : ListUtils.emptyIfNull(list1)){
// Do your stuff
}
You can do the same null-safe check to other Collection classes with CollectionUtils.emptyIfNull
.
Once you get the command line tools loaded as described by Nikos M in his excellent answer above you will need to agree to the gcc license and if you are using ruby gems you may need to link llvm-gcc as gcc-4.2.
If you do not do these the gem install will report "You have to install development tools first." after you have already installed them.
The steps are:
sudo gcc
sudo ln -s /usr/bin/llvm-gcc /usr/bin/gcc-4.2
The gcc must be run once under sudo so Apple can update their license info, you don't need an input file, it will update the license before it checks its arguments. The link is needed so that ruby 1.9 can find the compiler when building certain gems, such as the debugger. This may be fixed in ruby 2.x, but I'll cross that bridge when I get there.
Numpy is required by pandas (and by virtually all numerical tools for Python). Scipy is not strictly required for pandas but is listed as an "optional dependency". I wouldn't say that pandas is an alternative to Numpy and/or Scipy. Rather, it's an extra tool that provides a more streamlined way of working with numerical and tabular data in Python. You can use pandas data structures but freely draw on Numpy and Scipy functions to manipulate them.
I had this issue too, after following this guide, it was simply 1 additional patch that was required to get past the
Rule "Prior Visual Studio 2010 instances requiring update." failed.
Was to locate this file, and patch my machine
VS10sp1-KB983509.msp
Simply do a file search on the installation media for SQL Server 2012, in my case it was in \redist\VisualStudioShell (whereas in the guide it's listed as being in a different location).
Then hit 're-run'.
This is my solution that adjusts the height automatically:
function growDiv() {_x000D_
var growDiv = document.getElementById('grow');_x000D_
if (growDiv.clientHeight) {_x000D_
growDiv.style.height = 0;_x000D_
} else {_x000D_
var wrapper = document.querySelector('.measuringWrapper');_x000D_
growDiv.style.height = wrapper.clientHeight + "px";_x000D_
}_x000D_
document.getElementById("more-button").value = document.getElementById("more-button").value == 'Read more' ? 'Read less' : 'Read more';_x000D_
}
_x000D_
#more-button {_x000D_
border-style: none;_x000D_
background: none;_x000D_
font: 16px Serif;_x000D_
color: blue;_x000D_
margin: 0 0 10px 0;_x000D_
}_x000D_
_x000D_
#grow input:checked {_x000D_
color: red;_x000D_
}_x000D_
_x000D_
#more-button:hover {_x000D_
color: black;_x000D_
}_x000D_
_x000D_
#grow {_x000D_
-moz-transition: height .5s;_x000D_
-ms-transition: height .5s;_x000D_
-o-transition: height .5s;_x000D_
-webkit-transition: height .5s;_x000D_
transition: height .5s;_x000D_
height: 0;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<input type="button" onclick="growDiv()" value="Read more" id="more-button">_x000D_
_x000D_
<div id='grow'>_x000D_
<div class='measuringWrapper'>_x000D_
<div class="text">Here is some more text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae urna nulla. Vivamus a purus mi. In hac habitasse platea dictumst. In ac tempor quam. Vestibulum eleifend vehicula ligula, et cursus nisl gravida sit_x000D_
amet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</div>_x000D_
</div>_x000D_
</div>
_x000D_
I used the workaround that r3bel posted: Can you use CSS3 to transition from height:0 to the variable height of content?
I had this same problem, using an old version of the route-me library. I "skipped" all the libraries, and the libraries inside of libraries (proj4), but I still had the same problem. Turns out that route-me and proj4 were installing public header files, even when the libraries were being skipped, which was messing it up in the same way! So I just went into the route-me and proj4 targets "Build Phases" tab, opened "Copy Headers", opened "Public", and dragged those headers from "Public" into "Project". Now they don't get installed in $(BUILD)/usr/local/include, and I'm able to make an ipa file from the archive!
I hope Apple fixes this horrible usability problem with XCode. It gives absolutely no indication of what's wrong, it just doesn't work. I hate dimmed out controls that don't tell you anything about why they're dimmed out. How about instead of ignoring clicks, the disabled controls could pop up a message telling you why the hell they're disabled when you click on them in frustration?
TryParse is usually the most elegant way to handle this type of thing:
long temp = 0;
if (Int64.TryParse(dataAccCom.GetParameterValue(IDbCmd, "op_Id").ToString(), out temp))
{
DataTO.Id = temp;
}
To replace a character at a specific index, the function is as follows:
def replace_char(s , n , c):
n-=1
s = s[0:n] + s[n:n+1].replace(s[n] , c) + s[n+1:]
return s
where s is a string, n is index and c is a character.
PHP array_walk() function is specifically for altering array.
Try this:
array_walk ( $data, function (&$key) {
$key["transaction_date"] = date('d/m/Y',$key["transaction_date"]);
});
Try This
string path = @"c:\mytext.txt";
if (File.Exists(path))
{
File.Delete(path);
}
{ // Consider File Operation 1
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
StreamWriter str = new StreamWriter(fs);
str.BaseStream.Seek(0, SeekOrigin.End);
str.Write("mytext.txt.........................");
str.WriteLine(DateTime.Now.ToLongTimeString() + " " +
DateTime.Now.ToLongDateString());
string addtext = "this line is added" + Environment.NewLine;
str.Flush();
str.Close();
fs.Close();
// Close the Stream then Individually you can access the file.
}
File.AppendAllText(path, addtext); // File Operation 2
string readtext = File.ReadAllText(path); // File Operation 3
Console.WriteLine(readtext);
In every File Operation, The File will be Opened and must be Closed prior Opened. Like wise in the Operation 1 you must Close the File Stream for the Further Operations.
Using the sh module (pip install sh):
from sh import tail
# runs forever
for line in tail("-f", "/var/log/some_log_file.log", _iter=True):
print(line)
[update]
Since sh.tail with _iter
=True is a generator, you can:
import sh
tail = sh.tail("-f", "/var/log/some_log_file.log", _iter=True)
Then you can "getNewData" with:
new_data = tail.next()
Note that if the tail buffer is empty, it will block until there is more data (from your question it is not clear what you want to do in this case).
[update]
This works if you replace -f with -F, but in Python it would be locking. I'd be more interested in having a function I could call to get new data when I want it, if that's possible. – Eli
A container generator placing the tail call inside a while True loop and catching eventual I/O exceptions will have almost the same effect of -F.
def tail_F(some_file):
while True:
try:
for line in sh.tail("-f", some_file, _iter=True):
yield line
except sh.ErrorReturnCode_1:
yield None
If the file becomes inaccessible, the generator will return None. However it still blocks until there is new data if the file is accessible. It remains unclear for me what you want to do in this case.
Raymond Hettinger approach seems pretty good:
def tail_F(some_file):
first_call = True
while True:
try:
with open(some_file) as input:
if first_call:
input.seek(0, 2)
first_call = False
latest_data = input.read()
while True:
if '\n' not in latest_data:
latest_data += input.read()
if '\n' not in latest_data:
yield ''
if not os.path.isfile(some_file):
break
continue
latest_lines = latest_data.split('\n')
if latest_data[-1] != '\n':
latest_data = latest_lines[-1]
else:
latest_data = input.read()
for line in latest_lines[:-1]:
yield line + '\n'
except IOError:
yield ''
This generator will return '' if the file becomes inaccessible or if there is no new data.
[update]
The second to last answer circles around to the top of the file it seems whenever it runs out of data. – Eli
I think the second will output the last ten lines whenever the tail process ends, which with -f
is whenever there is an I/O error. The tail --follow --retry
behavior is not far from this for most cases I can think of in unix-like environments.
Perhaps if you update your question to explain what is your real goal (the reason why you want to mimic tail --retry), you will get a better answer.
The last answer does not actually follow the tail and merely reads what's available at run time. – Eli
Of course, tail will display the last 10 lines by default... You can position the file pointer at the end of the file using file.seek, I will left a proper implementation as an exercise to the reader.
IMHO the file.read() approach is far more elegant than a subprocess based solution.
try this:
$("table#myTable tr").last().after(data);
When there is a need to restrict access to some functions, we'll use the static keyword while defining and declaring a function.
/* file ab.c */
static void function1(void)
{
puts("function1 called");
}
And store the following code in another file ab1.c
/* file ab1.c */
int main(void)
{
function1();
getchar();
return 0;
}
/* in this code, we'll get a "Undefined reference to function1".Because function 1 is declared static in file ab.c and can't be used in ab1.c */
To verify whether is your pip
installation problem, try using easy_install
to install an earlier version of pip:
easy_install pip==9.0.1
If this succeed, pip
should be working now. Then you can go ahead to install any other version of pip
you want with:
pip install pip==10....
Or you can just stay with version 9.0.1
, as your project requires version >= 9.0.
Try building your project again.
This still appears to be an issue, causing package installations to be aborted with warnings about optional packages no being installed because of "Unsupported platform".
The problem relates to the "shrinkwrap" or package-lock.json
which gets persisted after every package manager execution. Subsequent attempts keep failing as this file is referenced instead of package.json
.
Adding these options to the npm install
command should allow packages to install again.
--no-optional argument will prevent optional dependencies from being installed.
--no-shrinkwrap argument, which will ignore an available package lock or
shrinkwrap file and use the package.json instead.
--no-package-lock argument will prevent npm from creating a package-lock.json file.
The complete command looks like this:
npm install --no-optional --no-shrinkwrap --no-package-lock
nJoy!
You need to create your own Prompt dialog. You could perhaps create a class for this.
public static class Prompt
{
public static string ShowDialog(string text, string caption)
{
Form prompt = new Form()
{
Width = 500,
Height = 150,
FormBorderStyle = FormBorderStyle.FixedDialog,
Text = caption,
StartPosition = FormStartPosition.CenterScreen
};
Label textLabel = new Label() { Left = 50, Top=20, Text=text };
TextBox textBox = new TextBox() { Left = 50, Top=50, Width=400 };
Button confirmation = new Button() { Text = "Ok", Left=350, Width=100, Top=70, DialogResult = DialogResult.OK };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
}
}
And calling it:
string promptValue = Prompt.ShowDialog("Test", "123");
Update:
Added default button (enter key) and initial focus based on comments and another question.
NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
For example, you could read your cube directly from a file into an array:
x = numpy.fromfile(file=open("data"), dtype=float).reshape((100, 100, 100))
Sum along the second dimension:
s = x.sum(axis=1)
Find which cells are above a threshold:
(x > 0.5).nonzero()
Remove every even-indexed slice along the third dimension:
x[:, :, ::2]
Also, many useful libraries work with NumPy arrays. For example, statistical analysis and visualization libraries.
Even if you don't have performance problems, learning NumPy is worth the effort.
You can also plot to a png file using gnuplot (which is free):
terminal commands
gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'
note: you always need to give the right extension (.png here) at set output
Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:
plot '<Fromfile.csv>' with line lt -1 lw 2
More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html
apt-get install gnuplot
)brew install gnuplot
)I have fast solution. Just create a file ArrayUtil.java
import java.util.ArrayList;
import java.util.Collection;
import org.json.JSONArray;
import org.json.JSONException;
public class ArrayUtil
{
public static ArrayList<Object> convert(JSONArray jArr)
{
ArrayList<Object> list = new ArrayList<Object>();
try {
for (int i=0, l=jArr.length(); i<l; i++){
list.add(jArr.get(i));
}
} catch (JSONException e) {}
return list;
}
public static JSONArray convert(Collection<Object> list)
{
return new JSONArray(list);
}
}
Usage:
ArrayList<Object> list = ArrayUtil.convert(jArray);
or
JSONArray jArr = ArrayUtil.convert(list);
In js you can change zoom by
document.body.style.zoom="90%"
But it doesn't work in FF http://caniuse.com/#search=zoom
For ff you can try
-moz-transform: scale(0.9);
And check next topic How can I zoom an HTML element in Firefox and Opera?
Try this:
$Object = 'FirstPart SecondPart' | ConvertFrom-String -PropertyNames Val1, Val2
$Object.Val1
$Object.Val2
I ran into a similar problem while creating a library to handle authentication. I want the app owner using my library to be able to register a callback with the library for checking authorization against LDAP groups the authenticated person is in. The configuration is getting passed in as a config.py file that gets imported and contains a dict with all the config parameters.
I got this to work:
>>> class MyClass(object):
... def target_func(self):
... print "made it!"
...
... def __init__(self,config):
... self.config = config
... self.config['funcname'] = getattr(self,self.config['funcname'])
... self.config['funcname']()
...
>>> instance = MyClass({'funcname':'target_func'})
made it!
Is there a pythonic-er way to do this?
values, counts = np.unique(words, return_counts=True)
By default, Valgrind writes its output to stderr. So you need to do something like:
valgrind a.out > log.txt 2>&1
Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).
1· Do I need these DLL's?
It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.
- Where can I get them?
most dlls can be found at https://www.dll-files.com
I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll
For me leshims.dll
can be placed at C:\Windows\System32\
. Context: windows 7 64bit.
Here are the steps:
Hope this helps
/* Hide scrollbar for Chrome, Safari and Opera */
::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
html {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
I was trying on a release build via adb install -r -d <app-release>.apk
Make sure you're running the debug build, then the menu will work via the shortcut or CLI.
You can programmatically get the image and check the dimensions using Javascript...
const img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
_x000D_
This can be useful if the image is not a part of the markup.
You can use this for check modify date of functions
and stored procedures
together ordered by date :
SELECT 'Stored procedure' as [Type] ,name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
UNION all
Select 'Function' as [Type],name, create_date, modify_date
FROM sys.objects
WHERE type = 'FN'
ORDER BY modify_date DESC
or :
SELECT type ,name, create_date, modify_date
FROM sys.objects
WHERE type in('P','FN')
ORDER BY modify_date DESC
-- this one shows type like : FN for function and P for stored procedure
Result will be like this :
Type | name | create_date | modify_date
'Stored procedure' | 'firstSp' | 2018-08-04 07:36:40.890 | 2019-09-05 05:18:53.157
'Stored procedure' | 'secondSp' | 2017-10-15 19:39:27.950 | 2019-09-05 05:15:14.963
'Function' | 'firstFn' | 2019-09-05 05:08:53.707 | 2019-09-05 05:08:53.707
Just like to contribute that the above answers of :not() can be very effective in angular forms, rather than creating effects or adjusting the view/DOM,
input.ng-invalid:not(.ng-pristine) { ... your css here i.e. border-color: red; ...}
Ensures that on loading your page, the input fields will only show the invalid (red borders or backgrounds, etc) if they have data added (i.e. no longer pristine) but are invalid.
Try using the WebConfigurationManager class instead. For example:
string userName = WebConfigurationManager.AppSettings["PFUserName"]
input[type='checkbox', name='ProductCode']
That's the CSS way and I'm almost sure it will work in jQuery.