2018 edit: I think this answer has some interesting info, but for any practical applications you should use Joe's answer instead.
A simple way to create a unique ID in JavaScript is to use the Date object:
var uniqid = Date.now();
That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.
The problem with that value now is that you cannot use it as an element's ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.
var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
var uniqid = randLetter + Date.now();
This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.
Parse the Id as it would be string and then add.
e.g.
$('.load_more').live("click",function() { //When user clicks
var newcurrentpageTemp = parseInt($(this).attr("id")) + 1;//Get the id from the hyperlink
alert(newcurrentpageTemp);
dosomething();
});
The simplest syntax to redirect both is:
command &> logfile
If you want to append to the file instead of overwrite:
command &>> logfile
1 ) Copy the initialAdminPassword in Specified path.
2 ) Login with following Credentials
User Name : admin
Password : <da12906084fd405090a9fabfd66342f0>
3 ) Once you login into the jenkins application you can click on admin profile and reset the password.
As explained in "Deleting your master branch" by Matthew Brett, you need to change your GitHub repo default branch.
You need to go to the GitHub page for your forked repository, and click on the “Settings” button.
Click on the "Branches" tab on the left hand side. There’s a “Default branch” dropdown list near the top of the screen.
From there, select placeholder (where placeholder is the dummy name for your new default branch).
Confirm that you want to change your default branch.
Now you can do (from the command line):
git push origin :master
Or, since 2012, you can delete that same branch directly on GitHub:
That was announced in Sept. 2013, a year after I initially wrote that answer.
For small changes like documentation fixes, typos, or if you’re just a walking software compiler, you can get a lot done in your browser without needing to clone the entire repository to your computer.
Note: for BitBucket, Tum reports in the comments:
About the same for Bitbucket
Repo -> Settings -> Repository details -> Main branch
There's this, from SQL Server DMV's In Action book:
The output shows the spid (process identifier), the ecid (this is similar to a thread within the same spid and is useful for identifying queries running in parallel), the user running the SQL, the status (whether the SQL is running or waiting), the wait status (why it’s waiting), the hostname, the domain name, and the start time (useful for determining how long the batch has been running).
The nice part is the query and parent query. That shows, for example, a stored proc as the parent and the query within the stored proc that is running. It has been very handy for me. I hope this helps someone else.
USE master
GO
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
er.session_Id AS [Spid]
, sp.ecid
, er.start_time
, DATEDIFF(SS,er.start_time,GETDATE()) as [Age Seconds]
, sp.nt_username
, er.status
, er.wait_type
, SUBSTRING (qt.text, (er.statement_start_offset/2) + 1,
((CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE er.statement_end_offset
END - er.statement_start_offset)/2) + 1) AS [Individual Query]
, qt.text AS [Parent Query]
, sp.program_name
, sp.Hostname
, sp.nt_domain
FROM sys.dm_exec_requests er
INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
WHERE session_Id > 50
AND session_Id NOT IN (@@SPID)
ORDER BY session_Id, ecid
If you're interested in the physical RAM, use the command dmidecode
. It gives you a lot more information than just that, but depending on your use case, you might also want to know if the 8G in the system come from 2x4GB sticks or 4x2GB sticks.
Top can be compiled from sources or downloaded from sunfreeware.com. As previously posted, vmstat is available (I believe it's in the core install?).
Try this out.
<iframe src="https://docs.google.com/viewerng/viewer?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" frameborder="0" height="100%" width="100%">_x000D_
</iframe>
_x000D_
See this article for a longer discussion of named actions. It also shows that you can use the [HttpGet] attribute instead of prefixing the action name with "get".
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
There's some proposition over the web (and this page) to use ViewConfiguration.getScaledTouchSlop() to have a device-scaled value for SWIPE_MIN_DISTANCE
.
getScaledTouchSlop()
is intended for the "scrolling threshold" distance, not swipe. The scrolling threshold distance has to be smaller than a "swing between page" threshold distance. For example, this function returns 12 pixels on my Samsung GS2, and the examples quoted in this page are around 100 pixels.
With API Level 8 (Android 2.2, Froyo), you've got getScaledPagingTouchSlop()
, intended for page swipe.
On my device, it returns 24 (pixels). So if you're on API Level < 8, I think "2 * getScaledTouchSlop()
" should be the "standard" swipe threshold.
But users of my application with small screens told me that it was too few... As on my application, you can scroll vertically, and change page horizontally. With the proposed value, they sometimes change page instead of scrolling.
You can write an object to a file using writeObject
in ObjectOutputStream
To gain access for other users to your local machine, i usually use ngrok. Ngrok exposes your localhost to the web, and has an NPM wrapper that is simple to install and start:
$ npm install ngrok -g
$ ngrok http 3000
See this example usage:
In the above example, the locally running instance of sails at: localhost:3000 is now available on the Internet served at: http://69f8f0ee.ngrok.io or https://69f8f0ee.ngrok.io
The new annotation @JsonIgnoreProperties resolves many of the issues with the other options.
@Entity
public class Material{
...
@JsonIgnoreProperties("costMaterials")
private List<Supplier> costSuppliers = new ArrayList<>();
...
}
@Entity
public class Supplier{
...
@JsonIgnoreProperties("costSuppliers")
private List<Material> costMaterials = new ArrayList<>();
....
}
Check it out here. It works just like in the documentation:
http://springquay.blogspot.com/2016/01/new-approach-to-solve-json-recursive.html
Just comment out "Defaults env_reset" in /etc/sudoers
Something like this
<html>
<body style="height:100%; width:100%">
<div id="header" style="position:absolute; top:0px; left:0px; height:200px; right:0px;overflow:hidden;">
</div>
<div id="content" style="position:absolute; top:200px; bottom:200px; left:0px; right:0px; overflow:auto;">
</div>
<div id="footer" style="position:absolute; bottom:0px; height:200px; left:0px; right:0px; overflow:hidden;">
</div>
</body>
</html>
I think the following code allow to use super.super...super.method() in most case. (even if it's uggly to do that)
In short
Usage :
public class A {
public void doThat() { ... }
}
public class B extends A {
public void doThat() { /* don't call super.doThat() */ }
}
public class C extends B {
public void doThat() {
Magic.exec(A.class, this, "doThat");
}
}
public class Magic {
public static <Type, ChieldType extends Type> void exec(Class<Type> oneSuperType, ChieldType instance,
String methodOfParentToExec) {
try {
Type type = oneSuperType.newInstance();
shareVars(oneSuperType, instance, type);
oneSuperType.getMethod(methodOfParentToExec).invoke(type);
shareVars(oneSuperType, type, instance);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static <Type, SourceType extends Type, TargetType extends Type> void shareVars(Class<Type> clazz,
SourceType source, TargetType target) throws IllegalArgumentException, IllegalAccessException {
Class<?> loop = clazz;
do {
for (Field f : loop.getDeclaredFields()) {
if (!f.isAccessible()) {
f.setAccessible(true);
}
f.set(target, f.get(source));
}
loop = loop.getSuperclass();
} while (loop != Object.class);
}
}
I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:
Under Conditional Formatting > Manage Rules:
$A2<$B2
$B$2:$B$100
(assuming you have 100 rows)This worked for me in Excel 2016.
Yes, there is: you can capture the echo
ed text using ob_start
:
<?php function TestBlockHTML($replStr) {
ob_start(); ?>
<html>
<body><h1><?php echo($replStr) ?></h1>
</html>
<?php
return ob_get_clean();
} ?>
I would change the implementation slightly:
First, I create a UnknownMatchException
:
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UnknownMatchException extends RuntimeException {
public UnknownMatchException(String matchId) {
super("Unknown match: " + matchId);
}
}
Note the use of @ResponseStatus, which will be recognized by Spring's ResponseStatusExceptionResolver
. If the exception is thrown, it will create a response with the corresponding response status. (I also took the liberty of changing the status code to 404 - Not Found
which I find more appropriate for this use case, but you can stick to HttpStatus.BAD_REQUEST
if you like.)
Next, I would change the MatchService
to have the following signature:
interface MatchService {
public Match findMatch(String matchId);
}
Finally, I would update the controller and delegate to Spring's MappingJackson2HttpMessageConverter
to handle the JSON serialization automatically (it is added by default if you add Jackson to the classpath and add either @EnableWebMvc
or <mvc:annotation-driven />
to your config, see the reference docs):
@RequestMapping(value = "/matches/{matchId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Match match(@PathVariable String matchId) {
// throws an UnknownMatchException if the matchId is not known
return matchService.findMatch(matchId);
}
Note, it is very common to separate the domain objects from the view objects or DTO objects. This can easily be achieved by adding a small DTO factory that returns the serializable JSON object:
@RequestMapping(value = "/matches/{matchId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public MatchDTO match(@PathVariable String matchId) {
Match match = matchService.findMatch(matchId);
return MatchDtoFactory.createDTO(match);
}
Just center the div in HTML:
#test {
width: 100px;
height:100px;
margin: 0px auto;
border: 1px solid red;
}
<div id="test">
<canvas width="100" height="100"></canvas>
</div>
Just change the height and width to whatever and you've got a centered div
I think this is what the original poster meant to accomplish:
var array_of_functions = [
function() { first_function('a string') },
function() { second_function('a string') },
function() { third_function('a string') },
function() { fourth_function('a string') }
]
for (i = 0; i < array_of_functions.length; i++) {
array_of_functions[i]();
}
Hopefully this will help others (like me 20 minutes ago :-) looking for any hint about how to call JS functions in an array.
Your debut
and fin
values are floating point values, not integers, because taille
is a float.
Make those values integers instead:
item = plateau[int(debut):int(fin)]
Alternatively, make taille
an integer:
taille = int(sqrt(len(plateau)))
I see this is a little old, but there might be a better solution here.
When you want a string, but you want the string to only match certain values, you can use enums.
For example:
enum Fruit {
Orange = "Orange",
Apple = "Apple",
Banana = "Banana"
}
let myFruit: Fruit = Fruit.Banana;
Now you'll know that no matter what, myFruit will always be the string "Banana" (Or whatever other enumerable value you choose). This is useful for many things, whether it be grouping similar values like this, or mapping user-friendly values to machine-friendly values, all while enforcing and restricting the values the compiler will allow.
On OSX the following works from the command line:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-running-insecure-content
<div style="width:300px; text-align:right;">
<img src="someimgage.gif">
</div>
On the Linux system you can do following (Should be similar for other OS)
Check if mysql process is running:
sudo service mysql status
If runnning then stop the process: (Make sure you close all mysql tool)
sudo service mysql stop
If you have issue stopping then do following
Search for process: ps aux | grep mysqld
Kill the process: kill -9 process_id
Now start mysql in safe mode with skip grant
sudo mysqld_safe --skip-grant-tables &
It depends on what you are trying to return. I used this recently:
return text.match(/[a-z]/i);
The term you should be googling is "authoritative," not "definitive".
On Linux or Mac you can use the commands whois
, dig
, host
, nslookup
or several others. nslookup
might also work on Windows.
An example:
$ whois stackoverflow.com
[...]
Domain servers in listed order:
NS51.DOMAINCONTROL.COM
NS52.DOMAINCONTROL.COM
As for the extra credit: Yes, it is possible.
aryeh is definitely wrong, as his suggestion usually will only give you the IP address for the hostname. If you use dig
, you have to look for NS records, like so:
dig ns stackoverflow.com
Keep in mind that this may ask your local DNS server and thus may give wrong or out-of-date answers that it has in its cache.
The same can be done without DataTrigger
too:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" >
<Setter.Value>
<Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
<Binding.ConverterParameter>
<x:Array Type="SolidColorBrush">
<SolidColorBrush Color="{StaticResource RedColor}"/>
<SolidColorBrush Color="{StaticResource TransparentColor}"/>
</x:Array>
</Binding.ConverterParameter>
</Binding>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowStyle>
Where BooleanToBrushConverter
is the following class:
public class BooleanToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return Brushes.Transparent;
Brush[] brushes = parameter as Brush[];
if (brushes == null)
return Brushes.Transparent;
bool isTrue;
bool.TryParse(value.ToString(), out isTrue);
if (isTrue)
{
var brush = (SolidColorBrush)brushes[0];
return brush ?? Brushes.Transparent;
}
else
{
var brush = (SolidColorBrush)brushes[1];
return brush ?? Brushes.Transparent;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
You can now use the npm package sequelize-auto-migrations to automatically generate a migrations file. https://www.npmjs.com/package/sequelize-auto-migrations
Using sequelize-cli, initialize your project with
sequelize init
Create your models and put them in your models folder.
Install sequelize-auto-migrations:
npm install sequelize-auto-migrations
Create an initial migration file with
node ./node_modules/sequelize-auto-migrations/bin/makemigration --name <initial_migration_name>
Run your migration:
node ./node_modules/sequelize-auto-migrations/bin/runmigration
You can also automatically generate your models from an existing database, but that is beyond the scope of the question.
I would use du
's --threshold
for this. Not sure if this option is available in all versions of du
but it is implemented in GNU's version.
Quoting from du(1)'s manual:
-t, --threshold=SIZE
exclude entries smaller than SIZE if positive, or entries greater
than SIZE if negative
Here's my solution, using du --threshold=
for OP's use case:
THRESHOLD=90k
if [[ -z "$(du --threshold=${THRESHOLD} file.txt)" ]]; then
mail -s "file.txt size is below ${THRESHOLD}, please fix. " [email protected] < /dev/null
mv -f /root/tmp/file.txt /var/www/file.txt
fi
The advantage of that, is that du
can accept an argument to that option in a known format - either human as in 10K
, 10MiB
or what ever you feel comfortable with - you don't need to manually convert between formats / units since du
handles that.
For reference, here's the explanation on this SIZE
argument from the man page:
The SIZE argument is an integer and optional unit (example: 10K is
10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers
of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on.
You could raise SystemExit(0)
instead of going to all the trouble to import sys; sys.exit(0)
.
For below Spring boot 2 version you need to use below code
server:
context-path: abc
And For Spring boot 2+ version use below code
server:
servlet:
context-path: abc
You need to Enable security and set the security realm on the Configure Global Security page (see: Standard Security Setup) and choose the appropriate Authorization method (Security Realm).
Depending on your selection, create the user using appropriate method. Recommended method is to select Jenkins’ own user database and tick Allow users to sign up, hit Save button, then you should be able to create user from the Jenkins interface. Otherwise if you've chosen external database, you need to create the user there (e.g. if it's Unix database, use credentials of existing Linux/Unix users or create a standard user using shell interface).
See also: Creating user in Jenkins via API
Angular 7/8
As of angular 6,the use of ngModel input property with reactive forms directive have been deprecated and removed altogether in angular 7+. Read official doc here.
Using reactive form approach you can get/set selected data as;
//in your template
<select formControlName="person" (change)="onChange($event)"class="form-control">
<option [value]="null" disabled>Choose person</option>
<option *ngFor="let person of persons" [value]="person">
{{person.name}}
</option>
</select>
//in your ts
onChange($event) {
let person = this.peopleForm.get("person").value
console.log("selected person--->", person);
// this.peopleForm.get("person").setValue(person.id);
}
While @Timar's answer works perfectly for null
default values (what was asked for), here another easy solution which allows other default values: Define an option interface as well as an according constant containing the defaults; in the constructor use the spread operator to set the options
member variable
interface IXOptions {
a?: string,
b?: any,
c?: number
}
const XDefaults: IXOptions = {
a: "default",
b: null,
c: 1
}
export class ClassX {
private options: IXOptions;
constructor(XOptions: IXOptions) {
this.options = { ...XDefaults, ...XOptions };
}
public printOptions(): void {
console.log(this.options.a);
console.log(this.options.b);
console.log(this.options.c);
}
}
Now you can use the class like this:
const x = new ClassX({ a: "set" });
x.printOptions();
Output:
set
null
1
Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
in Mysql Doku: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract
SELECT EXTRACT( YEAR_MONTH FROM `date` )
FROM `Table` WHERE Condition = 'Condition';
this.http.get<any>('http://192.168.1.15:4000/GetPriority')
.subscribe(response =>
{
this.records=JSON.stringify(response) // impoprtant
console.log("records"+this.records)
});
If you do not need to use JavaHL, Subclipse also provides a pure-Java SVN API library -- SVNKit (http://svnkit.com). Just install the SVNKit client adapter and library plugins from the Subclipse update site and then choose it in the preferences under Team > SVN.
You could use Java reflection to do this. The method would be represented as an instance of java.lang.reflect.Method.
import java.lang.reflect.Method;
public class Demo {
public static void main(String[] args) throws Exception{
Class[] parameterTypes = new Class[1];
parameterTypes[0] = String.class;
Method method1 = Demo.class.getMethod("method1", parameterTypes);
Demo demo = new Demo();
demo.method2(demo, method1, "Hello World");
}
public void method1(String message) {
System.out.println(message);
}
public void method2(Object object, Method method, String message) throws Exception {
Object[] parameters = new Object[1];
parameters[0] = message;
method.invoke(object, parameters);
}
}
I can give a small hack, you can use T-SQL function. Try this:
SELECT ID, PARSENAME(WebsiteName, 2)
FROM dbo.YourTable .....
Here's another possible reason besides the console.log
issue (at least in IE11):
When the console is not open, IE does pretty aggressive caching, so make sure that any $.ajax
calls or XMLHttpRequest
calls have caching set to false.
For example:
$.ajax({cache: false, ...})
When the developer console is open, caching is less aggressive. Seems to be a bug (or maybe a feature?)
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
3# Simple scrolling library on Github
You're close. This should do the trick:
new {items = new [] {
new {name = "command" , index = "X", optional = "0"},
new {name = "command" , index = "X", optional = "0"}
}}
If your source was an enumerable of some sort, you might want to do this:
new {items = source.Select(item => new
{
name = item.Name, index = item.Index, options = item.Optional
})};
You must modify the query like this
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))
INSERT INTO #TMPGUARDIAN(FRST_NAME,LAST_NAME)
SELECT LAST_NAME,FRST_NAME FROM TBL_PEOPLE
-- Make a last session for clearing the all temporary tables. always drop at end. In your case, sometimes, there might be an error happen if the table is not exists, while you trying to delete.
DROP TABLE #TMPGUARDIAN
Avoid using insert into Because If you are using insert into then in future if you want to modify the temp table by adding a new column which can be filled after some process (not along with insert). At that time, you need to rework and design it in the same manner.
Use Table Variable http://odetocode.com/articles/365.aspx
declare @userData TABLE(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30)
)
Advantages No need for Drop statements, since this will be similar to variables. Scope ends immediately after the execution.
I see that you’re trying to export SQL data to Excel to avoid copy-pasting your very large data set into Excel.
You might be interested in learning how to export SQL data to Excel and update the export automatically (with any SQL database: MySQL, Microsoft SQL Server, PostgreSQL).
?
What about
now()::timestamp
If your other timestamp are without time zone then this cast will yield the matching type "timestamp without time zone" for the current time.
I would like to read what others think about that option, though. I still don't trust in my understanding of this "with/without" time zone stuff.
EDIT: Adding Michael Ekoka's comment here because it clarifies an important point:
Caveat. The question is about generating default timestamp in UTC for a timestamp column that happens to not store the time zone (perhaps because there's no need to store the time zone if you know that all your timestamps share the same). What your solution does is to generate a local timestamp (which for most people will not necessarily be set to UTC) and store it as a naive timestamp (one that does not specify its time zone).
I have the same exact error message while I was doing my unit test and throwing observable exception after mocking my services.
I resolved it by passing exact function and format inside Observable.throw
.
Actual code which calls the service and subscribe
to get data. notice that catch
to handle the 400
error.
this.search(event).catch((e: Response) => {
if (e.status === 400) {
console.log(e.json().message);
} else if (e.url) {
console.log('HTTP Error: ' + e.status + ' ' + e.statusText,
'URL: ' + e.url, 'Info: ' + e.json().message));
}
}).finally(() => {
this.loading = false;
}).subscribe((bData) => {
this.data = bData;
});
The code inside the service
search() {
return this.someService.getData(request)
.do((r) => {
this.someService.defaultHeaders.delete('skipAlert');
return r;
})
.map((r) => {
return r.businessObjectDataElements.length && r.businessObjectDataElements || null;
});
}
I have mocked the SomeService and returning observable data and its fine as it have all the required methods inside it.
someServiceApi = fixture.debugElement.injector.get(SomeService);
spyOn(someServiceApi, 'getData').and.returnValue(Observable.of({}));
The above code is okey but when when I was trying to test the catch/error condition by passing Observable.throw({})
it was showing me the error as it was expecting Response
type return from the service.
So below service mocking return was giving me that error.
someServiceApi.getData
.and.returnValue(Observable.throw(new Response({status: 400, body: [], message: 'not found error'})));
So I Corrected it by replicating the exact expected function in my return object rather passing a Response
type value.
someServiceApi.getData
.and.returnValue(Observable.throw({status: 400, json: () => { return {message: 'not found error'}}, body: []}));
// see `json: () => { return {message: 'not found error'}}` inside return value
First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows
Then, you should copy php_mcrypt.dll
to ../xampp/php/ext/
and enable the extension by adding extension=mcrypt
to your xampp/php/php.ini
file.
A patch is little more (see below) than a series of instructions: "add this here", "remove that there", "change this third thing to a fourth". That's why git tells you:
The copy of the patch that failed is found in: c:/.../project2/.git/rebase-apply/patch
You can open that patch in your favorite viewer or editor, open the files-to-be-changed in your favorite editor, and "hand apply" the patch, using what you know (and git does not) to figure out how "add this here" is to be done when the files-to-be-changed now look little or nothing like what they did when they were changed earlier, with those changes delivered to you as a patch.
A three-way merge introduces that "little more" information than the plain "series of instructions": it tells you what the original version of the file was as well. If your repository has the original version, your git can compare what you did to a file, to what the patch says to do to the file.
As you saw above, if you request the three-way merge, git can't find the "original version" in the other repository, so it can't even attempt the three-way merge. As a result you get no conflict markers, and you must do the patch-application by hand.
--reject
When you have to apply the patch by hand, it's still possible that git can apply most of the patch for you automatically and leave only a few pieces to the entity with the ability to reason about the code (or whatever it is that needs patching). Adding --reject
tells git to do that, and leave the "inapplicable" parts of the patch in rejection files. If you use this option, you must still hand-apply each failing patch, and figure out what to do with the rejected portions.
Once you have made the required changes, you can git add
the modified files and use git am --continue
to tell git to commit the changes and move on to the next patch.
Since we don't have your code, I can't tell if this is the case, but sometimes, you wind up with one of the patches saying things that amount to, e.g., "fix the spelling of a word on line 42" when the spelling there was already fixed.
In this particular case, you, having looked at the patch and the current code, should say to yourself: "aha, this patch should just be skipped entirely!" That's when you use the other advice git already printed:
If you prefer to skip this patch, run "git am --skip" instead.
If you run git am --skip
, git will skip over that patch, so that if there were five patches in the mailbox, it will end up adding just four commits, instead of five (or three instead of five if you skip twice, and so on).
Okay, how about a CSS answer! We use display: table
. Then each of the divs are rows, and finally we apply height of 100% to middle 'row' and voilà.
body { display: table; }
div { display: table-row; }
#content {
width:450px;
margin:0 auto;
text-align: center;
background-color: blue;
color: white;
height: 100%;
}
This code capitalize words after dot:
function capitalizeAfterPeriod(input) {
var text = '';
var str = $(input).val();
text = convert(str.toLowerCase().split('. ')).join('. ');
var textoFormatado = convert(text.split('.')).join('.');
$(input).val(textoFormatado);
}
function convert(str) {
for(var i = 0; i < str.length; i++){
str[i] = str[i].split('');
if (str[i][0] !== undefined) {
str[i][0] = str[i][0].toUpperCase();
}
str[i] = str[i].join('');
}
return str;
}
It's hard to say what your question is, but there are some alternatives.
If you mean to literally execute a request using the ICMP ping protocol, you can get an ICMP library and execute the ping request directly. Google "Python ICMP" to find things like this icmplib. You might want to look at scapy, also.
This will be much faster than using os.system("ping " + ip )
.
If you mean to generically "ping" a box to see if it's up, you can use the echo protocol on port 7.
For echo, you use the socket library to open the IP address and port 7. You write something on that port, send a carriage return ("\r\n"
) and then read the reply.
If you mean to "ping" a web site to see if the site is running, you have to use the http protocol on port 80.
For or properly checking a web server, you use urllib2 to open a specific URL. (/index.html
is always popular) and read the response.
There are still more potential meaning of "ping" including "traceroute" and "finger".
I specifically wanted to use the same function that I was using for arrays for a single object, and wanted to keep it simple. This worked for me:
var mapped = [item].map(myMapFunction).pop();
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
Andrey Tarasevich provides the following explanation:
[Minor changes to formatting made. Parenthetical annotations added in square brackets []
].
The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.
Consider the following code sketch:
if (<condition>) foo(a); else bar(a);
where
foo
andbar
are ordinary functions. Now imagine that you'd like to replace functionfoo
with a macro of the above nature [namedCALL_FUNCS
]:if (<condition>) CALL_FUNCS(a); else bar(a);
Now, if your macro is defined in accordance with the second approach (just
{
and}
) the code will no longer compile, because the 'true' branch ofif
is now represented by a compound statement. And when you put a;
after this compound statement, you finished the wholeif
statement, thus orphaning theelse
branch (hence the compilation error).One way to correct this problem is to remember not to put
;
after macro "invocations":if (<condition>) CALL_FUNCS(a) else bar(a);
This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:
#define CALL_FUNCS(x) \ do { \ func1(x); \ func2(x); \ func3(x); \ } while (0)
Now this code:
if (<condition>) CALL_FUNCS(a); else bar(a);
will compile without any problems.
However, note the small but important difference between my definition of
CALL_FUNCS
and the first version in your message. I didn't put a;
after} while (0)
. Putting a;
at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.I don't know why the author of the code you quoted in your original message put this
;
afterwhile (0)
. In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final;
into the macro (for the reasons that I explained above).
I got this error when I tried assigning a component property to a state property during instantiation
export default {
props: ['value1'],
data() {
return {
value2: this.value1 // throws the error
}
},
created(){
this.value2 = this.value1 // safe
}
}
It would be fine to use query parameters on a POST endpoint, provided they refer to already existing resources.
For example:
POST /user_settings?user_id=4
{
"use_safe_mode": 1
}
The POST above has a query parameter referring to an existing resource. The body parameter defines the new resource to be created.
(Granted, this may be more of a personal preference than a dogmatic principle.)
This only applies to question 1.
I have an app that runs on Windows and uses a multi-line MFC editor box.
The editor box expects CRLF linebreaks, but I need to parse the text enterred
with some really big/nasty regexs'.
I didn't want to be stressing about this while writing the regex, so
I ended up normalizing back and forth between the parser and editor so that
the regexs' just use \n
. I also trap paste operations and convert them for the boxes.
This does not take much time.
This is what I use.
boost::regex CRLFCRtoLF (
" \\r\\n | \\r(?!\\n) "
, MODx);
boost::regex CRLFCRtoCRLF (
" \\r\\n?+ | \\n "
, MODx);
// Convert (All style) linebreaks to linefeeds
// ---------------------------------------
void ReplaceCRLFCRtoLF( string& strSrc, string& strDest )
{
strDest = boost::regex_replace ( strSrc, CRLFCRtoLF, "\\n" );
}
// Convert linefeeds to linebreaks (Windows)
// ---------------------------------------
void ReplaceCRLFCRtoCRLF( string& strSrc, string& strDest )
{
strDest = boost::regex_replace ( strSrc, CRLFCRtoCRLF, "\\r\\n" );
}
Can you use date as a factor?
Yes, but you probably shouldn't.
...or should you use
as.Date
on a date column?
Yes.
Which leads us to this:
library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) +
geom_bar(stat = "identity") +
theme_bw() +
labs(x = "Month", y = "Average Visits per User") +
scale_x_date(labels = date_format("%m-%Y"))
in which I've added stat = "identity"
to your geom_bar
call.
In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
Don't rescue Exception => e
(and not re-raise the exception) - or you might drive off a bridge.
Let's say you are in a car (running Ruby). You recently installed a new steering wheel with the over-the-air upgrade system (which uses eval
), but you didn't know one of the programmers messed up on syntax.
You are on a bridge, and realize you are going a bit towards the railing, so you turn left.
def turn_left
self.turn left:
end
oops! That's probably Not Good™, luckily, Ruby raises a SyntaxError
.
The car should stop immediately - right?
Nope.
begin
#...
eval self.steering_wheel
#...
rescue Exception => e
self.beep
self.log "Caught #{e}.", :warn
self.log "Logged Error - Continuing Process.", :info
end
beep beep
Warning: Caught SyntaxError Exception.
Info: Logged Error - Continuing Process.
You notice something is wrong, and you slam on the emergency breaks (^C
: Interrupt
)
beep beep
Warning: Caught Interrupt Exception.
Info: Logged Error - Continuing Process.
Yeah - that didn't help much. You're pretty close to the rail, so you put the car in park (kill
ing: SignalException
).
beep beep
Warning: Caught SignalException Exception.
Info: Logged Error - Continuing Process.
At the last second, you pull out the keys (kill -9
), and the car stops, you slam forward into the steering wheel (the airbag can't inflate because you didn't gracefully stop the program - you terminated it), and the computer in the back of your car slams into the seat in front of it. A half-full can of Coke spills over the papers. The groceries in the back are crushed, and most are covered in egg yolk and milk. The car needs serious repair and cleaning. (Data Loss)
Hopefully you have insurance (Backups). Oh yeah - because the airbag didn't inflate, you're probably hurt (getting fired, etc).
But wait! There's more reasons why you might want to use rescue Exception => e
!
Let's say you're that car, and you want to make sure the airbag inflates if the car is exceeding its safe stopping momentum.
begin
# do driving stuff
rescue Exception => e
self.airbags.inflate if self.exceeding_safe_stopping_momentum?
raise
end
Here's the exception to the rule: You can catch Exception
only if you re-raise the exception. So, a better rule is to never swallow Exception
, and always re-raise the error.
But adding rescue is both easy to forget in a language like Ruby, and putting a rescue statement right before re-raising an issue feels a little non-DRY. And you do not want to forget the raise
statement. And if you do, good luck trying to find that error.
Thankfully, Ruby is awesome, you can just use the ensure
keyword, which makes sure the code runs. The ensure
keyword will run the code no matter what - if an exception is thrown, if one isn't, the only exception being if the world ends (or other unlikely events).
begin
# do driving stuff
ensure
self.airbags.inflate if self.exceeding_safe_stopping_momentum?
end
Boom! And that code should run anyways. The only reason you should use rescue Exception => e
is if you need access to the exception, or if you only want code to run on an exception. And remember to re-raise the error. Every time.
Note: As @Niall pointed out, ensure always runs. This is good because sometimes your program can lie to you and not throw exceptions, even when issues occur. With critical tasks, like inflating airbags, you need to make sure it happens no matter what. Because of this, checking every time the car stops, whether an exception is thrown or not, is a good idea. Even though inflating airbags is a bit of an uncommon task in most programming contexts, this is actually pretty common with most cleanup tasks.
I used these two lines of code in application tag in manifest.xml and it worked.
tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"
Source: https://github.com/android/android-ktx/issues/576#issuecomment-437145192
I use them sparingly, but they can be pretty convenient:
def log(msg):
log.logfile.write(msg)
Now I can use log
throughout my module, and redirect output simply by setting log.logfile
. There are lots and lots of other ways to accomplish that, but this one's lightweight and dirt simple. And while it smelled funny the first time I did it, I've come to believe that it smells better than having a global logfile
variable.
You mistyped the set
command – you missed the backslash after C:
. It should be:
C:\>set path=C:\Program Files (x86)\Java\jdk1.7.0\bin
You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.
Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)
follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html
make a parent div, in css make it float:right then make the child div's position fixed this will make the div stay in its position at all times and on the right
Building on @Valentyn's answer a bit, here's one way to always automatically clear the cache whenever the ng-view content changes:
myApp.run(function($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function() {
$templateCache.removeAll();
});
});
Personally, I quite like the C++2011 approach because it neither requires you to use sizeof()
nor to remember adjusting the array bounds if you ever change the array bounds (and you can define the relevant function in C++2003 if you want, too):
#include <iterator>
#include <vector>
int x[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(std::begin(x), std::end(x));
Obviously, with C++2011 you might want to use initializer lists anyway:
std::vector<int> v({ 1, 2, 3, 4, 5 });
Disabling/setting read-only for all children controls in a container control. I needed to do this because some of the children controls were containers themselves.
public static void SetReadOnly(Control ctrl, bool readOnly)
{
//set the control read only
SetControlReadOnly(ctrl, readOnly);
if (ctrl.Controls != null && ctrl.Controls.Count > 0)
{
//recursively loop through all child controls
foreach (Control c in ctrl.Controls)
SetReadOnly(c, readOnly);
}
}
In your public View getView
method change return null;
to return convertView;
.
After trying a number of options and running into various issue with newer versions of Excel (2016) I came across this post from MS that worked like a charm. I enhanced it bit using some code from a post by danwagner.co
Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (Guid As GUID_TYPE) As LongPtr
Private Declare PtrSafe Function StringFromGUID2 Lib "ole32.dll" (Guid As GUID_TYPE, ByVal lpStrGuid As LongPtr, ByVal cbMax As Long) As LongPtr
Function CreateGuidString(Optional IncludeHyphens As Boolean = True, Optional IncludeBraces As Boolean = False)
Dim Guid As GUID_TYPE
Dim strGuid As String
Dim retValue As LongPtr
Const guidLength As Long = 39 'registry GUID format with null terminator {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
retValue = CoCreateGuid(Guid)
If retValue = 0 Then
strGuid = String$(guidLength, vbNullChar)
retValue = StringFromGUID2(Guid, StrPtr(strGuid), guidLength)
If retValue = guidLength Then
' valid GUID as a string
' remove them from the GUID
If Not IncludeHyphens Then
strGuid = Replace(strGuid, "-", vbNullString, Compare:=vbTextCompare)
End If
' If IncludeBraces is switched from the default False to True,
' leave those curly braces be!
If Not IncludeBraces Then
strGuid = Replace(strGuid, "{", vbNullString, Compare:=vbTextCompare)
strGuid = Replace(strGuid, "}", vbNullString, Compare:=vbTextCompare)
End If
CreateGuidString = strGuid
End If
End If
End Function
Public Sub TestCreateGUID()
Dim Guid As String
Guid = CreateGuidString() '<~ default
Debug.Print Guid
End Sub
There are additional options in the original MS post found here: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_excel-msoffice_custom-mso_2010/guid-run-time-error-70-permission-denied/c9ee4076-98af-4032-bc87-40ad7aa7cb38
You can use SoapUI: http://www.soapui.org/ This is a generally handy program. Make a new project, connect to the WSDL link, then right click on the project and say "Show interface viewer". Under "Schemas" on the left you can see the XSD.
SoapUI can do many things though!
In case your json file does not have a script to stop the app, an option that I use is just by pressing ctrl+C on the cmd.
I think this would be a more simpler way of outputting your results.
Sorry for using my own data should be easy to replace .
$query = "SELECT * FROM category ";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo $cat_id . " " . $cat_title ."<br>";
}
This would output :
You are using .index()
which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0)
will always return 2
, no matter how many times 1.0
occurs in the list.
Use enumerate()
to add indices to your loop instead:
def find(lst, a, b):
result = []
for i, x in enumerate(lst):
if x<a or x>b:
result.append(i)
return result
You can collapse this into a list comprehension:
def find(lst, a, b):
return [i for i, x in enumerate(lst) if x<a or x>b]
I would give a min-height and min-width to your overlay div of the size of the image, and change the background color on hover
.overlay { position: absolute; top: 0; left: 0; z-index: 200; min-height:200px; min-width:200px; background-color: none;}
.overlay:hover { background-color: red;}
If you are considering creating a function, try this: DECLARE @schema sysname = 'dbo' , @tablename sysname = 'mvtEST' , @cmd NVarchar(2000) , @ColName sysname
DECLARE @NewLine Table
(ColumnName Varchar(100)
,Location Int
,ColumnValue Varchar(8000)
)
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tablename AND DATA_TYPE LIKE '%CHAR%'
DECLARE looper CURSOR FAST_FORWARD for
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tablename AND DATA_TYPE LIKE '%CHAR%'
OPEN looper
FETCH NEXT FROM looper INTO @ColName
WHILE @@fetch_status = 0
BEGIN
SELECT @cmd = 'select ''' +@ColName+ ''', CHARINDEX(Char(10), '+ @ColName +') , '+ @ColName + ' from '+@schema + '.'+@tablename +' where CHARINDEX(Char(10), '+ @ColName +' ) > 0 or CHARINDEX(CHAR(13), '+@ColName +') > 0'
PRINT @cmd
INSERT @NewLine ( ColumnName, Location, ColumnValue )
EXEC sp_executesql @cmd
FETCH NEXT FROM looper INTO @ColName
end
CLOSE looper
DEALLOCATE looper
SELECT * FROM @NewLine
Go for whatever is most readable and easily maintainable. Just because you can write it out in a single line doesn't mean that you should. Your existing solution is close to what I would use other than I would user iteritems to skip the value lookup, and I hate nested ifs if I can avoid them:
for key, val in d.iteritems():
if filter_string not in key:
continue
# do something
However if you realllly want something to let you iterate through a filtered dict then I would not do the two step process of building the filtered dict and then iterating through it, but instead use a generator, because what is more pythonic (and awesome) than a generator?
First we create our generator, and good design dictates that we make it abstract enough to be reusable:
# The implementation of my generator may look vaguely familiar, no?
def filter_dict(d, filter_string):
for key, val in d.iteritems():
if filter_string not in key:
continue
yield key, val
And then we can use the generator to solve your problem nice and cleanly with simple, understandable code:
for key, val in filter_dict(d, some_string):
# do something
In short: generators are awesome.
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
if I understand correctly, the main source of error here is the exact syntax of the locale-name. Especially as it seems to differ between distributions. I've seen mentioned here in different answers/comments:
de_DE.utf8
de_DE.UTF-8
Even though this is obviously the same for a human being, the same does not hold for your standard deterministic algorithm.
So you will probably do something along the lines of:
DESIRED_LOCALE=de
DESIRED_LOCALE_COUNTRY=DE
DESIRED_CODEPAGE_RE=\.[Uu][Tt][Ff].?8
if [ $(locale -a | grep -cE "${DESIRED_LOCALE}_${DESIRED_LOCALE_COUNTRY}${DESIRED_CODEPAGE_RE}") -eq 1 ]
then
export LC_ALL=$(locale -a | grep -m1 -E "${DESIRED_LOCALE}_${DESIRED_LOCALE_COUNTRY}${DESIRED_CODEPAGE_RE}")
export LANG=$LC_ALL
else
echo "Not exactly one desired locale definition found: $(locale -a | grep -E "${DESIRED_LOCALE}_${DESIRED_LOCALE_COUNTRY}${DESIRED_CODEPAGE_RE}")" >&2
fi
In Swift 4.2 I would do something like that:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let yourVC = segue.destination as? YourViewController {
yourVC.yourData = self.someData
}
}
If you're using ViewPager
(like my case) you can use:
getSupportActionBar().setTitle(YOURE_TAB_BAR.getTabAt(position).getText());
in onPageSelected
method of your VIEW_PAGER.addOnPageChangeListener
sys.path
is only searched for Python modules. For dynamic linked libraries, the paths searched must be in LD_LIBRARY_PATH
. Check if your LD_LIBRARY_PATH
includes /usr/local/lib
, and if it doesn't, add it and try again.
Some more information (source):
In Linux, the environment variable LD_LIBRARY_PATH is a colon-separated set of directories where libraries should be searched for first, before the standard set of directories; this is useful when debugging a new library or using a nonstandard library for special purposes. The environment variable LD_PRELOAD lists shared libraries with functions that override the standard set, just as /etc/ld.so.preload does. These are implemented by the loader /lib/ld-linux.so. I should note that, while LD_LIBRARY_PATH works on many Unix-like systems, it doesn't work on all; for example, this functionality is available on HP-UX but as the environment variable SHLIB_PATH, and on AIX this functionality is through the variable LIBPATH (with the same syntax, a colon-separated list).
Update: to set LD_LIBRARY_PATH
, use one of the following, ideally in your ~/.bashrc
or equivalent file:
export LD_LIBRARY_PATH=/usr/local/lib
or
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
Use the first form if it's empty (equivalent to the empty string, or not present at all), and the second form if it isn't. Note the use of export.
You can use shuf
:
shuf -n 1 $FILE
There is also a utility called rl
. In Debian it's in the randomize-lines
package that does exactly what you want, though not available in all distros. On its home page it actually recommends the use of shuf
instead (which didn't exist when it was created, I believe). shuf
is part of the GNU coreutils, rl
is not.
rl -c 1 $FILE
Try using this attribute, for example for password min length:
[StringLength(100, ErrorMessage = "???????????? ????? ?????? 20 ????????", MinimumLength = User.PasswordMinLength)]
The first, curly braces. Otherwise, you run into consistency issues with keys that have odd characters in them, like =
.
# Works fine.
a = {
'a': 'value',
'b=c': 'value',
}
# Eeep! Breaks if trying to be consistent.
b = dict(
a='value',
b=c='value',
)
if you are using string array this is the best way:
int selectionPosition= adapter.getPosition("YOUR_VALUE");
spinner.setSelection(selectionPosition);
Microsoft is releasing the "Microsoft Edge WebView2" WPF control that will get us a great, free option for embedding Chromium across Windows 10, Windows 8.1, or Windows 7. It is available via Nuget as the package Microsoft.Web.WebView2
.
I have been using generic-pool with redis connections in my app - I highly recommend it. Its generic and I definitely know it works with mysql so I don't think you'll have any problems with it and mongo
The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.
I do it in simpler way - first install jquery by npm in console: npm install jquery -S
and then in component file I just write: let $ = require('.../jquery.min.js')
and it works! Here full example from some my code:
import { Component, Input, ElementRef, OnInit } from '@angular/core';
let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
@Component({
selector: 'departments-connections-graph',
templateUrl: './departmentsConnectionsGraph.template.html',
})
export class DepartmentsConnectionsGraph implements OnInit {
rootNode : any;
container: any;
constructor(rootNode: ElementRef) {
this.rootNode = rootNode;
}
ngOnInit() {
this.container = $(this.rootNode.nativeElement).find('.departments-connections-graph')[0];
console.log({ container : this.container});
...
}
}
In teplate I have for instance:
<div class="departments-connections-graph">something...</div>
EDIT
Alternatively instead of using:
let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
use
declare var $: any;
and in your index.html put:
<script src="assets/js/jquery-2.1.1.js"></script>
This will initialize jquery only once globaly - this is important for instance for use modal windows in bootstrap...
Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.
./manage.py shell
and only then
>>> from django.contrib.sites.models import Site
In my version of Git [1], every Git submodule has a name
and a path
. They don't necessarily have to be the same [2]. Getting both in a reliable way, without checking out the submodules first (git update --init
), is a tricky bit of shell wizardry.
names
I didn't find a way how to achieve this using git config
or any other git
command. Therefore we are back to regex on .gitmodules
(super ugly). But it seems to be somewhat safe since git
limits the possible code space allowed for submodule names
. In addition, since you probably want to use this list for further shell processing, the solution below separate entries with NULL
-bytes (\0
).
$ sed -nre \
's/^\[submodule \"(.*)\"]$/\1\x0/p' \
"$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0"
And in your script:
#!/usr/bin/env bash
while IFS= read -rd '' submodule_name; do
echo submodule name: "${submodule_name}"
done < <(
sed -nre \
's/^\[submodule \"(.*)\"]$/\1\x0/p' \
"$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0"
)
Note: read -rd ''
requires bash
and won't work with sh
.
paths
In my approach I try not to process the output from git config --get-regexp
with awk
, tr
, sed
, ... but instead pass it a zero byte separated back to git config --get
. This is to avoid problems with newlines, spaces and other special characters (e.g. Unicode) in the submodule paths
. In addition, since you probably want to use this list for further shell processing, the solution below separate entries with NULL
-bytes (\0
).
$ git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get
For example, in a Bash script you could then:
#!/usr/bin/env bash
while IFS= read -rd '' submodule_path; do
echo submodule path: "${submodule_path}"
done < <(
git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get
)
Note: read -rd ''
requires bash
and won't work with sh
.
$ git --version
git version 2.22.0
name
and path
Set up test repository:
$ git init test-name-path
$ cd test-name-path/
$ git checkout -b master
$ git commit --allow-empty -m 'test'
$ git submodule add ./ submodule-name
Cloning into '/tmp/test-name-path/submodule-name'...
done.
$ ls
submodule-name
$ cat .gitmodules
[submodule "submodule-name"]
path = submodule-name
url = ./
Move submodule to make name
and path
diverge:
$ git mv submodule-name/ submodule-path
$ ls
submodule-path
$ cat .gitmodules
[submodule "submodule-name"]
path = submodule-path
url = ./
$ git config --file .gitmodules --get-regexp '\.path$'
submodule.submodule-name.path submodule-path
Set up test repository:
$ git init test
$ cd test/
$ git checkout -b master
$ git commit --allow-empty -m 'test'
$
$ git submodule add ./ simplename
Cloning into '/tmp/test/simplename'...
done.
$
$ git submodule add ./ 'name with spaces'
Cloning into '/tmp/test/name with spaces'...
done.
$
$ git submodule add ./ 'future-name-with-newlines'
Cloning into '/tmp/test/future-name-with-newlines'...
done.
$ git mv future-name-with-newlines/ 'name
> with
> newlines'
$
$ git submodule add ./ 'name-with-unicode-'
Cloning into '/tmp/test/name-with-unicode-'...
done.
$
$ git submodule add ./ sub/folder/submodule
Cloning into '/tmp/test/sub/folder/submodule'...
done.
$
$ git submodule add ./ name.with.dots
Cloning into '/tmp/test/name.with.dots'...
done.
$
$ git submodule add ./ 'name"with"double"quotes'
Cloning into '/tmp/test/name"with"double"quotes'...
done.
$
$ git submodule add ./ "name'with'single'quotes"
Cloning into '/tmp/test/name'with'single'quotes''...
done.
$ git submodule add ./ 'name]with[brackets'
Cloning into '/tmp/test/name]with[brackets'...
done.
$ git submodule add ./ 'name-with-.path'
Cloning into '/tmp/test/name-with-.path'...
done.
.gitmodules
:
[submodule "simplename"]
path = simplename
url = ./
[submodule "name with spaces"]
path = name with spaces
url = ./
[submodule "future-name-with-newlines"]
path = name\nwith\nnewlines
url = ./
[submodule "name-with-unicode-"]
path = name-with-unicode-
url = ./
[submodule "sub/folder/submodule"]
path = sub/folder/submodule
url = ./
[submodule "name.with.dots"]
path = name.with.dots
url = ./
[submodule "name\"with\"double\"quotes"]
path = name\"with\"double\"quotes
url = ./
[submodule "name'with'single'quotes"]
path = name'with'single'quotes
url = ./
[submodule "name]with[brackets"]
path = name]with[brackets
url = ./
[submodule "name-with-.path"]
path = name-with-.path
url = ./
names
$ sed -nre \
's/^\[submodule \"(.*)\"]$/\1\x0/p' \
"$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0" \
| xargs -0 -n1 echo submodule name:
submodule name: simplename
submodule name: name with spaces
submodule name: future-name-with-newlines
submodule name: name-with-unicode-
submodule name: sub/folder/submodule
submodule name: name.with.dots
submodule name: name"with"double"quotes
submodule name: name'with'single'quotes
submodule name: name]with[brackets
submodule name: name-with-.path
paths
$ git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get \
| xargs -0 -n1 echo submodule path:
submodule path: simplename
submodule path: name with spaces
submodule path: name
with
newlines
submodule path: name-with-unicode-
submodule path: sub/folder/submodule
submodule path: name.with.dots
submodule path: name"with"double"quotes
submodule path: name'with'single'quotes
submodule path: name]with[brackets
submodule path: name-with-.path
You need to remove the static
from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard
and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new
a new instance of the IDCard
will be created and it will have it's own copies of the 3 variables.
If you use the static
keyword then those variables are common across every instance of IDCard
.
A couple of things to bear in mind:
name
not Name
.If an object's creation/existence dependents on another object which can't be tailored, its tight coupling. And, if the dependency can be tailored, its loose coupling. Consider an example in Java:
class Car {
private Engine engine = new Engine( "X_COMPANY" ); // this car is being created with "X_COMPANY" engine
// Other parts
public Car() {
// implemenation
}
}
The client of Car
class can create one with ONLY "X_COMPANY" engine.
Consider breaking this coupling with ability to change that:
class Car {
private Engine engine;
// Other members
public Car( Engine engine ) { // this car can be created with any Engine type
this.engine = engine;
}
}
Now, a Car
is not dependent on an engine of "X_COMPANY" as it can be created with types.
A Java specific note: using Java interfaces just for de-coupling sake is not a proper desing approach. In Java, an interface has a purpose - to act as a contract which intrisically provides de-coupling behavior/advantage.
Bill Rosmus's comment in accepted answer has a good explanation.
An ES6 approach to clearing a group of radio buttons:
Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
Here is a solution for Visual Studio 2017. The installer looks a littlebit different from the VS 2015 version and the name of the installation packages are different.
I think you need something like:
var text= data.response.venue.tips.groups[0].items[1].text;
Check if the file $JAVA_HOME/lib/security/cacerts
exists!
In my case it was not a file but a link to /etc/ssl/certs/java/cacerts
and also this was a link to itself (WHAT???) so due to it JVM can't find the file.
Solution:
Copy the real cacerts file (you can do it from another JDK) to /etc/ssl/certs/java/
directory and it'll solve your problem :)
You simply need to add that line legend: { display: false }
You can use the data attribute:
<div class="datepicker" data-date-start-date="+1d"></div>
You could wrap all your checkboxes in a parent class and check the length of .checked
..
if( $('.your-parent-class').find('.checked').length ){
$(".hide").toggle();
}
You'll want to use...
alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
preg_replace("/[[:blank:]]+/"," ",$input)
You are correct that the GPL is more restrictive than the MIT license.
You cannot include GPL code in a MIT licensed product. If you distribute a combined work that combines GPL and MIT code (except in some particular situations, e.g. 'mere aggregation'), that distribution must be compliant with the GPL.
You can include MIT licensed code in a GPL product. The whole combined work must be distributed in a way compliant with the GPL. If you have made changes to the MIT parts of the code, you would be required to publish the source for those changes if you distribute an application that contains GPL and MIT code.
If you are the copyright owner of the GPL code, you can of course choose to release that code under the MIT license instead - in that case it's your code and you can publish it under as many licenses as you want.
Another method: insert the following in your theme's function.php file.
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_trim_excerpt');
function custom_trim_excerpt($text) { // Fakes an excerpt if needed
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = x;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
array_push($words, '...');
$text = implode(' ', $words);
}
}
return $text;
}
You can use this.
Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.
Simple math.
double result = ((double)number) / 100.0;
Although you may want to use decimal
rather than double
: decimal vs double! - Which one should I use and when?
Use the following after the loop.
.TrimEnd(',')
or simply change to
string commaSeparatedList = input.Aggregate((a, x) => a + ", " + x)
Usage depends on whether the component's parent has a layout manager or not.
setSize()
-- use when a parent layout manager does not exist;setPreferredSize()
(also its related setMinimumSize
and setMaximumSize
) -- use when a parent layout manager exists.The setSize()
method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrame
s and JWindow
s) and things that are inside of scrolled panes. You also must call setSize()
if you've got components inside a parent without a layout manager.
Generally, setPreferredSize()
will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize()
and setLocation()
to position those components according to the layout's rules.
For example, a BorderLayout
tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame
, the size of the other components in the layout, and so on.
I had exactly the same problem right after switching off some (in my opinion unneccessary) Windows services. It turned out that when I switched ON again the "Application Experience"
everything resumed working fine.
May be you simply have to turn on this service? To switch ON Application Experience:
Click the Windows start buttonn.
In the box labeled "Search programs and files" type services.msc
and click the search button. A new window with title "Services" opens.
Right click on "Application Experience" line and select "Properties" from popup menu.
Change Startup type to "Automatic (delayed start)".
Restart computer.
Application Experiences should prevent the problem in the future.
You can't convert an integer value straight to a date but you can first it to a datetime then to a date type
select cast(40835 as datetime)
and then convert to a date (SQL 2008)
select cast(cast(40835 as datetime) as date)
cheers
Go to the XML layout Text where the widget (button or other View) indicates error, focus the cursor there and press alt+enter and select missing constraints attributes.
No, you cannot insert a div directly inside of a table. It is not correct html, and will result in unexpected output.
I would be happy to be more insightful, but you haven't said what you are attempting, so I can't really offer an alternative.
I think this is a feature currently missing right now.
I noticed when I was making a guide for the keyboard shortcut differences between it and Sublime.
It's a new editor though, I wouldn't be surprised if they added it back in a new version.
Python
As @numeral correctly said, column._jc.toString()
works fine in case of unaliased columns.
In case of aliased columns (i.e. column.alias("whatever")
) the alias can be extracted, even without the usage of regular expressions: str(column).split(" AS ")[1].split("`")[1]
.
I don't know Scala syntax, but I'm sure It can be done the same.
I have gone through all the posts above but I am convinced that the implementation of the Tournament algorithm is the best approach. Let us consider the following algorithm posted by @Gumbo
largest := numbers[0];
secondLargest := null
for i=1 to numbers.length-1 do
number := numbers[i];
if number > largest then
secondLargest := largest;
largest := number;
else
if number > secondLargest then
secondLargest := number;
end;
end;
end;
It is very good in case we are going to find the second largest number in an array. It has (2n-1) number of comparisons. But what if you want to calculate the third largest number or some kth largest number. The above algorithm doesn't work. You got to another procedure.
So, I believe tournament algorithm approach is the best and here is the link for that.
Gutch's code is close, but it'll only work right if:
The Approved Method is to do it the other way around. Open the existing document with a PdfStamper, and use the returned PdfContentByte from getOverContent() to write text (and whatever else you might need) directly to the page. No second document needed.
And you can use a ColumnText to handle layout and such for you... no need to get down and dirty with beginText(),setFontAndSize(),drawText(),drawText()...,endText().
There's an unofficial open-source API for the Android Market you may try to use to get the information you need. Hope this helps.
I was able to overcome this by using "gcc" instead of "g++" for my compiler. I know this isn't an option for most people, but thought I'd mention it as a workaround option :)
Make a Facebook app with these simple steps I have written below:
Numpy arrays do not have an append method. Use the Numpy append function instead:
import numpy as np
array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely
For example, if array_1 and array_2 have the following values:
array_1 = np.array([1, 2])
array_2 = np.array([3, 4])
If you call np.append without specifying an axis value, like so:
array_3 = np.append(array_1, array_2)
array_3 will have the following value:
array([1, 2, 3, 4])
Else, if you call np.append with an axis value of 0, like so:
array_3 = np.append(array_1, array_2, axis=0)
array_3 will have the following value:
array([[1, 2],
[3, 4]])
More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html
Adding below dependency in pom.xml, worked for me.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
You can also use NSThread
:
[NSThread sleepForTimeInterval:(NSTimeInterval)];
You can put this code in to first line of applicationDidFinishLaunching
method.
For example, display default.png for 5 seconds.
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
[NSThread sleepForTimeInterval:5.0];
}
Cory is correct
@ If you're using Eclipse PDT, this is done by opening up the PHP explorer view
I just spent about half an hour looking for the little arrow, until I actually looked up what the 'PHP Explorer' view is. Here is a screenshot:
Here's a solution with robocopy which copies the content of Folder1 into Folder2 going trough all subdirectories and automatically overwriting the files with the same name:
robocopy C:\Folder1 C:\Folder2 /COPYALL /E /IS /IT
Here:
/COPYALL
copies all file information
/E
copies subdirectories including empty directories
/IS
includes the same files
/IT
includes modified files with the same name
For more parameters see the official documentation: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy
Note: it can be necessary to run the command as administrator, because of the argument /COPYALL
. If you can't: just get rid of it.
adjust his code:
Object.prototype.each = function(iterateFunc) {
var counter = 0,
keys = Object.keys(this),
currentKey,
len = keys.length;
var that = this;
var next = function() {
if (counter < len) {
currentKey = keys[counter++];
iterateFunc(currentKey, that[currentKey]);
next();
} else {
that = counter = keys = currentKey = len = next = undefined;
}
};
next();
};
({ property1: 'sdsfs', property2: 'chat' }).each(function(key, val) {
// do things
console.log(key);
});
I found a good short method that seems to work well...
Dim x, y As Integer
x = 3: y = 5
ActiveSheet.Cells(y, x).Select
ActiveCell.Value = "Tada"
In this example we are selecting 3 columns over and 5 rows down, then putting "Tada" in the cell.
Another one-liner, without counting hyper-threaded cores:
lscpu | awk -F ":" '/Core/ { c=$2; }; /Socket/ { print c*$2 }'
NSString *url = [NSString stringWithFormat:@"https://itunes.apple.com/us/app/kidsworld/id906660185?ls=1&mt=8"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
are you parsing output of ls -l
?
If you are, and you just want to get the file name
find . -iname "*[0-9]"
If you have no choice because usrLog.txt is created by something/someone else and you absolutely must use this file, other options include
awk '/^[-d].*[0-9]$/' file
Ruby(1.9+)
ruby -ne 'print if /^[-d].*[0-9]$/' file
Bash
while read -r line ; do case $line in [-d]*[0-9] ) echo $line; esac; done < file
I like simple javascript, and I usually have jQuery around. Here's what I came up with, based off mparkuk's:
function typeInTextarea(el, newText) {
var start = el.prop("selectionStart")
var end = el.prop("selectionEnd")
var text = el.val()
var before = text.substring(0, start)
var after = text.substring(end, text.length)
el.val(before + newText + after)
el[0].selectionStart = el[0].selectionEnd = start + newText.length
el.focus()
}
$("button").on("click", function() {
typeInTextarea($("textarea"), "some text")
return false
})
Here's a demo: http://codepen.io/erikpukinskis/pen/EjaaMY?editors=101
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
You can squash (join) commits with an Interactive Rebase. There is a pretty nice YouTube video which shows how to do this on the command line or with SmartGit:
If you are already a SmartGit user then you can select all your outgoing commits (by holding down the Ctrl key) and open the context menu (right click) to squash your commits.
It's very comfortable:
There is also a very nice tutorial from Atlassian which shows how it works:
String str = new String("SOME")
always create a new object on the heap
String str="SOME"
uses the String pool
Try this small example:
String s1 = new String("hello");
String s2 = "hello";
String s3 = "hello";
System.err.println(s1 == s2);
System.err.println(s2 == s3);
To avoid creating unnecesary objects on the heap use the second form.
Just use the spread parameter to make the shadow smaller:
.shadow {_x000D_
-webkit-box-shadow: 0 6px 4px -4px black;_x000D_
-moz-box-shadow: 0 6px 4px -4px black;_x000D_
box-shadow: 0 6px 4px -4px black;_x000D_
}
_x000D_
<div class="shadow">Some content</div>
_x000D_
Live demo: http://dabblet.com/gist/a8f8ba527f5cff607327
To not see any shadow on the sides, the (absolute value of the) spread radius (4th parameter) needs to be the same as the blur radius (3rd parameter).
Check out Xtify Web Push notifications. http://getreactor.xtify.com/ This tool allows you to push content onto a webpage and target visitors as well as trigger messages based on browser DOM events. It's designed specifically with mobile in mind.
I can only assume your code came from a tutorial somewhere online? In that case, good job trying to figure it out by yourself. On the other hand, the fact that this code could actually be published online somewhere as the correct way to unzip a file is a bit frightening.
PHP has built-in extensions for dealing with compressed files. There should be no need to use system
calls for this. ZipArchive
docs is one option.
$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
$zip->extractTo('/myzips/extract_path/');
$zip->close();
echo 'woot!';
} else {
echo 'doh!';
}
Also, as others have commented, $HTTP_GET_VARS
has been deprecated since version 4.1 ... which was a reeeeeally long time ago. Don't use it. Use the $_GET
superglobal instead.
Finally, be very careful about accepting whatever input is passed to a script via a $_GET
variable.
UPDATE
As per your comment, the best way to extract the zip file into the same directory in which it resides is to determine the hard path to the file and extract it specifically to that location. So, you could do:
// assuming file.zip is in the same directory as the executing script.
$file = 'file.zip';
// get the absolute path to $file
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);
$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
// extract it to the path we determined above
$zip->extractTo($path);
$zip->close();
echo "WOOT! $file extracted to $path";
} else {
echo "Doh! I couldn't open $file";
}
Here is a small function I wrote to try all the colorschemes in $VIMRUNTIME/colors directory.
Add the below function to your vimrc, then open your source file and call the function from command.
function! DisplayColorSchemes()
let currDir = getcwd()
exec "cd $VIMRUNTIME/colors"
for myCol in split(glob("*"), '\n')
if myCol =~ '\.vim'
let mycol = substitute(myCol, '\.vim', '', '')
exec "colorscheme " . mycol
exec "redraw!"
echo "colorscheme = ". myCol
sleep 2
endif
endfor
exec "cd " . currDir
endfunction
I know this is an old post but, I've always used an updater extension method:
public static void Update<TSource>(this IEnumerable<TSource> outer, Action<TSource> updator)
{
foreach (var item in outer)
{
updator(item);
}
}
list.Where(w => w.Name == "height").ToList().Update(u => u.height = 30);
The short answer taken from the announcement of jQuery 3.0 Final Release :
Along with the regular version of jQuery that includes the ajax and effects modules, we’re releasing a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code.
The file size (gzipped) is about 6k smaller, 23.6k vs 30k.
cout << fixed << setprecision(2) << total;
setprecision
specifies the minimum precision. So
cout << setprecision (2) << 1.2;
will print 1.2
fixed
says that there will be a fixed number of decimal digits after the decimal point
cout << setprecision (2) << fixed << 1.2;
will print 1.20
Go to your java bin directory via the cmd:
C:\Program Files\Java\jdk1.7.0_25\bin>
Now type in the below comand in your cmd:
keytool -list -v -keystore "c:\users\your_user_name\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
I had the same problem and found a very elegant solution for a Pager Class from
http://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/
In your controller the call looks like:
return View(partnerList.ToPagedList(currentPageIndex, pageSize));
and in your view:
<div class="pager">
Seite: <%= Html.Pager(ViewData.Model.PageSize,
ViewData.Model.PageNumber,
ViewData.Model.TotalItemCount)%>
</div>
bundle update gem-name [--major|--patch|--minor]
This also works for dependencies.
Here is an answer based on that by Anubis (which is a better approach as it doesn't modify the headers for every request) but which is more equivalent to the code in the original question:
using Newtonsoft.Json;
...
var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://api.clickatell.com/rest/message"),
Headers = {
{ HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxx" },
{ HttpRequestHeader.Accept.ToString(), "application/json" },
{ "X-Version", "1" }
},
Content = new StringContent(JsonConvert.SerializeObject(svm))
};
var response = client.SendAsync(httpRequestMessage).Result;
I ended up recording a Macro to save and compile in one step, and keymap Ctrl+s
to it.
Another possibility for those of us uploading files as part of the request. If the content length exceeds <httpRuntime maxRequestLength="size in kilo bytes" />
and you're using request verification tokens, the browser displays the 'The required anti-forgery form field "__RequestVerificationToken" is not present'
message instead of the request length exceeded message.
Setting maxRequestLength to a value large enough to cater for the request cures the immediate issue - though I'll admit it's not a proper solution (we want the user to know the true problem of file size, not that of request verification tokens missing).
I see Federico you've found solution by yourself. The problem was in two places. Assignations need proper quoting, in your case
SOME_PATH="/$COMPANY/someProject/some path"
is one of possible solutions.
But in shell those quotes are not stored in a memory, so when you want to use this variable, you need to quote it again, for example:
NEW_VAR="$SOME_PATH"
because if not, space will be expanded to command level, like this:
NEW_VAR=/YourCompany/someProject/some path
which is not what you want.
For more info you can check out my article about it http://www.cofoh.com/white-shell
I believe you intended it more this way:
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
TaskStart.ToString("dd-MMMM-yyyy");
rpt.SetParameterValue("TaskStartDate", TaskStart);
}
}
You always accessed your first row in your dataset.
Depends on what you mean by better. This works if your goal is removal of redundancy.
s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))
On macOS Mojave with Xcode 10.3, I got scary warnings from the gem
route with or without -n /usr/local/bin
:
xcodeproj's executable "xcodeproj" conflicts with /usr/local/bin/xcodeproj
Overwrite the executable? [yN]
What works for me is still Homebrew, just
brew install cocoapods
To add new ViewController
once you have have an existing ViewController
, follow below step:
Click on background of Main.storyboard
.
Search and select ViewController
from object library at the
utility window.
Drag and drop it in background to create a new ViewController
.
merge into t2 t2
using (select * from t1) t1
on (t2.user_id = t1.user_id)
when matched then update
set
t2.c1 = t1.c1
, t2.c2 = t1.c2
I think you should use prop(), if you are using jQuery 1.6 onwards.
To check it you should do:
$('#test').prop('checked', true);
to uncheck it:
$('#test').prop('checked', false);
This is called modular exponentiation(https://en.wikipedia.org/wiki/Modular_exponentiation).
Let's assume you have the following expression:
19 ^ 3 mod 7
Instead of powering 19 directly you can do the following:
(((19 mod 7) * 19) mod 7) * 19) mod 7
But this can take also a long time due to a lot of sequential multipliations and so you can multiply on squared values:
x mod N -> x ^ 2 mod N -> x ^ 4 mod -> ... x ^ 2 |log y| mod N
Modular exponentiation algorithm makes assumptions that:
x ^ y == (x ^ |y/2|) ^ 2 if y is even
x ^ y == x * ((x ^ |y/2|) ^ 2) if y is odd
And so recursive modular exponentiation algorithm will look like this in java:
/**
* Modular exponentiation algorithm
* @param x Assumption: x >= 0
* @param y Assumption: y >= 0
* @param N Assumption: N > 0
* @return x ^ y mod N
*/
public static long modExp(long x, long y, long N) {
if(y == 0)
return 1 % N;
long z = modExp(x, Math.abs(y/2), N);
if(y % 2 == 0)
return (long) ((Math.pow(z, 2)) % N);
return (long) ((x * Math.pow(z, 2)) % N);
}
Special thanks to @chux for found mistake with incorrect return value in case of y and 0 comparison.
You can -Xours
or -Xtheirs
with git merge
as well. So:
git reset --hard HEAD
)git merge -Xours
or git merge -Xtheirs
)DISCLAIMER: of course you can choose only one option, either -Xours
or -Xtheirs
, do use different strategy you should of course go file by file.
I do not know if there is a way for checkout
, but I do not honestly think it is terribly useful: selecting the strategy with the checkout command is useful if you want different solutions for different files, otherwise just go for the merge strategy approach.
Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...
# fooz.yml
foo:
bar: <%= $ENV[:some_var] %>
No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.
If you can use the template like that or the << >>
or the {{ }}
styles depending on your reader, after that you just ...
In another yml file ...
# boo.yml
development:
fooz: foo
Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.
//basic code non strack algorithm just started learning java ignore space and time.
/// {[()]}[][]{}
// {[( -a -> }]) -b -> replace a(]}) -> reverse a( }]))->
//Split string to substring {[()]}, next [], next [], next{}
public class testbrackets {
static String stringfirst;
static String stringsecond;
static int open = 0;
public static void main(String[] args) {
splitstring("(()){}()");
}
static void splitstring(String str){
int len = str.length();
for(int i=0;i<=len-1;i++){
stringfirst="";
stringsecond="";
System.out.println("loop starttttttt");
char a = str.charAt(i);
if(a=='{'||a=='['||a=='(')
{
open = open+1;
continue;
}
if(a=='}'||a==']'||a==')'){
if(open==0){
System.out.println(open+"started with closing brace");
return;
}
String stringfirst=str.substring(i-open, i);
System.out.println("stringfirst"+stringfirst);
String stringsecond=str.substring(i, i+open);
System.out.println("stringsecond"+stringsecond);
replace(stringfirst, stringsecond);
}
i=(i+open)-1;
open=0;
System.out.println(i);
}
}
static void replace(String stringfirst, String stringsecond){
stringfirst = stringfirst.replace('{', '}');
stringfirst = stringfirst.replace('(', ')');
stringfirst = stringfirst.replace('[', ']');
StringBuilder stringfirst1 = new StringBuilder(stringfirst);
stringfirst = stringfirst1.reverse().toString();
System.out.println("stringfirst"+stringfirst);
System.out.println("stringsecond"+stringsecond);
if(stringfirst.equals(stringsecond)){
System.out.println("pass");
}
else{
System.out.println("fail");
System.exit(0);
}
}
}
My solution:
#!/bin/bash
user_cmds="$@"
GID=$(id -g $USER)
UID=$(id -u $USER)
RUN_SCRIPT=$(mktemp -p $(pwd))
(
cat << EOF
addgroup --gid $GID $USER
useradd --no-create-home --home /cmd --gid $GID --uid $UID $USER
cd /cmd
runuser -l $USER -c "${user_cmds}"
EOF
) > $RUN_SCRIPT
trap "rm -rf $RUN_SCRIPT" EXIT
docker run -v $(pwd):/cmd --rm my-docker-image "bash /cmd/$(basename ${RUN_SCRIPT})"
This allows the user to run arbitrary commands using the tools provides by my-docker-image
. Note how the user's current working directory is volume mounted
to /cmd
inside the container.
I am using this workflow to allow my dev-team to cross-compile C/C++ code for the arm64 target, whose bsp I maintain (the my-docker-image
contains the cross-compiler, sysroot, make, cmake, etc). With this a user can simply do something like:
cd /path/to/target_software
cross_compile.sh "mkdir build; cd build; cmake ../; make"
Where cross_compile.sh
is the script shown above. The addgroup/useradd
machinery allows user-ownership of any files/directories created by the build.
While this works for us. It seems sort of hacky. I'm open to alternative implementations ...
You can add an atrribute in linearLayout : android:scrollbars="vertical"
I came across the same issue.
I found that it is easy to group by any minute interval is just dividing epoch by minutes in amount of seconds and then either rounding or using floor to get ride of the remainder. So if you want to get interval in 5 minutes you would use 300 seconds.
SELECT COUNT(*) cnt,
to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300)
AT TIME ZONE 'UTC' as interval_alias
FROM TABLE_NAME GROUP BY interval_alias
interval_alias cnt
------------------- ----
2010-11-16 10:30:00 2
2010-11-16 10:35:00 10
2010-11-16 10:45:00 8
2010-11-16 10:55:00 11
This will return the data correctly group by the selected minutes interval; however, it will not return the intervals that don't contains any data. In order to get those empty intervals we can use the function generate_series.
SELECT generate_series(MIN(date_trunc('hour',timestamp_column)),
max(date_trunc('minute',timestamp_column)),'5m') as interval_alias FROM
TABLE_NAME
Result:
interval_alias
-------------------
2010-11-16 10:30:00
2010-11-16 10:35:00
2010-11-16 10:40:00
2010-11-16 10:45:00
2010-11-16 10:50:00
2010-11-16 10:55:00
Now to get the result with interval with zero occurrences we just outer join both result sets.
SELECT series.minute as interval, coalesce(cnt.amnt,0) as count from
(
SELECT count(*) amnt,
to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300)
AT TIME ZONE 'UTC' as interval_alias
from TABLE_NAME group by interval_alias
) cnt
RIGHT JOIN
(
SELECT generate_series(min(date_trunc('hour',timestamp_column)),
max(date_trunc('minute',timestamp_column)),'5m') as minute from TABLE_NAME
) series
on series.minute = cnt.interval_alias
The end result will include the series with all 5 minute intervals even those that have no values.
interval count
------------------- ----
2010-11-16 10:30:00 2
2010-11-16 10:35:00 10
2010-11-16 10:40:00 0
2010-11-16 10:45:00 8
2010-11-16 10:50:00 0
2010-11-16 10:55:00 11
The interval can be easily changed by adjusting the last parameter of generate_series. In our case we use '5m' but it could be any interval we want.
No, there isn't one - you have a couple of options:
Wrap the whole script in a big if/end block that is simply ensured to not be true (i.e. "if 1=2 begin" - this will only work however if the script doesn't include any GO statements (as those indicate a new batch)
Use the return statement at the top (again, limited by the batch separators)
Use a connection based approach, which will ensure non-execution for the entire script (entire connection to be more accurate) - use something like a 'SET PARSEONLY ON' or 'SET NOEXEC ON' at the top of the script. This will ensure all statements in the connection (or until said set statement is turned off) will not execute and will instead be parsed/compiled only.
Use a comment block to comment out the entire script (i.e. /* and */)
EDIT: Demonstration that the 'return' statement is batch specific - note that you will continue to see result-sets after the returns:
select 1
return
go
select 2
return
select 3
go
select 4
return
select 5
select 6
go
//This code worked for me
class CountOfLettersOfString
{
static void Main()
{
Console.WriteLine("Enter string to check count of letters");
string name = Console.ReadLine();
//Method1
char[] testedalphabets = new char[26];
int[] letterCount = new int[26];
int countTestesd = 0;
Console.WriteLine($"Given String is:{name}");
for (int i = 0; i < name.Length - 1; i++)
{
int countChar = 1;
bool isCharTested = false;
for (int j = 0; j < testedalphabets.Length - 1; j++)
{
if (name[i] == testedalphabets[j])
{
isCharTested = true;
break;
}
}
if (!isCharTested)
{
testedalphabets[countTestesd] = name[i];
for (int k = i + 1; k < name.Length - 1; k++)
{
if (name[i] == name[k])
{
countChar++;
}
}
letterCount[countTestesd] = countChar;
countTestesd++;
}
else
{
continue;
}
}
for (int i = 0; i < testedalphabets.Length - 1; i++)
{
if (!char.IsLetter(testedalphabets[i]))
{
continue;
}
Console.WriteLine($"{testedalphabets[i]}-{letterCount[i]}");
}
//Method2
var g = from c in name.ToLower().ToCharArray() // make sure that L and l are the same eg
group c by c into m
select new { Key = m.Key, Count = m.Count() };
foreach (var item in g)
{
Console.WriteLine(string.Format("Character:{0} Appears {1} times", item.Key.ToString(), item.Count));
}
Console.ReadLine();
}
}
An alternative solution for preventing functions to change the user par
. You can set the default parameters early on the function, so that the graphical parameters and layout will not be changed during the function execution. See ?on.exit
for further details.
on.exit(layout(1))
opar<-par(no.readonly=TRUE)
on.exit(par(opar),add=TRUE,after=FALSE)
The answer is that java.sql.Timestamp
is a mess and should be avoided. Use java.time.LocalDateTime
instead.
So why is it a mess? From the java.sql.Timestamp
JavaDoc, a java.sql.Timestamp
is a "thin wrapper around java.util.Date
that allows the JDBC API to identify this as an SQL TIMESTAMP value". From the java.util.Date
JavaDoc, "the Date
class is intended to reflect coordinated universal time (UTC)". From the ISO SQL spec a TIMESTAMP WITHOUT TIME ZONE "is a data type that is datetime without time zone". TIMESTAMP is a short name for TIMESTAMP WITHOUT TIME ZONE. So a java.sql.Timestamp
"reflects" UTC while SQL TIMESTAMP is "without time zone".
Because java.sql.Timestamp
reflects UTC its methods apply conversions. This causes no end of confusion. From the SQL perspective it makes no sense to convert a SQL TIMESTAMP value to some other time zone as a TIMESTAMP has no time zone to convert from. What does it mean to convert 42 to Fahrenheit? It means nothing because 42 does not have temperature units. It's just a bare number. Similarly you can't convert a TIMESTAMP of 2020-07-22T10:38:00 to Americas/Los Angeles because 2020-07-22T10:30:00 is not in any time zone. It's not in UTC or GMT or anything else. It's a bare date time.
java.time.LocalDateTime
is also a bare date time. It does not have a time zone, exactly like SQL TIMESTAMP. None of its methods apply any kind of time zone conversion which makes its behavior much easier to predict and understand. So don't use java.sql.Timestamp
. Use java.time.LocalDateTime
.
LocalDateTime ldt = rs.getObject(col, LocalDateTime.class);
ps.setObject(param, ldt, JDBCType.TIMESTAMP);
What you want to do is a bad idea. It would require you to embed your username and password in the app. This is a very bad idea as it might be possible to reverse engineer your APK and get the username and password to this publicly facing mysql server which may contain sensitive user data.
I would suggest making a web service to act as a proxy to the mysql server. I assume users need to be logged in, so you could use their username/password to authenticate to the web service.
This should do:
samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]
So in short, no there is no alternative to reassigning.
Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:
R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
b c
a 1 A
b 2 B
c 3 C
d 4 D
e 5 E
f 6 F
g 7 G
h 8 H
i 9 I
j 10 J
R>
The following works for me:
<img src="{{ asset('bundle/myname/img/image.gif', null, true) }}" />
BufferedReader
can't wrap an InputStream
directly. It wraps another Reader
. In this case you'd want to do something like:
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
If you have a list of contacts the you can go for this:
((Spinner) view.findViewById(R.id.mobile)).setSelection(spinnerContactPersonDesignationAdapter.getPosition(schoolContact.get(i).getCONT_DESIGNATION()));
I'd rather trust JDK over System property. Following is a working snippet.
private boolean checkIfStringContainsNewLineCharacters(String str){
if(!StringUtils.isEmpty(str)){
Scanner scanner = new Scanner(str);
scanner.nextLine();
boolean hasNextLine = scanner.hasNextLine();
scanner.close();
return hasNextLine;
}
return false;
}
Thanks to galloglass' answer. The code works great with Python 2.7. There is only one thing I want to metion. When read the manifest.mbdb file, you should use binary mode. Otherwise, not all content are read.
I also made some minor changes to make the code work with Python 3.4. Here is the code.
#!/usr/bin/env python
import sys
import hashlib
mbdx = {}
def getint(data, offset, intsize):
"""Retrieve an integer (big-endian) and new offset from the current offset"""
value = 0
while intsize > 0:
value = (value << 8) + data[offset]
offset = offset + 1
intsize = intsize - 1
return value, offset
def getstring(data, offset):
"""Retrieve a string and new offset from the current offset into the data"""
if chr(data[offset]) == chr(0xFF) and chr(data[offset + 1]) == chr(0xFF):
return '', offset + 2 # Blank string
length, offset = getint(data, offset, 2) # 2-byte length
value = data[offset:offset + length]
return value.decode(encoding='latin-1'), (offset + length)
def process_mbdb_file(filename):
mbdb = {} # Map offset of info in this file => file info
data = open(filename, 'rb').read() # 'b' is needed to read all content at once
if data[0:4].decode() != "mbdb": raise Exception("This does not look like an MBDB file")
offset = 4
offset = offset + 2 # value x05 x00, not sure what this is
while offset < len(data):
fileinfo = {}
fileinfo['start_offset'] = offset
fileinfo['domain'], offset = getstring(data, offset)
fileinfo['filename'], offset = getstring(data, offset)
fileinfo['linktarget'], offset = getstring(data, offset)
fileinfo['datahash'], offset = getstring(data, offset)
fileinfo['unknown1'], offset = getstring(data, offset)
fileinfo['mode'], offset = getint(data, offset, 2)
fileinfo['unknown2'], offset = getint(data, offset, 4)
fileinfo['unknown3'], offset = getint(data, offset, 4)
fileinfo['userid'], offset = getint(data, offset, 4)
fileinfo['groupid'], offset = getint(data, offset, 4)
fileinfo['mtime'], offset = getint(data, offset, 4)
fileinfo['atime'], offset = getint(data, offset, 4)
fileinfo['ctime'], offset = getint(data, offset, 4)
fileinfo['filelen'], offset = getint(data, offset, 8)
fileinfo['flag'], offset = getint(data, offset, 1)
fileinfo['numprops'], offset = getint(data, offset, 1)
fileinfo['properties'] = {}
for ii in range(fileinfo['numprops']):
propname, offset = getstring(data, offset)
propval, offset = getstring(data, offset)
fileinfo['properties'][propname] = propval
mbdb[fileinfo['start_offset']] = fileinfo
fullpath = fileinfo['domain'] + '-' + fileinfo['filename']
id = hashlib.sha1(fullpath.encode())
mbdx[fileinfo['start_offset']] = id.hexdigest()
return mbdb
def modestr(val):
def mode(val):
if (val & 0x4):
r = 'r'
else:
r = '-'
if (val & 0x2):
w = 'w'
else:
w = '-'
if (val & 0x1):
x = 'x'
else:
x = '-'
return r + w + x
return mode(val >> 6) + mode((val >> 3)) + mode(val)
def fileinfo_str(f, verbose=False):
if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
if (f['mode'] & 0xE000) == 0xA000:
type = 'l' # symlink
elif (f['mode'] & 0xE000) == 0x8000:
type = '-' # file
elif (f['mode'] & 0xE000) == 0x4000:
type = 'd' # dir
else:
print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
type = '?' # unknown
info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" %
(type, modestr(f['mode'] & 0x0FFF), f['userid'], f['groupid'], f['filelen'],
f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
for name, value in f['properties'].items(): # extra properties
info = info + ' ' + name + '=' + repr(value)
return info
verbose = True
if __name__ == '__main__':
mbdb = process_mbdb_file(
r"Manifest.mbdb")
for offset, fileinfo in mbdb.items():
if offset in mbdx:
fileinfo['fileID'] = mbdx[offset]
else:
fileinfo['fileID'] = "<nofileID>"
print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
print(fileinfo_str(fileinfo, verbose))
In .Net, you cannot assign a null
value to an int
or any other struct. Instead, use a Nullable<int>
, or int?
for short:
int? value = 0;
if (value == 0)
{
value = null;
}
Further Reading
Rails3 Code with fully localized messages:
In the model user.rb define the validation
validates :email, :presence => true
In config/locales/en.yml
en:
activerecord:
models:
user: "Customer"
attributes:
user:
email: "Email address"
errors:
models:
user:
attributes:
email:
blank: "cannot be empty"
if you have a the input password in a variable and you want to match exactly 123456 then anchors will help you:
/^123456$/
in perl the test for matching the password would be something like
print "MATCH_OK" if ($input_pass=~/^123456$/);
EDIT:
bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way
as a second thought, you may want to consider a safer authentication mechanism :)
you can access the children of a vuejs component with this.$children
. if you want to use the query selector on the current component instance then this.$el.querySelector(...)
just doing a simple console.log(this)
will show you all the properties of a vue component instance.
additionally if you know the element you want to access in your component, you can add the v-el:uniquename
directive to it and access it via this.$els.uniquename
Hidde:
BUTTON.setVisibility(View.GONE);
Show:
BUTTON.setVisibility(View.VISIBLE);
This is a DevExpress
specific answer based on the top-voted answer by Gregor S.
(currently it has 128 votes).
This means we can keep the styling consistent across the entire application:
Unfortunately, the original answer doesn't work with a ComboBoxEdit
from DevExpress without some modifications.
First, the XAML for the ComboBoxEdit
:
<dxe:ComboBoxEdit ItemsSource="{Binding Source={xamlExtensions:XamlExtensionEnumDropdown {x:myEnum:EnumFilter}}}"
SelectedItem="{Binding BrokerOrderBookingFilterSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
DisplayMember="Description"
MinWidth="144" Margin="5"
HorizontalAlignment="Left"
IsTextEditable="False"
ValidateOnTextInput="False"
AutoComplete="False"
IncrementalFiltering="True"
FilterCondition="Like"
ImmediatePopup="True"/>
Needsless to say, you will need to point xamlExtensions
at the namespace that contains the XAML extension class (which is defined below):
xmlns:xamlExtensions="clr-namespace:XamlExtensions"
And we have to point myEnum
at the namespace that contains the enum:
xmlns:myEnum="clr-namespace:MyNamespace"
Then, the enum:
namespace MyNamespace
{
public enum EnumFilter
{
[Description("Free as a bird")]
Free = 0,
[Description("I'm Somewhat Busy")]
SomewhatBusy = 1,
[Description("I'm Really Busy")]
ReallyBusy = 2
}
}
The problem in with the XAML is that we can't use SelectedItemValue
, as this throws an error as the setter is unaccessable (bit of an oversight on your part, DevExpress
). So we have to modify our ViewModel
to obtain the value directly from the object:
private EnumFilter _filterSelected = EnumFilter.All;
public object FilterSelected
{
get
{
return (EnumFilter)_filterSelected;
}
set
{
var x = (XamlExtensionEnumDropdown.EnumerationMember)value;
if (x != null)
{
_filterSelected = (EnumFilter)x.Value;
}
OnPropertyChanged("FilterSelected");
}
}
For completeness, here is the XAML extension from the original answer (slightly renamed):
namespace XamlExtensions
{
/// <summary>
/// Intent: XAML markup extension to add support for enums into any dropdown box, see http://bit.ly/1g70oJy. We can name the items in the
/// dropdown box by using the [Description] attribute on the enum values.
/// </summary>
public class XamlExtensionEnumDropdown : MarkupExtension
{
private Type _enumType;
public XamlExtensionEnumDropdown(Type enumType)
{
if (enumType == null)
{
throw new ArgumentNullException("enumType");
}
EnumType = enumType;
}
public Type EnumType
{
get { return _enumType; }
private set
{
if (_enumType == value)
{
return;
}
var enumType = Nullable.GetUnderlyingType(value) ?? value;
if (enumType.IsEnum == false)
{
throw new ArgumentException("Type must be an Enum.");
}
_enumType = value;
}
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var enumValues = Enum.GetValues(EnumType);
return (
from object enumValue in enumValues
select new EnumerationMember
{
Value = enumValue,
Description = GetDescription(enumValue)
}).ToArray();
}
private string GetDescription(object enumValue)
{
var descriptionAttribute = EnumType
.GetField(enumValue.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false)
.FirstOrDefault() as DescriptionAttribute;
return descriptionAttribute != null
? descriptionAttribute.Description
: enumValue.ToString();
}
#region Nested type: EnumerationMember
public class EnumerationMember
{
public string Description { get; set; }
public object Value { get; set; }
}
#endregion
}
}
Disclaimer: I have no affiliation with DevExpress. Telerik is also a great library.
The target container should have the white-space:pre
style.
Try it below.
<script>_x000D_
function copycontent(){_x000D_
var content = document.getElementById('ta').value;_x000D_
document.getElementById('target').innerText = content;_x000D_
}_x000D_
</script>_x000D_
<textarea id='ta' rows='3'>_x000D_
line 1_x000D_
line 2_x000D_
line 3_x000D_
</textarea>_x000D_
<button id='btn' onclick='copycontent();'>_x000D_
Copy_x000D_
</button>_x000D_
<p id='target' style='white-space:pre'>_x000D_
_x000D_
</p>
_x000D_
Simulator doesn't have a Camera. If you want to access a camera you need a device. You can't test camera on simulator. You can only check the photo and video gallery.
Had the same issue, found that the template component tags worked with <app-[component-name]></app-[component-name]>
. So, if your component is called mycomponent.component.ts
:
@Component({
selector: 'my-app',
template: `
<h1>Hello {{name}}</h1>
<h4>Something</h4>
<app-mycomponent></app-mycomponent>
`,
It may depend on what you consider fallthrough. I'm ok with this sort of thing:
switch (value)
{
case 0:
result = ZERO_DIGIT;
break;
case 1:
case 3:
case 5:
case 7:
case 9:
result = ODD_DIGIT;
break;
case 2:
case 4:
case 6:
case 8:
result = EVEN_DIGIT;
break;
}
But if you have a case label followed by code that falls through to another case label, I'd pretty much always consider that evil. Perhaps moving the common code to a function and calling from both places would be a better idea.
You'll need to use the HTML()
or display()
functions from IPython's display module:
from IPython.display import display, HTML
# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
display(HTML(df2.to_html()))
Note that if you just print df1.to_html()
you'll get the raw, unrendered HTML.
You can also import from IPython.core.display
with the same effect
I found a way to automate running the clean before you debug your code. (Warning, this runs everytime you hit the button, even for hot restart)
First, find the Run > Edit Configurations Menu
Click the External tool '+' icon under Before launch: External tool, Activate tool window.
A token is a piece of data created by server, and contains information to identify a particular user and token validity. The token will contain the user's information, as well as a special token code that user can pass to the server with every method that supports authentication, instead of passing a username and password directly.
Token-based authentication is a security technique that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server.
An authentication is successful if a user can prove to a server that he or she is a valid user by passing a security token. The service validates the security token and processes the user request.
After the token is validated by the service, it is used to establish security context for the client, so the service can make authorization decisions or audit activity for successive user requests.
The error as reported appears when the variables are null (or empty):
$ unset var3 var4; var5=$(($var4-$var3))
bash: -: syntax error: operand expected (error token is "-")
That could happen because the value given to bc was incorrect. That might well be that bc needs UPPERcase values. It needs BFCA3000
, not bfca3000
. That is easily fixed in bash, just use the ^^
expansion:
var3=bfca3000; var3=`echo "ibase=16; ${var1^^}" | bc`
That will change the script to this:
#!/bin/bash
var1="bfca3000"
var2="efca3250"
var3="$(echo "ibase=16; ${var1^^}" | bc)"
var4="$(echo "ibase=16; ${var2^^}" | bc)"
var5="$(($var4-$var3))"
echo "Diference $var5"
But there is no need to use bc [1], as bash could perform the translation and substraction directly:
#!/bin/bash
var1="bfca3000"
var2="efca3250"
var5="$(( 16#$var2 - 16#$var1 ))"
echo "Diference $var5"
[1]Note: I am assuming the values could be represented in 64 bit math, as the difference was calculated in bash in your original script. Bash is limited to integers less than ((2**63)-1) if compiled in 64 bits. That will be the only difference with bc which does not have such limit.
You can set this at boot by adding the "elevator" parameter to the kernel cmdline (such as in grub.cfg)
Example:
elevator=deadline
This will make "deadline" the default I/O scheduler for all block devices.
If you'd like to query or change the scheduler after the system has booted, or would like to use a different scheduler for a specific block device, I recommend installing and use the tool ioschedset to make this easy.
https://github.com/kata198/ioschedset
If you're on Archlinux it's available in aur:
https://aur.archlinux.org/packages/ioschedset
Some example usage:
# Get i/o scheduler for all block devices
[username@hostname ~]$ io-get-sched
sda: bfq
sr0: bfq
# Query available I/O schedulers
[username@hostname ~]$ io-set-sched --list
mq-deadline kyber bfq none
# Set sda to use "kyber"
[username@hostname ~]$ io-set-sched kyber /dev/sda
Must be root to set IO Scheduler. Rerunning under sudo...
[sudo] password for username:
+ Successfully set sda to 'kyber'!
# Get i/o scheduler for all block devices to assert change
[username@hostname ~]$ io-get-sched
sda: kyber
sr0: bfq
# Set all block devices to use 'deadline' i/o scheduler
[username@hostname ~]$ io-set-sched deadline
Must be root to set IO Scheduler. Rerunning under sudo...
+ Successfully set sda to 'deadline'!
+ Successfully set sr0 to 'deadline'!
# Get the current block scheduler just for sda
[username@hostname ~]$ io-get-sched sda
sda: mq-deadline
Usage should be self-explanatory. The tools are standalone and only require bash.
Hope this helps!
EDIT: Disclaimer, these are scripts I wrote.
According to @Abhishek Singh's you need to understand the problem:
What is the line which gives exception ?? The reason for this is because the element to which you have referred is removed from the DOM structure
and you can not refer to it anymore (imagine what element's ID has changed).
Follow the code:
class TogglingPage {
@FindBy(...)
private WebElement btnTurnOff;
@FindBy(...)
private WebElement btnTurnOn;
TogglingPage turnOff() {
this.btnTurnOff.isDisplayed();
this.btnTurnOff.click(); // when clicked, button should swap into btnTurnOn
this.btnTurnOn.isDisplayed();
this.btnTurnOn.click(); // when clicked, button should swap into btnTurnOff
this.btnTurnOff.isDisplayed(); // throws an exception
return new TogglingPage();
}
}
Now, let us wonder why?
btnTurnOff
was found by a driver - okbtnTurnOff
was replaced by btnTurnOn
- okbtnTurnOn
was found by a driver. - okbtnTurnOn
was replaced by btnTurnOff
- okthis.btnTurnOff.isDisplayed();
on the element which does not exist anymore in Selenium sense - you can see it, it works perfectly, but it is a different instance of the same button. Possible fix:
TogglingPage turnOff() {
this.btnTurnOff.isDisplayed();
this.btnTurnOff.click();
TogglingPage newPage = new TogglingPage();
newPage.btnTurnOn.isDisplayed();
newPage.btnTurnOn.click();
TogglingPage newerPage = new TogglingPage();
newerPage.btnTurnOff.isDisplayed(); // ok
return newerPage;
}
In case you need to split a string from your JSON, the string has the \n special character replaced with \\n.
Split string by newline:
Result.split('\n');
Split string received in JSON, where special character \n was replaced with \\n during JSON.stringify(in javascript) or json.json_encode(in PHP). So, if you have your string in a AJAX response, it was processed for transportation. and if it is not decoded, it will sill have the \n replaced with \\n** and you need to use:
Result.split('\\n');
Note that the debugger tools from your browser might not show this aspect as you was expecting, but you can see that splitting by \\n resulted in 2 entries as I need in my case:
If you have fetched, yet this still happens, the following might be a reason.
It can happen that the commit you are trying to pick, is no longer belonging to any branch. This may happen when you rebase.
In such case, at the remote repo:
git checkout xxxxx
git checkout -b temp-branch
Then in your repo, fetch again. The new branch will be fetched, including that commit.
it should be :
$_SERVER['REQUEST_URI'];
Take a look at : Get the full URL in PHP