I found problems with the two common ways of doing this:
Doing this with custom headers (<customHeaders>
) in web.config allows different deployments of the same application to have this set differently. I see this as one more thing that can go wrong, so I think it's better if the application specifies this in code. Also, IIS6 doesn't support this.
Including an HTML <meta>
tag in a Web Forms Master Page or MVC Layout Page seems better than the above. However, if some pages don't inherit from these then the tag needs to be duplicated, so there's a potential maintainability and reliability problem.
Network traffic could be reduced by only sending the X-UA-Compatible
header to Internet Explorer clients.
If your application is structured in a way that causes all pages to ultimately inherit from a single root page, include the <meta>
tag as shown in the other answers.
Otherwise,
I think the best way to do this is to automatically add the HTTP header to all HTML responses. One way to do this is using an IHttpModule
:
public class IeCompatibilityModeDisabler : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreSendRequestHeaders += (sender, e) => DisableCompatibilityModeIfApplicable();
}
private void DisableCompatibilityModeIfApplicable()
{
if (IsIe && IsPage)
DisableCompatibilityMode();
}
private void DisableCompatibilityMode()
{
var response = Context.Response;
response.AddHeader("X-UA-Compatible", "IE=edge");
}
private bool IsIe { get { return Context.Request.Browser.IsBrowser("IE"); } }
private bool IsPage { get { return Context.Handler is Page; } }
private HttpContext Context { get { return HttpContext.Current; } }
public void Dispose() { }
}
IE=edge
indicates that IE should use its latest rendering engine (rather than compatibility mode) to render the page.
It seems that HTTP modules are often registered in the web.config file, but this brings us back to the first problem. However, you can register them programmatically in Global.asax like this:
public class Global : HttpApplication
{
private static IeCompatibilityModeDisabler module;
void Application_Start(object sender, EventArgs e)
{
module = new IeCompatibilityModeDisabler();
}
public override void Init()
{
base.Init();
module.Init(this);
}
}
Note that it is important that the module is static
and not instantiated in Init
so that there is only one instance per application. Of course, in a real-world application an IoC container should probably be managing this.
PreSendRequestHeaders
event in the above code doesn't seem to fire in IIS6. I haven't figured out how to resolve this bug yet.You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer: http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#SetMode
Edit: in case something happens to kill the msdn link, here is the content:
Specifying Document Compatibility Modes
You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.
<html> <head> <!-- Enable IE9 Standards mode --> <meta http-equiv="X-UA-Compatible" content="IE=9" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.
The following example specifies EmulateIE7 mode.
<html> <head> <!-- Mimic Internet Explorer 7 --> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.
I was able to get around this loading the headers before the HTML with php, and it worked very well.
<?php
header( 'X-UA-Compatible: IE=edge,chrome=1' );
header( 'content: width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' );
include('ix.html');
?>
ix.html is the content I wanted to load after sending the headers.
If the first column is always the same size (including the spaces), then you can just take those characters (via LEFT
) and clean up the spaces (with RTRIM
):
SELECT RTRIM(LEFT(YourColumn, YourColumnSize))
Alternatively, you can extract the second (or third, etc.) column (using SUBSTRING
):
SELECT RTRIM(SUBSTRING(YourColumn, PreviousColumnSizes, YourColumnSize))
One benefit of this approach (especially if YourColumn
is the result of a computation) is that YourColumn
is only specified once.
entropy is availability of information or knowledge, Lack of information will leads to difficulties in prediction of future which is high entropy (next word prediction in text mining) and availability of information/knowledge will help us more realistic prediction of future (low entropy).
Relevant information of any type will reduce entropy and helps us predict more realistic future, that information can be word "meat" is present in sentence or word "meat" is not present. This is called Information Gain
entropy is lack of order of predicability
There is also one more option than @: and <text></text>
.
Using <script>
block itself.
When you need to do large chunks of JavaScript depending on Razor code, you can do it like this:
@if(Utils.FeatureEnabled("Feature")) {
<script>
// If this feature is enabled
</script>
}
<script>
// Other JavaScript code
</script>
Pros of this manner is that it doesn't mix JavaScript and Razor too much, because mixing them a lot will cause readability issues eventually. Also large text blocks are not very readable either.
Here.. Works perfectly for me
.modal-body {
max-height:500px;
overflow-y:auto;
}
I assume you have already read Wikipedia and other academic resources on this, so I won't recycle any of that information. I must also caveat that I am not a computer science expert by any means, but I'll share my two cents on my understanding of these topics...
Breaks the problem down into discrete subproblems. The recursive algorithm for the Fibonacci sequence is an example of Dynamic Programming, because it solves for fib(n) by first solving for fib(n-1). In order to solve the original problem, it solves a different problem.
These algorithms typically solve similar pieces of the problem, and then put them together at the end. Mergesort is a classic example of divide and conquer. The main difference between this example and the Fibonacci example is that in a mergesort, the division can (theoretically) be arbitrary, and no matter how you slice it up, you are still merging and sorting. The same amount of work has to be done to mergesort the array, no matter how you divide it up. Solving for fib(52) requires more steps than solving for fib(2).
public interface IService {
String BASE_URL = "https://api.demo.com/";
@GET("Login") //i.e https://api.demo.com/Search?
Call<Products> getUserDetails(@Query("email") String emailID, @Query("password") String password)
}
It will be called this way. Considering you did the rest of the code already.
Call<Results> call = service.getUserDetails("[email protected]", "Password@123");
For example when a query is returned, it will look like this.
https://api.demo.com/[email protected]&password=Password@123
You can use colorRampPalette
from base or RColorBrewer
package:
With colorRampPalette
, you can specify colours as follows:
colorRampPalette(c("red", "green"))(5)
# [1] "#FF0000" "#BF3F00" "#7F7F00" "#3FBF00" "#00FF00"
You can alternatively provide hex codes as well:
colorRampPalette(c("#3794bf", "#FFFFFF", "#df8640"))(5)
# [1] "#3794BF" "#9BC9DF" "#FFFFFF" "#EFC29F" "#DF8640"
# Note that the mid color is the mid value...
With RColorBrewer
you could use colors from pre-existing palettes:
require(RColorBrewer)
brewer.pal(9, "Set1")
# [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628" "#F781BF"
# [9] "#999999"
Look at RColorBrewer
package for other available palettes. Hope this helps.
Faster option:
The following code will copy your Pandas DF to postgres DB much faster than df.to_sql method and you won't need any intermediate csv file to store the df.
Create an engine based on your DB specifications.
Create a table in your postgres DB that has equal number of columns as the Dataframe (df).
Data in DF will get inserted in your postgres table.
from sqlalchemy import create_engine
import psycopg2
import io
if you want to replace the table, we can replace it with normal to_sql method using headers from our df and then load the entire big time consuming df into DB.
engine = create_engine('postgresql+psycopg2://username:password@host:port/database')
df.head(0).to_sql('table_name', engine, if_exists='replace',index=False) #drops old table and creates new empty table
conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_from(output, 'table_name', null="") # null values become ''
conn.commit()
public class BOX
{
double height, length, breadth;
public static bool operator == (BOX b1, BOX b2)
{
if (b1 is null)
return b2 is null;
return b1.Equals(b2);
}
public static bool operator != (BOX b1, BOX b2)
{
return !(b1 == b2);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
return obj is BOX b2? (length == b2.length &&
breadth == b2.breadth &&
height == b2.height): false;
}
public override int GetHashCode()
{
return (height,length,breadth).GetHashCode();
}
}
Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.
That's why you can't use something 'not hashable' as a dict key, like a list:
>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
You can read more about hash tables or check how it has been implemented in python and why it is implemented that way.
Well, longs can't hold anything but integers.
One option is to use a float: float('234.89')
The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))
>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L
var result = string.Join("", input.Select(c => ((int)c).ToString("X2")));
OR
var result =string.Join("",
input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c))));
Simply put, this is wrong because it unnecessarily opens up possibilities to MANY bugs. When the @Override
is invoked, the state of the object may be inconsistent and/or incomplete.
A quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:
There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.
Here's an example to illustrate:
public class ConstructorCallsOverride {
public static void main(String[] args) {
abstract class Base {
Base() {
overrideMe();
}
abstract void overrideMe();
}
class Child extends Base {
final int x;
Child(int x) {
this.x = x;
}
@Override
void overrideMe() {
System.out.println(x);
}
}
new Child(42); // prints "0"
}
}
Here, when Base
constructor calls overrideMe
, Child
has not finished initializing the final int x
, and the method gets the wrong value. This will almost certainly lead to bugs and errors.
Constructors with many parameters can lead to poor readability, and better alternatives exist.
Here's a quote from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters:
Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameters, a third with two optional parameters, and so on...
The telescoping constructor pattern is essentially something like this:
public class Telescope {
final String name;
final int levels;
final boolean isAdjustable;
public Telescope(String name) {
this(name, 5);
}
public Telescope(String name, int levels) {
this(name, levels, false);
}
public Telescope(String name, int levels, boolean isAdjustable) {
this.name = name;
this.levels = levels;
this.isAdjustable = isAdjustable;
}
}
And now you can do any of the following:
new Telescope("X/1999");
new Telescope("X/1999", 13);
new Telescope("X/1999", 13, true);
You can't, however, currently set only the name
and isAdjustable
, and leaving levels
at default. You can provide more constructor overloads, but obviously the number would explode as the number of parameters grow, and you may even have multiple boolean
and int
arguments, which would really make a mess out of things.
As you can see, this isn't a pleasant pattern to write, and even less pleasant to use (What does "true" mean here? What's 13?).
Bloch recommends using a builder pattern, which would allow you to write something like this instead:
Telescope telly = new Telescope.Builder("X/1999").setAdjustable(true).build();
Note that now the parameters are named, and you can set them in any order you want, and you can skip the ones that you want to keep at default values. This is certainly much better than telescoping constructors, especially when there's a huge number of parameters that belong to many of the same types.
This can be used to merge any number of files specified on the command:
jq -rs 'reduce .[] as $item ({}; . * $item)' file1.json file2.json file3.json ... file10.json
or this for any number of files
jq -rs 'reduce .[] as $item ({}; . * $item)' ./*.json
Across all options with component maps I haven't found the simplest way to define the map using ES6 short syntax:
import React from 'react'
import { PhotoStory, VideoStory } from './stories'
const components = {
PhotoStory,
VideoStory,
}
function Story(props) {
//given that props.story contains 'PhotoStory' or 'VideoStory'
const SpecificStory = components[props.story]
return <SpecificStory/>
}
In the header file
header file
#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef MAIN_FILE
int global;
#else
extern int global;
#endif
#endif
In the file with the file you want the global to live:
#define MAIN_FILE
#include "share.h"
In the other files that need the extern version:
#include "share.h"
beware when comparing numbers that are package versions, like checking if grep 2.20 is greater than version 2.6:
$ awk 'BEGIN { print (2.20 >= 2.6) ? "YES" : "NO" }'
NO
$ awk 'BEGIN { print (2.2 >= 2.6) ? "YES" : "NO" }'
NO
$ awk 'BEGIN { print (2.60 == 2.6) ? "YES" : "NO" }'
YES
I solved such problem with such shell/awk function:
# get version of GNU tool
toolversion() {
local prog="$1" operator="$2" value="$3" version
version=$($prog --version | awk '{print $NF; exit}')
awk -vv1="$version" -vv2="$value" 'BEGIN {
split(v1, a, /\./); split(v2, b, /\./);
if (a[1] == b[1]) {
exit (a[2] '$operator' b[2]) ? 0 : 1
}
else {
exit (a[1] '$operator' b[1]) ? 0 : 1
}
}'
}
if toolversion grep '>=' 2.6; then
# do something awesome
fi
Just FYI, Geocoder is asynchronous so the accepted answer while logical doesn't really work in this instance. I would prefer to have an outside object that acts as your updater.
var updater = {};
function geoCodeCity(goocoord) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': goocoord
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
updater.currentLocation = results[1].formatted_address;
} else {
if (status == "ERROR") {
console.log(status);
}
}
});
};
one of the easy way to do that is use landa function without any problem like
userControl_Material1.simpleButton4.Click += (s, ee) =>
{
Save_mat(mat_global);
};
i think it should be
select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212
or
select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212
Here is code in Java to get all options in dropdown list.
WebElement sel = myD.findElement(By.name("dropdown_name"));
List<WebElement> lists = sel.findElements(By.tagName("option"));
for(WebElement element: lists)
{
String var2 = tdElement.getText();
System.out.println(var2);
}
Hope it may helpful to someone.
Just additional notes. Using class ES6, When we create static methods..the Javacsript engine set the descriptor attribute a lil bit different from the old-school "static" method
function Car() {
}
Car.brand = function() {
console.log('Honda');
}
console.log(
Object.getOwnPropertyDescriptors(Car)
);
it sets internal attribute (descriptor property) for brand() to
..
brand: [object Object] {
configurable: true,
enumerable: true,
value: ..
writable: true
}
..
compared to
class Car2 {
static brand() {
console.log('Honda');
}
}
console.log(
Object.getOwnPropertyDescriptors(Car2)
);
that sets internal attribute for brand() to
..
brand: [object Object] {
configurable: true,
enumerable: false,
value:..
writable: true
}
..
see that enumerable is set to false for static method in ES6.
it means you cant use the for-in loop to check the object
for (let prop in Car) {
console.log(prop); // brand
}
for (let prop in Car2) {
console.log(prop); // nothing here
}
static method in ES6 is treated like other's class private property (name, length, constructor) except that static method is still writable thus the descriptor writable is set to true { writable: true }
. it also means that we can override it
Car2.brand = function() {
console.log('Toyota');
};
console.log(
Car2.brand() // is now changed to toyota
);
I recommend https://pypi.python.org/pypi/anytree
from anytree import Node, RenderTree
udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)
print(udo)
Node('/Udo')
print(joe)
Node('/Udo/Dan/Joe')
for pre, fill, node in RenderTree(udo):
print("%s%s" % (pre, node.name))
Udo
+-- Marc
¦ +-- Lian
+-- Dan
+-- Jet
+-- Jan
+-- Joe
print(dan.children)
(Node('/Udo/Dan/Jet'), Node('/Udo/Dan/Jan'), Node('/Udo/Dan/Joe'))
anytree has also a powerful API with:
Just make sure all the implementations of firebase you are using have the same version inside the dependencies in build.gradle (app).
You can insert a SVG indirectly using <img>
HTML tag and this is possible on StackOverflow following what is described below:
I have following SVG file on my PC
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="350" height="350" viewBox="0 0 350 350">
<title>SVG 3 Circles Intersection </title>
<circle cx="110" cy="110" r="100"
stroke="red"
stroke-width="3"
fill="none"
/>
<text x="110" y="110"
text-anchor="middle"
stroke="red"
stroke-width="1px"
> Label
</text>
<circle cx="240" cy="110" r="100"
stroke="blue"
stroke-width="3"
fill="none"
/>
<text x="240" y="110"
text-anchor="middle"
stroke="blue"
stroke-width="1px"
> Ticket
</text>
<circle cx="170" cy="240" r="100"
stroke="green"
stroke-width="3"
fill="none"
/>
<text x="170" y="240"
text-anchor="middle"
stroke="green"
stroke-width="1px"
> Vecto
</text>
</svg>
I have uploaded this image to https://svgur.com
After upload was terminated, I have obtained following URL:
https://svgshare.com/i/RJV.svg
I have then MANUALLY (without using IMAGE icon) added following html tag
<img src="https://svgshare.com/i/KJV.svg"/>
and the result is just below
For user with some doubt, it is possible to see what I have done in editing following answer on StackOverflow inserting SVG image
REMARK-1: the SVG file must contains <?xml?>
element. At begin, I have simply created a SVG file that begins directly with <svg>
tag and nothing worked !
REMARK-2: at begin, I have tried to insert an image using IMAGE
icon of Edit Toolbar
. I paste URL of my SVG file but StackOverflow don't accept this method. The <img>
tag must be added manually.
I hope that this answer can help other users.
Here is the method I use:
public boolean isNetworkAvailable(final Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
Even better, check to make sure it is "connected":
public boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
Here is how to use the method:
if (isNetworkAvailable(context)) {
// code here
} else {
// code
}
Permission needed:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Just in case you actually mean 'discard changes' whenever you use 'git stash' (and don't really use git stash to stash it temporarily), in that case you can use
git checkout -- <file>
Note that git stash is just a quicker and simple alternative to branching and doing stuff.
A simple way to solve the issue would be to wrap the try/catch in a while loop and maintain a count. This way you could prevent an infinite loop by checking a count against some other variable while maintaining a log of your failures. It isn't the most exquisite solution, but it would work.
Make sure you set up the correct settings for connection pool. This is very important as I have explained in the following article: https://medium.com/@dewanwaqas/configurations-that-significantly-improves-your-app-performance-built-using-sql-server-and-net-ed044e53b60 You will see a drastic improvement in your application's performance if you follow it.
I'm not sure it's possible "out of the box". And, unfortunately, I don't know an appropriate plugin either. To solve the problem you suggested you could use regular expressions.
[^ ]+
(or \d+
, or whatever you prefer)Hotkeys may vary depending on you OS and personal preferences (mine are for OS X).
debugger
is a reserved keyword by EcmaScript and given optional semantics since ES5
As a result, it can be used not only in Chrome, but also Firefox and Node.js via node debug myscript.js
.
The standard says:
Syntax
DebuggerStatement : debugger ;
Semantics
Evaluating the DebuggerStatement production may allow an implementation to cause a breakpoint when run under a debugger. If a debugger is not present or active this statement has no observable effect.
The production DebuggerStatement : debugger ; is evaluated as follows:
- If an implementation defined debugging facility is available and enabled, then
- Perform an implementation defined debugging action.
- Let result be an implementation defined Completion value.
- Else
- Let result be (normal, empty, empty).
- Return result.
No changes in ES6.
I've come across Flexi Auth (http://haseydesign.com/flexi-auth/). It looks very promising, and I've started using it. It has wonderfful features. Fully integrates with CI, and comes with two different library files, in which one is very heavy loaded with all the functions and the other one contains only the validations.
One of the best is that the newly registered member gets temporary access for a given amount of time on the site, until they click on the link from their email and activate.
There is a (somewhat) related question on StackOverflow:
Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeeze
d or sliced into a 2D array.
More generally, the reason for the Exception
TypeError: Invalid dimensions for image data
is shown here: matplotlib.pyplot.imshow()
needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!
You can easily check this with (these checks are done by imshow
, this function is only meant to give a more specific message in case it's not a valid input):
from __future__ import print_function
import numpy as np
def valid_imshow_data(data):
data = np.asarray(data)
if data.ndim == 2:
return True
elif data.ndim == 3:
if 3 <= data.shape[2] <= 4:
return True
else:
print('The "data" has 3 dimensions but the last dimension '
'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
''.format(data.shape[2]))
return False
else:
print('To visualize an image the data must be 2 dimensional or '
'3 dimensional, not "{}".'
''.format(data.ndim))
return False
In your case:
>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False
The np.asarray
is what is done internally by matplotlib.pyplot.imshow
so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list
) it's necessary.
In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0) # or axis=1
plt.imshow(a)
plt.show()
or just use something that accepts 1D arrays like plot
:
a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()
You could also try 'upData' from 'Hmisc' package.
library(Hmisc)
trSamp = upData(trSamp, rename=c(sample.trainer.index..10000. = 'newname2'))
setTimeout( function ( ) { alert( "moo" ); }, 10000 ); //displays msg in 10 seconds
The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.
This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessDialogKey(keyData);
}
There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:
$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});
Another would be to load the content of your external link into the dialog container using ajax.
$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});
Both works fine but depends on the external content.
If you know what column the text/pattern you're looking for (e.g. "yyy") is in, you can just check that specific column to see if it matches, and print it.
For example, given a file with the following contents, (called asdf.txt)
xxx yyy zzz
to only print the second column if it matches the pattern "yyy", you could do something like this:
awk '$2 ~ /yyy/ {print $2}' asdf.txt
Note that this will also match basically any line where the second column has a "yyy" in it, like these:
xxx yyyz zzz
xxx zyyyz
Solution #1: Your statement
.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does not refer to a proper Range
to act upon. Instead,
.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does (and similarly in some other cases).
Solution #2:
Activate Worksheets("Cable Cards")
prior to using its cells.
Explanation:
Cells(RangeStartRow, RangeStartColumn)
(e.g.) gives you a Range
, that would be ok, and that is why you often see Cells
used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet
. Thus, your code attempts using .Range(rng1, rng2)
, where .Range
is a method of one Worksheet
object and rng1
and rng2
are in a different Worksheet
.
There are two checks that you can do to make this quite evident:
Activate your Worksheets("Cable Cards")
prior to executing your Sub
and it will start working (now you have well-formed references to Range
s). For the code you posted, adding .Activate
right after With...
would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range
in another Worksheet
.
With a sheet other than Worksheets("Cable Cards")
active, set a breakpoint at the line throwing the error, start your Sub
, and when execution breaks, write at the immediate window
Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
and see the different outcomes.
Conclusion:
Using Cells
or Range
without a specified object (e.g., Worksheet
, or Range
) might be dangerous, especially when working with more than one Sheet
, unless one is quite sure about what Sheet
is active.
Use HTML Form "elements" attribute:
$.each($("form").elements, function(){
console.log($(this));
});
Now it's not necessary to provide such names as "input, textarea, select ..." etc.
<select style="width: 100%;" name="id_driver" id="id_driver" >
<option value="" @if (old('id_driver') == "") selected @endif>Select</option>
@foreach(\App\Driver::all() as $driver)
<option value="{{$driver->id}}" @if (old('id_driver') == $driver->id)
selected @endif >(#{{$driver->id}}) {{$driver->business_name}}
</option>
@endforeach
</select>
No, it is like I want to run Form_Load of Form A,if it is possible
-- Varun Mahajan
The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:
Form B:
Sub RunFormALoad()
Forms!FormA.ToDoOnLoad
End Sub
Form A:
Public Sub Form_Load()
ToDoOnLoad
End Sub
Sub ToDoOnLoad()
txtText = "Hi"
End Sub
I tried this out for transmitting continuous data (float values converted to string) from my PC (MATLAB) to my phone. But, still my App misreads the delimiter '\n' and still data gets garbled. So, I took the character 'N' as the delimiter rather than '\n' (it could be any character that doesn't occur as part of your data) and I've achieved better transmission speed - I gave just 0.1 seconds delay between transmitting successive samples - with more than 99% data integrity at the receiver i.e. out of 2000 samples (float values) that I transmitted, only 10 were not decoded properly in my application.
My answer in short is: Choose a delimiter other than '\r' or '\n' as these create more problems for real-time data transmission when compared to other characters like the one I've used. If we work more, may be we can increase the transmission rate even more. I hope my answer helps someone!
Maybe not very elegant, but it does the job:
exec(open("script.py").read())
You can't float or set the width of an inline element. Remove display: inline;
from both classes and your markup should present fine.
EDIT: You can set the width, but it will cause the element to be rendered as a block.
I have been struggling with how to add query string parameters to my URL. I couldn't make it work until I realized that I needed to add ?
at the end of my URL, otherwise it won't work. This is very important as it will save you hours of debugging, believe me: been there...done that.
Below, is a simple API Endpoint that calls the Open Weather API and passes APPID
, lat
and lon
as query parameters and return weather data as a JSON
object. Hope this helps.
//Load the request module
var request = require('request');
//Load the query String module
var querystring = require('querystring');
// Load OpenWeather Credentials
var OpenWeatherAppId = require('../config/third-party').openWeather;
router.post('/getCurrentWeather', function (req, res) {
var urlOpenWeatherCurrent = 'http://api.openweathermap.org/data/2.5/weather?'
var queryObject = {
APPID: OpenWeatherAppId.appId,
lat: req.body.lat,
lon: req.body.lon
}
console.log(queryObject)
request({
url:urlOpenWeatherCurrent,
qs: queryObject
}, function (error, response, body) {
if (error) {
console.log('error:', error); // Print the error if one occurred
} else if(response && body) {
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
res.json({'body': body}); // Print JSON response.
}
})
})
Or if you want to use the querystring
module, make the following changes
var queryObject = querystring.stringify({
APPID: OpenWeatherAppId.appId,
lat: req.body.lat,
lon: req.body.lon
});
request({
url:urlOpenWeatherCurrent + queryObject
}, function (error, response, body) {...})
jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:
$(document).keypress(function(e){
var checkWebkitandIE=(e.which==26 ? 1 : 0);
var checkMoz=(e.which==122 && e.ctrlKey ? 1 : 0);
if (checkWebkitandIE || checkMoz) $("body").append("<p>ctrl+z detected!</p>");
});
Tested in IE7,Firefox 3.6.3 & Chrome 4.1.249.1064
Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:
$(document).keydown(function(e){
if (e.keyCode==90 && e.ctrlKey)
$("body").append("<p>ctrl+z detected!</p>");
});
Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 }
is an idiomatic universal zero-initializer. This is also almost the case in C++.
Since this initalizer is universal, for bool
array you don't really need a different "syntax". 0
works as an initializer for bool
type as well, so
bool myBoolArray[ARRAY_SIZE] = { 0 };
is guaranteed to initialize the entire array with false
. As well as
char* myPtrArray[ARRAY_SIZE] = { 0 };
in guaranteed to initialize the whole array with null-pointers of type char *
.
If you believe it improves readability, you can certainly use
bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };
but the point is that = { 0 }
variant gives you exactly the same result.
However, in C++ = { 0 }
might not work for all types, like enum types, for example, which cannot be initialized with integral 0
. But C++ supports the shorter form
T myArray[ARRAY_SIZE] = {};
i.e. just an empty pair of {}
. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.
Ok I'll share this option. This is a pretty performant option - it uses an array internally - and reuses entries. It's thread safe - and you can retrieve the contents as a List.
static class FixedSizeCircularReference<T> {
T[] entries
FixedSizeCircularReference(int size) {
this.entries = new Object[size] as T[]
this.size = size
}
int cur = 0
int size
synchronized void add(T entry) {
entries[cur++] = entry
if (cur >= size) {
cur = 0
}
}
List<T> asList() {
int c = cur
int s = size
T[] e = entries.collect() as T[]
List<T> list = new ArrayList<>()
int oldest = (c == s - 1) ? 0 : c
for (int i = 0; i < e.length; i++) {
def entry = e[oldest + i < s ? oldest + i : oldest + i - s]
if (entry) list.add(entry)
}
return list
}
}
Equality in direct comparing:
string1 = "sample"
string2 = "sample"
if string1 == string2 :
print("Strings are equal with text : ", string1," & " ,string2)
else :
print ("Strings are not equal")
Equality in character sets:
string1 = 'abc def ghi'
string2 = 'def ghi abc'
set1 = set(string1.split(' '))
set2 = set(string2.split(' '))
print set1 == set2
if string1 == string2 :
print("Strings are equal with text : ", string1," & " ,string2)
else :
print ("Strings are not equal")
ThiefMaster's answer is 100% correct, although I came across a similar problem where I needed to fetch a property from a nested object (object within an object), so as an alternative to his answer, you can create a recursive solution that will allow you to define a nomenclature to grab any property, regardless of depth:
function fetchFromObject(obj, prop) {
if(typeof obj === 'undefined') {
return false;
}
var _index = prop.indexOf('.')
if(_index > -1) {
return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
}
return obj[prop];
}
Where your string reference to a given property ressembles property1.property2
Code and comments in JsFiddle.
Yes, you can use the built-in hashlib
module or the built-in hash
function. Then, chop-off the last eight digits using modulo operations or string slicing operations on the integer form of the hash:
>>> s = 'she sells sea shells by the sea shore'
>>> # Use hashlib
>>> import hashlib
>>> int(hashlib.sha1(s.encode("utf-8")).hexdigest(), 16) % (10 ** 8)
58097614L
>>> # Use hash()
>>> abs(hash(s)) % (10 ** 8)
82148974
(A little late to the party...)
The three ways I've gotten around this problem in the past are:
Example in Swift, picturing the foundry's explanation above and the Apple's documentation:
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func dismissViewController1AndPresentViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
vc1.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
self.presentViewController(vc1, animated: true, completion: nil)
}
func dismissViewController1AndPresentViewController2() {
self.dismissViewControllerAnimated(false, completion: { () -> Void in
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.presentViewController(vc2, animated: true, completion: nil)
})
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.dismissViewController1AndPresentViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func popViewController1AndPushViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
self.navigationController?.pushViewController(vc1, animated: true)
}
func popViewController1AndPushViewController2() {
self.navigationController?.popViewControllerAnimated(false)
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.navigationController?.pushViewController(vc2, animated: true)
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.popViewController1AndPushViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
Add android:inputType="number"
as an XML attribute.
It also can be run by exporting the bash and sh
of the gitbash C:\Program Files\git\bin\
in the Advance section of the environment variable of the Windows Server.
In Advance section in the path var kindly add the C:\Program Files\git\bin\
which will make the bash
and the sh
of the git-bash to be executable from the window cmd
.
Then,
Run the shell file as
bash shellscript.sh
or sh shellscript.sh
You guys don't need those complex things to set locales on Ubuntu/Debian. You don't even need /etc/local.gen
file.
Simply locale-gen
will do everything and the author only missed locales
package.
RUN apt-get update && apt-get install -y locales && rm -rf /var/lib/apt/lists/* \
&& locale-gen "en_US.UTF-8"
ENV LANG=en_US.UTF-8 \
LANGUAGE=en_US:en \
LC_ALL=en_US.UTF-8
I found this the simplest and the most effective. I confirm it works on Ubuntu 16.04.
Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.
I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.
Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.
just add /FORCE as linker flag and you're all set.
for instance, if you're working on CMakeLists.txt. Then add following line:
SET(CMAKE_EXE_LINKER_FLAGS "/FORCE")
Here's a vanilla js example to trigger any event:
function triggerEvent(el, type){
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
Let me expand a bit on a VonC's very comprehensive answer:
First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.
Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".
Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.
HTH
C11 timespec_get
It returns up to nanoseconds, rounded to the resolution of the implementation.
It is already implemented in Ubuntu 15.10. API looks the same as the POSIX clock_gettime
.
#include <time.h>
struct timespec ts;
timespec_get(&ts, TIME_UTC);
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
More details here: https://stackoverflow.com/a/36095407/895245
Try to use:
location.reload(true);
When this method receives a true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
More info:
You need to explicitly ask for the content type.
Add this line:
request.ContentType = "application/json; charset=utf-8";
At the appropriate place
/**
* This method gets the Key for the given Value
* @param paramName
* @return
*/
private String getKeyForValueFromMap(String paramName) {
String keyForValue = null;
if(paramName!=null)) {
Set<Entry<String,String>> entrySet = myMap().entrySet();
if(entrySet!=null && entrySet.size>0) {
for(Entry<String,String> entry : entrySet) {
if(entry!=null && paramName.equalsIgnoreCase(entry.getValue())) {
keyForValue = entry.getKey();
}
}
}
}
return keyForValue;
}
Not sure if it has changed since the accepted answer was accepted, but it is possible.
$location.search()
will return an object of key-value pairs, the same pairs as the query string. A key that has no value is just stored in the object as true. In this case, the object would be:
{"test_user_bLzgB": true}
You could access this value directly with $location.search().test_user_bLzgB
Example (with larger query string): http://fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse
Note: Due to hashes (as it will go to http://fiddle.jshell.net/#/url, which would create a new fiddle), this fiddle will not work in browsers that do not support js history (will not work in IE <10)
Edit:
As pointed out in the comments by @Naresh and @DavidTchepak, the $locationProvider
also needs to be configured properly: https://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration
Here is a list of special characters that you can escape when creating a string literal for JSON:
\b Backspace (ASCII code 08) \f Form feed (ASCII code 0C) \n New line \r Carriage return \t Tab \v Vertical tab \' Apostrophe or single quote \" Double quote \\ Backslash character
Reference: String literals
Some of these are more optional than others. For instance, your string should be perfectly valid whether you escape the tab character or leave in a tab literal. You should certainly be handling the backslash and quote characters, though.
If you are doing this on mac type: sudo chown -R $USER /usr/local that will give you administrative access to your files
I had similar Issue where we have GenericResponse object containing list of values
ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
redisMatchedDriverUrl,
HttpMethod.POST,
requestEntity,
ResponseDTO.class
);
Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects
ObjectMapper mapper = new ObjectMapper();
List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });
ProgressDialog
was deprecated in API level 26 .
refers to functions or elements that are in the process of being replaced by newer ones."Deprecated"
ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like
ProgressBar
, which can be embedded in your app's UI.
Advantage
I would personally say that ProgressBar
has the edge over the two .ProgressBar
is a user interface element that indicates the progress of an operation. Display progress bars to a user in a non-interruptive way. Show the progress bar in your app's user interface.
[UPDATE: 2021.01.04]
One thing that has changed since I first posted this in 2014, is the format of #pragma message
.
Nowadays, the parens are required!
#pragma message ("USER IS " USER)
#pragma message ("USER_VS IS " USER_VS)
That said, the 2016 code (using characters, not strings) still works in VS2019.
But, as @Artyer points out, the version involving c_strcmp
will NOT work in ANY modern compiler.
[UPDATE: 2018.05.03]
CAVEAT: Not all compilers implement the C++11 specification in the same way. The below code works in the compiler I tested on, while many commenters used a different compiler.
Quoting from Shafik Yaghmour's answer at: Computing length of a C string at compile time. Is this really a constexpr?
Constant expressions are not guaranteed to be evaluated at compile time, we only have a non-normative quote from draft C++ standard section 5.19 Constant expressions that says this though:
[...]>[ Note: Constant expressions can be evaluated during translation.—end note ]
That word can
makes all the difference in the world.
So, YMMV on this (or any) answer involving constexpr
, depending on the compiler writer's interpretation of the spec.
[UPDATED 2016.01.31]
As some didn't like my earlier answer because it avoided the whole compile time string compare
aspect of the OP by accomplishing the goal with no need for string compares, here is a more detailed answer.
You can't! Not in C98 or C99. Not even in C11. No amount of MACRO manipulation will change this.
The definition of const-expression
used in the #if
does not allow strings.
It does allow characters, so if you limit yourself to characters you might use this:
#define JACK 'J'
#define QUEEN 'Q'
#define CHOICE JACK // or QUEEN, your choice
#if 'J' == CHOICE
#define USER "jack"
#define USER_VS "queen"
#elif 'Q' == CHOICE
#define USER "queen"
#define USER_VS "jack"
#else
#define USER "anonymous1"
#define USER_VS "anonymous2"
#endif
#pragma message "USER IS " USER
#pragma message "USER_VS IS " USER_VS
You can! In C++11. If you define a compile time helper function for the comparison.
[2021.01.04: CAVEAT: This does not work in any MODERN compiler. See comment by @Artyer.]
// compares two strings in compile time constant fashion
constexpr int c_strcmp( char const* lhs, char const* rhs )
{
return (('\0' == lhs[0]) && ('\0' == rhs[0])) ? 0
: (lhs[0] != rhs[0]) ? (lhs[0] - rhs[0])
: c_strcmp( lhs+1, rhs+1 );
}
// some compilers may require ((int)lhs[0] - (int)rhs[0])
#define JACK "jack"
#define QUEEN "queen"
#define USER JACK // or QUEEN, your choice
#if 0 == c_strcmp( USER, JACK )
#define USER_VS QUEEN
#elif 0 == c_strcmp( USER, QUEEN )
#define USER_VS JACK
#else
#define USER_VS "unknown"
#endif
#pragma message "USER IS " USER
#pragma message "USER_VS IS " USER_VS
So, ultimately, you will have to change the way you accomlish your goal of choosing final string values for USER
and USER_VS
.
You can't do compile time string compares in C99, but you can do compile time choosing of strings.
If you really must do compile time sting comparisons, then you need to change to C++11 or newer variants that allow that feature.
[ORIGINAL ANSWER FOLLOWS]
Try:
#define jack_VS queen
#define queen_VS jack
#define USER jack // jack or queen, your choice
#define USER_VS USER##_VS // jack_VS or queen_VS
// stringify usage: S(USER) or S(USER_VS) when you need the string form.
#define S(U) S_(U)
#define S_(U) #U
UPDATE: ANSI token pasting is sometimes less than obvious. ;-D
Putting a single #
before a macro causes it to be changed into a string of its value, instead of its bare value.
Putting a double ##
between two tokens causes them to be concatenated into a single token.
So, the macro USER_VS
has the expansion jack_VS
or queen_VS
, depending on how you set USER
.
The stringify macro S(...)
uses macro indirection so the value of the named macro gets converted into a string. instead of the name of the macro.
Thus USER##_VS
becomes jack_VS
(or queen_VS
), depending on how you set USER
.
Later, when the stringify macro is used as S(USER_VS)
the value of USER_VS
(jack_VS
in this example) is passed to the indirection step S_(jack_VS)
which converts its value (queen
) into a string "queen"
.
If you set USER
to queen
then the final result is the string "jack"
.
For token concatenation, see: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html
For token string conversion, see: https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification
[UPDATED 2015.02.15 to correct a typo.]
The simple and best way to delete all files from a folder in PHP
$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
if(is_file($file))
unlink($file); //delete file
}
Got this source code from here - http://www.codexworld.com/delete-all-files-from-folder-using-php/
I realize this is a very old post, but I encountered a similar issue in which my displayed image always had a border around it. I was trying to fill the browser window with a single image. Adding styles like border:none; did not remove the border and neither did margin:0; or padding:0; or any combination of the three.
However, adding position:absolute;top:0;left:0; fixed the problem.
The original post above has position:absolute; but does not have top:0;left:0; and this was adding a default border on my page.
To illustrate the solution, this has a white border (to be precise, it has a top and left offset):
<img src="filename.jpg"
style="width:100%;height:100%;position:absolute;">
This does not have a border:
<img src="filename.jpg"
style="width:100%;height:100%;position:absolute;top:0;left:0;">
Hopefully this helps someone finding this post looking to resolve a similar problem.
A simple way to do that in VBA is:
YourText = "c:\excel\text.txt"
xString = Mid(YourText, 2 + Len(YourText) - InStr(StrReverse(YourText), "\" ))
Yes Jython does this, but it may or may not be what you want
NSLog(@"%@",CGRectCreateDictionaryRepresentation(rect));
I agree with the answers 1 and 2. However, I prefer to specify each library separately. This makes the depencencies clearer in big projects. Yet, there is the danger of mistyping the (case-sensitive) variable names. In that case there is no direct cmake error but some undefined references linker issues later on, which may take some time to resolve. Therefore I use the following cmake function:
function(VerifyVarDefined)
foreach(lib ${ARGV})
if(DEFINED ${lib})
else(DEFINED ${lib})
message(SEND_ERROR "Variable ${lib} is not defined")
endif(DEFINED ${lib})
endforeach()
endfunction(VerifyVarDefined)
For the example mentioned above, this looks like:
VerifyVarDefined(Boost_PROGRAM_OPTIONS_LIBRARY Boost_REGEX_LIBRARY)
target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} )
If I had written "BOOST_PROGRAM_OPTIONS_LIBRARY" there would have been an error triggered by cmake and not much later triggered by the linker.
In My case, the Problem was in Branch Name. My new branch name contains brackets, Once I renamed it and remove brackets, It's sorted.
You can also try this for the double quotes:
JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);
If you want to create a simple hyperlink instead of the pin it button,
Change this:
http://pinterest.com/pin/create/button/?url=
To this:
http://pinterest.com/pin/create/link/?url=
So, a complete URL might simply look like this:
<a href="//pinterest.com/pin/create/link/?url=http%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F&media=http%3A%2F%2Ffarm8.staticflickr.com%2F7027%2F6851755809_df5b2051c9_z.jpg&description=Next%20stop%3A%20Pinterest">Pin it</a>
Just an alternative to
ls -d "$PWD/"*
to pinpoint that *
is shell expansion, so
echo "$PWD/"*
would do the same (the drawback you cannot use -1
to separate by new lines, not spaces).
[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.
This one is great:
<style type="text/css">
textarea.test
{
width: 100%;
height: 100%;
border-color: Transparent;
}
</style>
<textarea class="test"></textarea>
This may help you!
$latlng='{"lat":29.5345741,"lng":75.0342196}';
$latlng=json_decode($latlng,TRUE); // array
echo "Lat=".$latlng['lat'];
echo '<br/>';
echo "Lng=".$latlng['lng'];
echo '<br/>';
$latlng2='{"lat":29.5345741,"lng":75.0342196}';
$latlng2=json_decode($latlng2); // object
echo "Lat=".$latlng2->lat;
echo '<br/>';
echo "Lng=".$latlng2->lng;
echo '<br/>';
Question: Is there a simple way to do this in the current release of Python?
Answer: There is no simple (direct) way to do this in the current release of Python.
Reference: Please refer to docs.python.org/2/library/datetime.html, section 8.1.2. timedelta Objects. As we may understand from that, we cannot increment month directly since it is not a uniform time unit.
Plus: If you want first day -> first day and last day -> last day mapping you should handle that separately for different months.
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
I had a doubt that whether the encrypted text will be same for single text when encryption done by multiple times on a same text??
This depends strongly on the crypto algorithm you use:
It Worked for me: For Current Date
$date = date('Y-m-d', strtotime("+1 day"));
for anydate:
date('Y-m-d', strtotime("+1 day", strtotime($date)));
Here's what I ended up with. It's a listing of all properties and methods, and I listed all parameters for each method. I didn't succeed on getting all of the values.
foreach(System.Reflection.AssemblyName an in System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies()){
System.Reflection.Assembly asm = System.Reflection.Assembly.Load(an.ToString());
foreach(Type type in asm.GetTypes()){
//PROPERTIES
foreach (System.Reflection.PropertyInfo property in type.GetProperties()){
if (property.CanRead){
Response.Write("<br>" + an.ToString() + "." + type.ToString() + "." + property.Name);
}
}
//METHODS
var methods = type.GetMethods();
foreach (System.Reflection.MethodInfo method in methods){
Response.Write("<br><b>" + an.ToString() + "." + type.ToString() + "." + method.Name + "</b>");
foreach (System.Reflection.ParameterInfo param in method.GetParameters())
{
Response.Write("<br><i>Param=" + param.Name.ToString());
Response.Write("<br> Type=" + param.ParameterType.ToString());
Response.Write("<br> Position=" + param.Position.ToString());
Response.Write("<br> Optional=" + param.IsOptional.ToString() + "</i>");
}
}
}
}
If you only want non-negative integers, try:
^\d+$
in my case the issue was in the EOL Conversion. (End Of Line).
i created the file on windows and only after i converted the EOL from windows(CR LF) to unix(LF), everything went well.
I did the conversion with Notepad++ very easily from: Edit -> EOL Conversion -> Unix(LF)
The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.
>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]
A table alias cannot start with a @
. So, give @Temp
another alias (or leave out the two-part naming altogether):
SELECT *
FROM @TEMP t
WHERE t.ID = 1;
Also, a single equals sign is traditionally used in SQL for a comparison.
To print certain lines in a text file. Create a "lines2print" list and then just print when the enumeration is "in" the lines2print list. To get rid of extra '\n' use line.strip() or line.strip('\n'). I just like "list comprehension" and try to use when I can. I like the "with" method to read text files in order to prevent leaving a file open for any reason.
lines2print = [26,30] # can be a big list and order doesn't matter.
with open("filepath", 'r') as fp:
[print(x.strip()) for ei,x in enumerate(fp) if ei in lines2print]
or if list is small just type in list as a list into the comprehension.
with open("filepath", 'r') as fp:
[print(x.strip()) for ei,x in enumerate(fp) if ei in [26,30]]
The gritty terminal was written to use Jsch, but with better handling and vt102 emulation. You can take a look at the code there. We use it and it works just fine.
Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?
e.g.
private void Example(int? arg1, int? arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
A derived class is not the the same class as its base class and you may or may not care whether any members of the base class are initialized at the time of the construction of the derived class. That is a determination made by the programmer not by the compiler.
you can do it short like this:
matrix = [["A, B, C, D, E"]*5]
print(matrix)
[['A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E']]
If the destination table does exist but you don't want to specify column names:
DECLARE @COLUMN_LIST NVARCHAR(MAX);
DECLARE @SQL_INSERT NVARCHAR(MAX);
SET @COLUMN_LIST = (SELECT DISTINCT
SUBSTRING(
(
SELECT ', table1.' + SYSCOL1.name AS [text()]
FROM sys.columns SYSCOL1
WHERE SYSCOL1.object_id = SYSCOL2.object_id and SYSCOL1.is_identity <> 1
ORDER BY SYSCOL1.object_id
FOR XML PATH ('')
), 2, 1000)
FROM
sys.columns SYSCOL2
WHERE
SYSCOL2.object_id = object_id('dbo.TableOne') )
SET @SQL_INSERT = 'INSERT INTO dbo.TableTwo SELECT ' + @COLUMN_LIST + ' FROM dbo.TableOne table1 WHERE col3 LIKE ' + @search_key
EXEC sp_executesql @SQL_INSERT
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
string rootNode = XmlDoc.ChildNodes[0].Name;
The following should work for anyone who is looking for a combination of text and hyperlink within an Android app.
In string.xml
:
<string name="applink">Looking for Digital Visiting card?
<a href="https://play.google.com/store/apps/details?id=com.themarkwebs.govcard">Get it here</a>
</string>
Now you can utilise this string
in any given View
like this:
<TextView
android:id="@+id/getapp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:textColor="@color/main_color_grey_600"
android:textSize="15sp"
android:text="@string/applink"/>
Now, in your Activity or Fragment, do the following:
TextView getapp =(TextView) findViewById(R.id.getapp);
getapp.setMovementMethod(LinkMovementMethod.getInstance());
By now, you don't require to set android:autoLink="web"
or android:linksClickable="true"
using this approach.
I hope you will find this helpful.
I'm using the first approach but a bit different that allows to address the problems you mentioned.
Everything that is needed to run tests for DAOs is in source control. It includes schema and scripts to create the DB (docker is very good for this). If the embedded DB can be used - I use it for speed.
The important difference with the other described approaches is that the data that is required for test is not loaded from SQL scripts or XML files. Everything (except some dictionary data that is effectively constant) is created by application using utility functions/classes.
The main purpose is to make data used by test
It basically means that these utilities allow to declaratively specify only things essential for the test in test itself and omit irrelevant things.
To give some idea of what it means in practice, consider the test for some DAO which works with Comment
s to Post
s written by Authors
. In order to test CRUD operations for such DAO some data should be created in the DB. The test would look like:
@Test
public void savedCommentCanBeRead() {
// Builder is needed to declaratively specify the entity with all attributes relevant
// for this specific test
// Missing attributes are generated with reasonable values
// factory's responsibility is to create entity (and all entities required by it
// in our example Author) in the DB
Post post = factory.create(PostBuilder.post());
Comment comment = CommentBuilder.comment().forPost(post).build();
sut.save(comment);
Comment savedComment = sut.get(comment.getId());
// this checks fields that are directly stored
assertThat(saveComment, fieldwiseEqualTo(comment));
// if there are some fields that are generated during save check them separately
assertThat(saveComment.getGeneratedField(), equalTo(expectedValue));
}
This has several advantages over SQL scripts or XML files with test data:
I find it more convenient that tests do commit when they are executed. Firstly, some effects (for example DEFERRED CONSTRAINTS
) cannot be checked if commit never happens. Secondly, when a test fails the data can be examined in the DB as it is not reverted by the rollback.
Of cause this has a downside that test may produce a broken data and this will lead to the failures in other tests. To deal with this I try to isolate the tests. In the example above every test may create new Author
and all other entities are created related to it so collisions are rare. To deal with the remaining invariants that can be potentially broken but cannot be expressed as a DB level constraint I use some programmatic checks for erroneous conditions that may be run after every single test (and they are run in CI but usually switched off locally for performance reasons).
The standard approach is to use sprintf(buffer, "%lu", value);
to write a string rep of value
to buffer
. However, overflow is a potential problem, as sprintf
will happily (and unknowingly) write over the end of your buffer.
This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.
This site discusses this and related problems at some length.
Some libraries offer snprintf
as an alternative which lets you specify a maximum buffer size.
1.) First off, what is the correct terminology for an array created on the end of the name element of an input tag in a form?
"Oftimes Confusing PHPism"
As far as JavaScript is concerned a bunch of form controls with the same name are just a bunch of form controls with the same name, and form controls with names that include square brackets are just form controls with names that include square brackets.
The PHP naming convention for form controls with the same name is sometimes useful (when you have a number of groups of controls so you can do things like this:
<input name="name[1]">
<input name="email[1]">
<input name="sex[1]" type="radio" value="m">
<input name="sex[1]" type="radio" value="f">
<input name="name[2]">
<input name="email[2]">
<input name="sex[2]" type="radio" value="m">
<input name="sex[2]" type="radio" value="f">
) but does confuse some people. Some other languages have adopted the convention since this was originally written, but generally only as an optional feature. For example, via this module for JavaScript.
2.) How do I get the information from that array with JavaScript?
It is still just a matter of getting the property with the same name as the form control from elements
. The trick is that since the name of the form controls includes square brackets, you can't use dot notation and have to use square bracket notation just like any other JavaScript property name that includes special characters.
Since you have multiple elements with that name, it will be a collection rather then a single control, so you can loop over it with a standard for loop that makes use of its length property.
var myForm = document.forms.id_of_form;
var myControls = myForm.elements['p_id[]'];
for (var i = 0; i < myControls.length; i++) {
var aControl = myControls[i];
}
If you made an account using google/ other oauth, then you need to set a bitbucket password for your account first. The URL for that is : https://bitbucket.org/account/user// or look for Bitbucket settings under the menu.
Then can login from git (I tried via command line). I use the built in manager for credentials :
credential.helper=manager
Now, after I set the password on the bitbucket site (email verified too), and tried to push again, it prompted me for the password, then pushed the code.
Menu location image on bitbucket web page -> http://ctrlv.in/747291 as of May 2016.
getElementsByClassName()
returns HTMLCollection so you could try this
var button = document.getElementsByClassName("navButton")[0];
Edit
var buttons = document.getElementsByClassName("navButton");
for(i=0;buttons.length;i++){
buttons[i].onmouseover = function(){
this.className += ' active' //add class
this.setAttribute("src", "images/arrows/top_o.png");
}
}
Getting check status
var checked = $("#selectall").is(":checked");
Then for setting
$("input:checkbox").attr("checked",checked);
In CSharp, If you create the method/function outline with it's Parms, then when you add the three forward slashes it will auto generate the summary and parms section.
So I put in:
public string myMethod(string sImput1, int iInput2)
{
}
I then put the three /// before it and Visual Studio's gave me this:
/// <summary>
///
/// </summary>
/// <param name="sImput1"></param>
/// <param name="iInput2"></param>
/// <returns></returns>
public string myMethod(string sImput1, int iInput2)
{
}
You can use something like this
<script type="text/javascript">
var myObject = {'name':'Kasun', 'address':'columbo','age': '29'}
var count = Object.keys(myObject).length;
console.log(count);
</script>
That's the RHEL release version.
You can see the kernel version by typing uname -r
. It'll be 2.6.something.
Using MySQL connector and Entity Framework Core 2.0
My issue was that I was getting an exception like fx. Ex.Message = "The required column 'body' was not present in the results of a 'FromSql' operation.". So, in order to fetch rows via a stored procedure in this manner, you must return all columns for that entity type which the DBSet is associated with, even if you don't need to access all of it for your current request.
var result = _context.DBSetName.FromSql($"call storedProcedureName()").ToList();
OR with parameters
var result = _context.DBSetName.FromSql($"call storedProcedureName({optionalParam1})").ToList();
IList<T> is an interface so you can inherit another class and still implement IList<T> while inheriting List<T> prevents you to do so.
For example if there is a class A and your class B inherits it then you can't use List<T>
class A : B, IList<T> { ... }
Updated 10-second countdown using class Clock extends Component
import React, { Component } from 'react';
class Clock extends Component {
constructor(props){
super(props);
this.state = {currentCount: 10}
}
timer() {
this.setState({
currentCount: this.state.currentCount - 1
})
if(this.state.currentCount < 1) {
clearInterval(this.intervalId);
}
}
componentDidMount() {
this.intervalId = setInterval(this.timer.bind(this), 1000);
}
componentWillUnmount(){
clearInterval(this.intervalId);
}
render() {
return(
<div>{this.state.currentCount}</div>
);
}
}
module.exports = Clock;
For those that use coffeescript, I've put the code we use globally to disable the submit buttons on our most widely used form. An adaption of Adil's answer above.
$('#new_post button').prop 'disabled', true
$('#new_post #post_message').keyup ->
$('#new_post button').prop 'disabled', if @value == '' then true else false
return
This whole problem would just go away if LinearLayout had a setAdapter method, because then when you told someone to use it instead the alternative would be trivial.
If you actually want a scrolling ListView inside another scrolling view this won't help, but otherwise this will at least give you an idea.
You need to create a custom adapter to combine all the content you want to scroll over and set the ListView's adapter to that.
I don't have sample code handy, but if you want something like.
<ListView/>
(other content)
<ListView/>
Then you need to create an adapter that represents all of that content. The ListView/Adapters are smart enough to handle different types as well, but you need to write the adapter yourself.
The android UI API just isn't as mature as pretty much everything else out there, so it doesn't have the same niceties as other platforms. Also, when doing something on android you need to be in an android (unix) mindset where you expect that to do anything you're probably going to have to assemble functionality of smaller parts and write a bunch of your own code to get it to work.
new Date().toLocaleTimeString()
Please have a look at http://jsfiddle.net/2dJAN/59/
$("#submit").click(function () {
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
});
After removing and updating pod I still had same issue.
I've found that previous developer put flag in 'Build Settings -> Other Linker Flags' with Framework name (in my case -framework 'OGVKit') that made the issue.
After deleting that flag, project builds properly.
This can be accomplished with a simple VBA function. Excel has support for a Worksheet Change Sub which can be programmed to put a date in a related column every time it fires.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
End If
End Sub
A quick explanation. The following "if" statement checks for two things: (1) if it is the second column that changed (Column B), and (2) if the cell 3 columns over (Column E) is currently empty.
If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
If both conditions are true, then it puts the date into the cell in Column E with the NOW()
function.
Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
I would join @Nicholas in recommending PyInstaller (with the --onefile
flag), but be warned: do not use the "latest release", PyInstaller 1.3 -- it's years old. Use the "pre-release" 1.4, download it here -- or even better the code from the svn repo -- install SVN and run svn co http://svn.pyinstaller.org/trunk pyinstaller
.
As @Nicholas implies, dynamic libraries cannot be run from the same file as the rest of the executable -- but fortunately they can be packed together with all the rest in a "self-unpacking" executable that will unpack itself into some temporary directory as needed; PyInstaller does a good job at this (and at many other things -- py2exe
is more popular, but pyinstaller
in my opinion is preferable in all other respects).
Here's another one:
PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate
Name LockedOut LastLogonDate
---- --------- -------------
Yxxxxxxx True 14/11/2014 10:19:20
Bxxxxxxx True 18/11/2014 08:38:34
Administrator True 03/11/2014 20:32:05
Other parameters worth mentioning:
Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive
Get-Help Search-ADAccount -ShowWindow
To serialize the response into a class, define the target class
public class Result {
public Long user_id;
}
And map response to it:
Response response = given().body(requestBody).when().post("/admin");
Result result = response.as(Result.class);
You must have Jackson or Gson in the classpath as the documentation states: http://rest-assured.googlecode.com/svn/tags/2.3.1/apidocs/com/jayway/restassured/response/ResponseBodyExtractionOptions.html#as(java.lang.Class)
Take a look at https://hashids.org/ it is open source and in many languages.
Their page outlines some of the pitfalls of other approaches.
Sorry my fault, try this...
#!/bin/bash
:
declare -r HEX_DIGITS="0123456789ABCDEF"
dec_value=$1
hex_value=""
until [ $dec_value == 0 ]; do
rem_value=$((dec_value % 16))
dec_value=$((dec_value / 16))
hex_digit=${HEX_DIGITS:$rem_value:1}
hex_value="${hex_digit}${hex_value}"
done
echo -e "${hex_value}"
Example:
$ ./dtoh 1024
400
Here's one implementation, what works like $.prop(name[,value])
or $.attr(name[,value])
function. If b
variable is filled, visibility is set according to that, and this
is returned (allowing to continue with other properties), otherwise it returns visibility value.
jQuery.fn.visible = function (b) {
if(b === undefined)
return this.css('visibility')=="visible";
else {
this.css('visibility', b? 'visible' : 'hidden');
return this;
}
}
Example:
$("#result").visible(true).on('click',someFunction);
if($("#result").visible())
do_something;
I was able to fix this on Windows 7 64-bit running Python 3.4.3 by running the set
command at a command prompt to determine the existing Visual Studio tools environment variable; in my case it was VS140COMNTOOLS
for Visual Studio Community 2015.
Then run the following (substituting the variable on the right-hand side if yours has a different name):
set VS100COMNTOOLS=%VS140COMNTOOLS%
This allowed me to install the PyCrypto module that was previously giving me the same error as the OP.
For a more permanent solution, add this environment variable to your Windows environment via Control Panel ("Edit the system environment variables"), though you might need to use the actual path instead of the variable substitution.
The real reason you want to use NVARCHAR is when you have different languages in the same column, you need to address the columns in T-SQL without decoding, you want to be able to see the data "natively" in SSMS, or you want to standardize on Unicode.
If you treat the database as dumb storage, it is perfectly possible to store wide strings and different (even variable-length) encodings in VARCHAR (for instance UTF-8). The problem comes when you are attempting to encode and decode, especially if the code page is different for different rows. It also means that the SQL Server will not be able to deal with the data easily for purposes of querying within T-SQL on (potentially variably) encoded columns.
Using NVARCHAR avoids all this.
I would recommend NVARCHAR for any column which will have user-entered data in it which is relatively unconstrained.
I would recommend VARCHAR for any column which is a natural key (like a vehicle license plate, SSN, serial number, service tag, order number, airport callsign, etc) which is typically defined and constrained by a standard or legislation or convention. Also VARCHAR for user-entered, and very constrained (like a phone number) or a code (ACTIVE/CLOSED, Y/N, M/F, M/S/D/W, etc). There is absolutely no reason to use NVARCHAR for those.
So for a simple rule:
VARCHAR when guaranteed to be constrained NVARCHAR otherwise
Generalizing Afanasii Kurakin's answer, we have:
function replaceAt(str, index, ch) {
return str.replace(/./g, (c, i) => i == index ? ch : c);
}
let str = 'Hello World';
str = replaceAt(str, 1, 'u');
console.log(str); // Hullo World
_x000D_
Let's expand and explain both the regular expression and the replacer function:
function replaceAt(str, index, newChar) {
function replacer(origChar, strIndex) {
if (strIndex === index)
return newChar;
else
return origChar;
}
return str.replace(/./g, replacer);
}
let str = 'Hello World';
str = replaceAt(str, 1, 'u');
console.log(str); // Hullo World
_x000D_
The regular expression .
matches exactly one character. The g
makes it match every character in a for loop. The replacer
function is called given both the original character and the index of where that character is in the string. We make a simple if
statement to determine if we're going to return either origChar
or newChar
.
I have found a great work-around for this. It really only works practically if you want to be able to select up to 4 or so options from your drop down list but here it is:
For each "item" create as many rows as drop-down items you'd like to be able to select. So if you want to be able to select up to 3 characteristics from a given drop down list for each person on your list, create a total of 3 rows for each person. Then merge A:1-A:3, B:1-B:3, C:1-C:3 etc until you reach the column that you'd like your drop-down list to be. Don't merge those cells, instead place the your Data Validation drop-down in each of those cells.
Hope this is clear!!
I used interop to open Excel and to modify the column widths once the data was done. If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow. Instead, I generated a .CSV
, then opened the .CSV
in Excel. This has its own problems, but I've found this the quickest method.
First, convert the .CSV
:
// Convert array data into CSV format.
// Modified from http://csharphelper.com/blog/2018/04/write-a-csv-file-from-an-array-in-c/.
private string GetCSV(List<string> Headers, List<List<double>> Data)
{
// Get the bounds.
var rows = Data[0].Count;
var cols = Data.Count;
var row = 0;
// Convert the array into a CSV string.
StringBuilder sb = new StringBuilder();
// Add the first field in this row.
sb.Append(Headers[0]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Headers[col]);
// Move to the next line.
sb.AppendLine();
for (row = 0; row < rows; row++)
{
// Add the first field in this row.
sb.Append(Data[0][row]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Data[col][row]);
// Move to the next line.
sb.AppendLine();
}
// Return the CSV format string.
return sb.ToString();
}
Then, export it to Excel:
public void ExportToExcel()
{
// Initialize app and pop Excel on the screen.
var excelApp = new Excel.Application { Visible = true };
// I use unix time to give the files a unique name that's almost somewhat useful.
DateTime dateTime = DateTime.UtcNow;
long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
var path = @"C:\Users\my\path\here + unixTime + ".csv";
var csv = GetCSV();
File.WriteAllText(path, csv);
// Create a new workbook and get its active sheet.
excelApp.Workbooks.Open(path);
var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
// iterate over each value and throw it in the chart
for (var column = 0; column < Data.Count; column++)
{
((Excel.Range)workSheet.Columns[column + 1]).AutoFit();
}
currentSheet = workSheet;
}
You'll have to install some stuff, too...
Right click on the solution from solution explorer and select "Manage NuGet Packages." - add Microsoft.Office.Interop.Excel
It might actually work right now if you created the project the way interop wants you to. If it still doesn't work, I had to create a new project in a different category. Under New > Project, select Visual C# > Windows Desktop > Console App. Otherwise, the interop tools won't work.
In case I forgot anything, here's my 'using' statements:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
try
data = pd.read_csv("data.csv")
data.shape
and in the output you can see something like (aa,bb) where aa is the # of rows
In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :
By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers:
old 1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new 1: insert into customers (customer_name) values ('Marks Ltd')
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks Ltd
If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off
to switch off the behaviour while running the script:
SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd
You might want to add set define on
at the end of the script to restore the default behaviour.
If you want to sort data either in Ascending or Descending order based on particular column, using sequlize js
, use the order
method of sequlize
as follows
// Will order the specified column by descending order
order: sequelize.literal('column_name order')
e.g. order: sequelize.literal('timestamp DESC')
Create a BroadcastReceiver
and register it to receive ACTION_BOOT_COMPLETED. You also need RECEIVE_BOOT_COMPLETED permission.
Read: Listening For and Broadcasting Global Messages, and Setting Alarms
When you use addEventListener
, this
will be bound automatically. So if you want a reference to the element on which the event handler is installed, just use this
from within your function:
productLineSelect.addEventListener('change',getSelection,false);
function getSelection(){
var value = sel.options[this.selectedIndex].value;
alert(value);
}
If you want to pass in some other argument from the context where you call addEventListener
, you can use a closure, like this:
productLineSelect.addEventListener('change', function(){
// pass in `this` (the element), and someOtherVar
getSelection(this, someOtherVar);
},false);
function getSelection(sel, someOtherVar){
var value = sel.options[sel.selectedIndex].value;
alert(value);
alert(someOtherVar);
}
You can't break from a Groovy each loop, but you can break from a java "enhanced" for loop.
def a = [1, 2, 3, 4, 5, 6, 7]
for (def i : a) {
if (i < 2)
continue
if (i > 5)
break
println i
}
Output:
2
3
4
5
This might not fit for absolutely every situation but it's helped for me :)
SURE: Simply,
This is what you need :
io.to(socket.id).emit("event", data);
whenever a user joined to the server, socket details will be generated including ID. This is the ID really helps to send a message to particular people.
first we need to store all the socket.ids in array,
var people={};
people[name] = socket.id;
here name is the receiver name. Example:
people["ccccc"]=2387423cjhgfwerwer23;
So, now we can get that socket.id with the receiver name whenever we are sending message:
for this we need to know the receivername. You need to emit receiver name to the server.
final thing is:
socket.on('chat message', function(data){
io.to(people[data.receiver]).emit('chat message', data.msg);
});
Hope this works well for you.
Good Luck!!
SHA1
is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.
However, breaking a SHA1
hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.
So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.
As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod
eliminate information from your input. Suppose you calculate mod 5
and you get 0
. What was the input? Was it 0
, 5
or 500
? You see, you can't really 'go back' in this case.
Way 1: only works for dataURL, not for other types of url.
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);
Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)
//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename, {type:mimeType});})
);
}
//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
console.log(file);
})
Both works in Chrome and Firefox.
Now this become even simpler and more flexible by using CSS GRID.You just have to overlap the blured background(imgbg) with the text(h2)
<div class="container">
<div class="imgbg"></div>
<h2>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Facilis enim
aut rerum mollitia quas voluptas delectus facere magni cum unde?:)
</h2>
</div>
and the css:
.container {
display: grid;
width: 30em;
}
.imgbg {
background: url(bg3.jpg) no-repeat center;
background-size: cover;
grid-column: 1/-1;
grid-row: 1/-1;
filter: blur(4px);
}
.container h2 {
text-transform: uppercase;
grid-column: 1/-1;
grid-row: 1/-1;
z-index: 2;
}
Try doing it like this.
User::where('email', $userEmail)
->update([
'member_type' => $plan
]);
I’ve found that in order to properly delete the old history from the new repository, you have to do a little more work after the filter-branch
step.
Do the clone and the filter:
git clone --no-hardlinks foo bar; cd bar
git filter-branch --subdirectory-filter subdir/you/want
Remove every reference to the old history. “origin” was keeping track of your clone, and “original” is where filter-branch saves the old stuff:
git remote rm origin
git update-ref -d refs/original/refs/heads/master
git reflog expire --expire=now --all
Even now, your history might be stuck in a packfile that fsck won’t touch. Tear it to shreds, creating a new packfile and deleting the unused objects:
git repack -ad
There is an explanation of this in the manual for filter-branch.
try this single command to both delete and insert the data:
DELETE MyTable
OUTPUT DELETED.Col1, DELETED.COl2,...
INTO MyBackupTable
working sample:
--set up the tables
DECLARE @MyTable table (col1 int, col2 varchar(5))
DECLARE @MyBackupTable table (col1 int, col2 varchar(5))
INSERT INTO @MyTable VALUES (1,'A')
INSERT INTO @MyTable VALUES (2,'B')
INSERT INTO @MyTable VALUES (3,'C')
INSERT INTO @MyTable VALUES (4,'D')
--single command that does the delete and inserts
DELETE @MyTable
OUTPUT DELETED.Col1, DELETED.COl2
INTO @MyBackupTable
--show both tables final values
select * from @MyTable
select * from @MyBackupTable
OUTPUT:
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
(4 row(s) affected)
col1 col2
----------- -----
(0 row(s) affected)
col1 col2
----------- -----
1 A
2 B
3 C
4 D
(4 row(s) affected)
The correct way from hibernate doc:
Session s = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
// here get object
List<Employee> list = s.createCriteria(Employee.class).list();
tx.commit();
} catch (HibernateException ex) {
if (tx != null) {
tx.rollback();
}
Logger.getLogger("con").info("Exception: " + ex.getMessage());
ex.printStackTrace(System.err);
} finally {
s.close();
}
HibernateUtil code (can find at Google):
public class HibernateUtil {
private static final SessionFactory tmrSessionFactory;
private static final Ejb3Configuration tmrEjb3Config;
private static final EntityManagerFactory tmrEntityManagerFactory;
static {
try {
tmrSessionFactory = new Configuration().configure("tmr.cfg.xml").buildSessionFactory();
tmrEjb3Config = new Ejb3Configuration().configure("tmr.cfg.xml");
tmrEntityManagerFactory = tmrEjb3Config.buildEntityManagerFactory();
} catch (HibernateException ex) {
Logger.getLogger("app").log(Level.WARN, ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return tmrSessionFactory;
}
/* getters and setters here */
}
I would like to thank the person who posted the answer, but he has deleted the post. We can do it like this.
$("#yourElem").uploadify({
'uploader': ...,
'script': ...
'fileExt' : '*.jpg;*.gif;', //add allowed extensions
.....,
'onSelect': function(e, q, f) {
var validExtensions = ['jpg','gif']; //array of valid extensions
var fileName = f.name;
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
if ($.inArray(fileNameExt, validExtensions) == -1){
alert("Invalid file type");
$("#yourElem").uploadifyCancel(q);
return false;
}
}
});
Thanks for the answer, it really worked...
string input = "this is a test";
string[] afterSplit = input.Split();
foreach (var word in afterSplit)
Console.WriteLine(word);
Result:
this
is
a
test
Or if you don't want to reinvent the URI parsing wheel use URI.js
To get the value of a parameter named foo:
new URI((''+document.location)).search(true).foo
What that does is
Here's a fiddle for this.... http://jsfiddle.net/m6tett01/12/
See the above definition where it states that a callback function is passed off to some other function and at some point it is called.
In C++ it is desirable to have callback functions call a classes method. When you do this you have access to the member data. If you use the C way of defining a callback you will have to point it to a static member function. This is not very desirable.
Here is how you can use callbacks in C++. Assume 4 files. A pair of .CPP/.H files for each class. Class C1 is the class with a method we want to callback. C2 calls back to C1's method. In this example the callback function takes 1 parameter which I added for the readers sake. The example doesn't show any objects being instantiated and used. One use case for this implementation is when you have one class that reads and stores data into temporary space and another that post processes the data. With a callback function, for every row of data read the callback can then process it. This technique cuts outs the overhead of the temporary space required. It is particularly useful for SQL queries that return a large amount of data which then has to be post-processed.
/////////////////////////////////////////////////////////////////////
// C1 H file
class C1
{
public:
C1() {};
~C1() {};
void CALLBACK F1(int i);
};
/////////////////////////////////////////////////////////////////////
// C1 CPP file
void CALLBACK C1::F1(int i)
{
// Do stuff with C1, its methods and data, and even do stuff with the passed in parameter
}
/////////////////////////////////////////////////////////////////////
// C2 H File
class C1; // Forward declaration
class C2
{
typedef void (CALLBACK C1::* pfnCallBack)(int i);
public:
C2() {};
~C2() {};
void Fn(C1 * pThat,pfnCallBack pFn);
};
/////////////////////////////////////////////////////////////////////
// C2 CPP File
void C2::Fn(C1 * pThat,pfnCallBack pFn)
{
// Call a non-static method in C1
int i = 1;
(pThat->*pFn)(i);
}
The problem with all of the answers given so far is that on the something borrowed site, the Mac bar remains totally hidden when scrolling up, and the provided answers don't accomplish that.
If you just use scrollTo
and then the user later scrolls up, the nav bar is revealed again, so it seems you have to put the whole site inside of a div and force scrolling to happen inside of that div rather than on the body which keeps the nav bar hidden during scrolling in any direction.
You can, however, still reveal the nav bar by touching near the top of the screen on apple devices.
Angular can only access static files like images and config files from assets folder. Nice way to download string path of remote stored image and load it to template.
public concateInnerHTML(path: string): string {
if(path){
let front = "<img class='d-block' src='";
let back = "' alt='slide'>";
let result = front + path + back;
return result;
}
return null;
}
In a Component imlement DoCheck interface and past in it formula for database. Data base query is only a sample.
ngDoCheck(): void {
this.concatedPathName = this.concateInnerHTML(database.query('src'));
}
And in html tamplate <div [innerHtml]="concatedPathName"></div>
I second NLog too because it works with unmanaged code too. I suppose it could be possibe to use log4net and log4cxx together, but NLog handles both managed and unmanaged code out of the box.
I also looked at Common.Logging, a facade that makes abstraction of the logging api, it supports log4net, NLog and Entreprise Library. I don't think i'll use it, but i like how they use lambdas to improve performance when logging is disabled (a feature shared with NLog and probably others).
If you frequently need to access the Nth element of a sequence, std::list
, which is implemented as a doubly linked list, is probably not the right choice. std::vector
or std::deque
would likely be better.
That said, you can get an iterator to the Nth element using std::advance
:
std::list<Object> l;
// add elements to list 'l'...
unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
std::list<Object>::iterator it = l.begin();
std::advance(it, N);
// 'it' points to the element at index 'N'
}
For a container that doesn't provide random access, like std::list
, std::advance
calls operator++
on the iterator N
times. Alternatively, if your Standard Library implementation provides it, you may call std::next
:
if (l.size() > N)
{
std::list<Object>::iterator it = std::next(l.begin(), N);
}
std::next
is effectively wraps a call to std::advance
, making it easier to advance an iterator N
times with fewer lines of code and fewer mutable variables. std::next
was added in C++11.
Well if you know the basics behind them, it shouldn't be too hard.
Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.
When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place.
Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).
Check out this fast hash table implementation:
I use this:
Math.round(Date.now() / 1000)
No need for new object creation (see doc Date.now())
Decision tree between ES5, ES6 and TypeScript
Do you mind having a build step?
Do you want to use types?
ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers
ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.
TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).
Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
If you do not want to depend on throwing exception (which you probably should not) you can try this:
public static <T> T cast(Object o, Class<T> clazz) {
return clazz.isInstance(o) ? clazz.cast(o) : null;
}
Putting *args
and/or **kwargs
as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.
For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:
def my_sum(*args):
return sum(args)
It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.
You don’t actually have to call them args
and kwargs
, that’s just a convention. It’s the *
and **
that do the magic.
The official Python documentation has a more in-depth look.
Define a new handler and runnable:
private Handler handler = new Handler(Looper.getMainLooper());
private Runnable runnable = new Runnable() {
@Override
public void run() {
// Do what ever you want
}
};
Call post delayed:
handler.postDelayed(runnable, sleep_time);
Remove your callback from your handler:
handler.removeCallbacks(runnable);
var filteredFiles = Directory
.GetFiles(path, "*.*")
.Where(file => file.ToLower().EndsWith("aspx") || file.ToLower().EndsWith("ascx"))
.ToList();
Edit 2014-07-23
You can do this in .NET 4.5 for a faster enumeration:
var filteredFiles = Directory
.EnumerateFiles(path) //<--- .NET 4.5
.Where(file => file.ToLower().EndsWith("aspx") || file.ToLower().EndsWith("ascx"))
.ToList();
To install a specific package:
conda install <pkg>=<version>
eg:
conda install matplotlib=1.4.3
This happened to me also, while i was reading text containing Hebrew from a .txt
file.
I clicked: file -> save as
and I saved this file as a UTF-8
encoding
Most mocking frameworks (Moq and RhinoMocks included) generate proxy classes as a substitute for your mocked class, and override the virtual methods with behavior that you define. Because of this, you can only mock interfaces, or virtual methods on concrete or abstract classes. Additionally, if you're mocking a concrete class, you almost always need to provide a parameterless constructor so that the mocking framework knows how to instantiate the class.
Why the aversion to creating interfaces in your code?
Goes to the right and can be used the same way for the left
.yourComponent
{
float: right;
bottom: 0;
}
I have also tried that error , I got it right by just adding /hello/any name because it is path that there must be an hello/name
example : instead of just putting http://localhost/app_dev.php
put it like this way http://localhost/name_of_your_project/web/app_dev.php/hello/ai
it will display Hello Ai . I hope I answer your question.
I think that they should perform generally the same, but there are some differences.
START
is generally used to start applications or to start the default application for a given file type. That way if you START http://mywebsite.com
it doesn't do START iexplore.exe http://mywebsite.com
.
START myworddoc.docx
would start Microsoft Word and open myworddoc.docx.CALL myworddoc.docx
does the same thing... however START
provides more options for the window state and things of that nature. It also allows process priority and affinity to be set.
In short, given the additional options provided by start, it should be your tool of choice.
START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
[command/program] [parameters]
"title" Title to display in window title bar.
path Starting directory.
B Start application without creating a new window. The
application has ^C handling ignored. Unless the application
enables ^C processing, ^Break is the only way to interrupt
the application.
I The new environment will be the original environment passed
to the cmd.exe and not the current environment.
MIN Start window minimized.
MAX Start window maximized.
SEPARATE Start 16-bit Windows program in separate memory space.
SHARED Start 16-bit Windows program in shared memory space.
LOW Start application in the IDLE priority class.
NORMAL Start application in the NORMAL priority class.
HIGH Start application in the HIGH priority class.
REALTIME Start application in the REALTIME priority class.
ABOVENORMAL Start application in the ABOVENORMAL priority class.
BELOWNORMAL Start application in the BELOWNORMAL priority class.
NODE Specifies the preferred Non-Uniform Memory Architecture (NUMA)
node as a decimal integer.
AFFINITY Specifies the processor affinity mask as a hexadecimal number.
The process is restricted to running on these processors.
The affinity mask is interpreted differently when /AFFINITY and
/NODE are combined. Specify the affinity mask as if the NUMA
node's processor mask is right shifted to begin at bit zero.
The process is restricted to running on those processors in
common between the specified affinity mask and the NUMA node.
If no processors are in common, the process is restricted to
running on the specified NUMA node.
WAIT Start application and wait for it to terminate.
The plattform agnostic way would be 'sLineBreak': http://www.freepascal.org/docs-html/rtl/system/slinebreak.html
Write('Hello' + sLineBreak + 'World!');
I could solve similar problem with System.Net.HTTP by adding assembly reference in app.config of main application.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.1.1" newVersion="4.0.0.0" />
</dependentAssembly></runtime>
To round an integer to 1 significant figure the basic idea is to convert it to a floating point with 1 digit before the point and round that, then convert it back to its original integer size.
To do this we need to know the largest power of 10 less than the integer. We can use floor of the log 10 function for this.
from math import log10, floor def round_int(i,places): if i == 0: return 0 isign = i/abs(i) i = abs(i) if i < 1: return 0 max10exp = floor(log10(i)) if max10exp+1 < places: return i sig10pow = 10**(max10exp-places+1) floated = i*1.0/sig10pow defloated = round(floated)*sig10pow return int(defloated*isign)
Here is the example:
var charCode = "a".charCodeAt(0);_x000D_
console.log(charCode);
_x000D_
Or if you have longer strings:
var string = "Some string";_x000D_
_x000D_
for (var i = 0; i < string.length; i++) {_x000D_
console.log(string.charCodeAt(i));_x000D_
}
_x000D_
String.charCodeAt(x)
method will return ASCII character code at a given position.
I made this very simple function that works wonders:
function safeOrZero(route) {
try {
Function(`return (${route})`)();
} catch (error) {
return 0;
}
return Function(`return (${route})`)();
}
The route is whatever chain of values that can blow up. I use it for jQuery/cheerio and objects and such.
Examples 1: a simple object such as this const testObj = {items: [{ val: 'haya' }, { val: null }, { val: 'hum!' }];};
.
But it could be a very large object that we haven't even made. So I pass it through:
let value1 = testobj.items[2].val; // "hum!"
let value2 = testobj.items[3].val; // Uncaught TypeError: Cannot read property 'val' of undefined
let svalue1 = safeOrZero(`testobj.items[2].val`) // "hum!"
let svalue2 = safeOrZero(`testobj.items[3].val`) // 0
Of course if you prefer you can use null
or 'No value'
... Whatever suit your needs.
Usually a DOM query or a jQuery selector may throw an error if it's not found. But using something like:
const bookLink = safeOrZero($('span.guidebook > a')[0].href);
if(bookLink){
[...]
}
db:create
- Creates the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.
db:create:all
- Creates the database for all environments.
db:drop
- Drops the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.
db:drop:all
- Drops the database for all environments.
db:migrate
- Runs migrations for the current environment that have not run yet. By default it will run migrations only in the development environment.
db:migrate:redo
- Runs db:migrate:down and db:migrate:up or db:migrate:rollback and db:migrate:up depending on the specified migration.
db:migrate:up
- Runs the up for the given migration VERSION.
db:migrate:down
- Runs the down for the given migration VERSION.
db:migrate:status
- Displays the current migration status.
db:migrate:rollback
- Rolls back the last migration.
db:version
- Prints the current schema version.
db:forward
- Pushes the schema to the next version.
db:seed
- Runs the db/seeds.rb file.
db:schema:load
Recreates the database from the schema.rb file. Deletes existing data.
db:schema:dump
Dumps the current environment’s schema to db/schema.rb.
db:structure:load
- Recreates the database from the structure.sql file.
db:structure:dump
- Dumps the current environment’s schema to db/structure.sql.
(You can specify another file with SCHEMA=db/my_structure.sql
)
db:setup
Runs db:create, db:schema:load and db:seed.
db:reset
Runs db:drop and db:setup.
db:migrate:reset
- Runs db:drop, db:create and db:migrate.
db:test:prepare
- Check for pending migrations and load the test schema. (If you run rake without any arguments it will do this by default.)
db:test:clone
- Recreate the test database from the current environment’s database schema.
db:test:clone_structure
- Similar to db:test:clone, but it will ensure that your test database has the same structure, including charsets and collations, as your current environment’s database.
db:environment:set
- Set the current RAILS_ENV environment in the ar_internal_metadata table. (Used as part of the protected environment check.)
db:check_protected_environments
- Checks if a destructive action can be performed in the current RAILS_ENV environment. Used internally when running a destructive action such as db:drop or db:schema:load.
"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types."
"The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."
Here is my source.
If you don't want to bother with a file, you can do something like this in your code:
static
{
Logger rootLogger = Logger.getRootLogger();
rootLogger.setLevel(Level.INFO);
rootLogger.addAppender(new ConsoleAppender(
new PatternLayout("%-6r [%p] %c - %m%n")));
}
Can't you just add a reference to System.Web
and then you can use Server.MapPath
?
Edit: Nowadays I'd recommend using the HostingEnvironment.MapPath
Method:
It's a static method in System.Web
assembly that Maps a virtual path to a physical path on the server. It doesn't require a reference to HttpContext
.
First()
is causing this if your select returns 0 rows. You either have to catch that exception, or use FirstOrDefault()
which will return null in case of no elements.
You can simply Create a logout button and add this link to it and it will utimately log you out from the app and will redirect to your desired site:
https://appengine.google.com/_ah/logout?continue=http://www.YOURSITE.com
just toggle YOURSITE with your website
See this bug: https://bugs.launchpad.net/ubuntu/+source/mysql-5.6/+bug/1435823
There seems to be a temporary fix there
Create a newfile /etc/tmpfiles.d/mysql.conf:
# systemd tmpfile settings for mysql
# See tmpfiles.d(5) for details
d /var/run/mysqld 0755 mysql mysql -
After reboot, mysql should start normally.
if you are using linux on cloud, then usually you don't have chance to touch the real hardware using your hands. so you don't see the configuration interface when booting for the first time, and of course cannot configure it. As a result, the firstboot
service will always be in the way to rc.local
. The solution is to disable firstboot
by doing:
sudo chkconfig firstboot off
if you are not sure why your rc.local
does not run, you can always check from /etc/rc.d/rc
file because this file will always run and call other subsystems (e.g. rc.local).
You can't decode a unicode
, and you can't encode a str
. Try doing it the other way around.
In my case, I only updated the custom view.
// DO NOT LIKE THIS
customView.layoutIfNeeded() // Change to view.layoutIfNeeded()
UIView.animate(withDuration: 0.5) {
customViewConstraint.constant = 100.0
customView.layoutIfNeeded() // Change to view.layoutIfNeeded()
}
Try git checkout -f master
.
-f
or --force
Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html
When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.
When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.
It means that the variable it is a prefix to is available to be used within a block.
Try this one
.parent_div{
display: flex;
}
public async Task<ActionResult> Index()
{
apiTable table = new apiTable();
table.Name = "Asma Nadeem";
table.Roll = "6655";
string str = "";
string str2 = "";
HttpClient client = new HttpClient();
string json = JsonConvert.SerializeObject(table);
StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);
str = "" + response.Content + " : " + response.StatusCode;
if (response.IsSuccessStatusCode)
{
str2 = "Data Posted";
}
return View();
}
If you want to execute that command, you should probably change:
PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'
to:
PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)
File.Copy(@"C:\oldFile.txt", @"C:\newFile.txt", true);
Please do not forget to overwrite the previous file! Make sure you add the third param., by adding the third param, you allow the file to be overwritten. Else you could use a try catch for the exception.
Regards, G
I tried joonty's answer, but I also got the
exec: 1: not found
error. This is what works best for me (confirmed to work in zsh also):
#!/bin/bash
LOG_FILE=/tmp/both.log
exec > >(tee ${LOG_FILE}) 2>&1
echo "this is stdout"
chmmm 77 /makeError
The file /tmp/both.log afterwards contains
this is stdout
chmmm command not found
The /tmp/both.log is appended unless you remove the -a from tee.
Hint: >(...)
is a process substitution. It lets the exec
to the tee
command as if it were a file.
The following worked for me (though I think port 2101 did not really contribute to this):
-Dcom.sun.management.jmxremote.port=2100
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.rmi.port=2101
-Djava.rmi.server.hostname=<IP_ADDRESS>OR<HOSTNAME>
I am connecting from a remote machine to a server which has Docker running and the process is inside the container. Also, I stopped firewallD but I don't think that was the issue as I could telnet to 2100 even with the firewall open. Hope it helps.
To test and see if you can access your MQTT server from outside world (outside of your VM or local machine), you can install one of the MQTT publishing and monitoring tools such as MQTT-Spy on your outside-world machine and then subscribe for '#" (meaning all the topics).
You can follow this by the method @hardillb mentioned in his answer above and test back and forth such as this:
On the machine with Mosquitto Server running,
On the outside-word machine with mqtt-spy running,
I have mainly mentioned mqtt-spy since it's multi-platform and easy to use. You can go with any other tool really.
And also to my knowledge to run the mosquitto_sub
and mosquitto_pub
you need to have mosquitto-clients installed on your Linux machine running the test (in my case Ubuntu) which can be done easily by,
sudo apt-get install mosquitto-clients
Thank you guys for this answers. But I think the accepted answer needs more clarity, As i found difficulty in getting the solution.
We may set the environment variable as mentioned in the answer by w0rldart .
In this case(after seting envmnt var) we may run the phpFile by opening start >> CMD and typing commands like,
php.exe <path to file location>
or
php <path to file location>
example:
php.exe C:\xampp\htdocs\test.php
you can open Start >> CMD as administrator and write like
<path to php.exe in xampp's php folder> <path to file location>
example:
C:\xampp\php\php.exe C:\xampp\htdocs\test.php
or
C:\xampp\php\php C:\xampp\htdocs\test.php
Hopes this will help somebody.
# prevent mime based attacks
Header set X-Content-Type-Options "nosniff"
This header prevents "mime" based attacks. This header prevents Internet Explorer from MIME-sniffing a response away from the declared content-type as the header instructs the browser not to override the response content type. With the nosniff option, if the server says the content is text/html, the browser will render it as text/html.
I was able to achieve this in ASP.NET MVC using the client IP address and freegeoip.net API. freegeoip.net is free and does not require any license.
Below is the sample code I used.
String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
string url = "http://freegeoip.net/json/" + UserIP.ToString();
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;
You can go through this post for more details.Hope it helps!
Fix: Unlock your device before running it.
Hi Guys: Think I may have a fix for this:
Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!
My solution: Because all others did not work for me. I deleted the symlinks at C:\ProgramData\Oracle\Java\javapath. this makes eclipse to run with the jre declared in the PATH. This is better for me because I want to develop Java with the JRE I chose, not the system JRE. Often you want to develop with older versions and such
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void)
{
int i = 0;
char *a = (char *) malloc(sizeof(char) * 1024);
while (1) {
scanf("%c", &a[i]);
if (a[i] == '\n') {
break;
}
else {
i++;
}
}
a[i] = '\0';
i = 0;
printf("\n");
while (a[i] != '\0') {
printf("%c", a[i]);
i++;
}
free(a);
getch();
return 0;
}
You can get current login customer name from session in following way :
$customer = Mage::getSingleton('customer/session')->getCustomer();
This will return the customer details of current login customer.
Now you can get customer name by using getName()
echo $customer->getName();