async
methods are different than normal methods. Whatever you return from async
methods are wrapped in a Task
.
If you return no value(void) it will be wrapped in Task
, If you return int
it will be wrapped in Task<int>
and so on.
If your async method needs to return int
you'd mark the return type of the method as Task<int>
and you'll return plain int
not the Task<int>
. Compiler will convert the int
to Task<int>
for you.
private async Task<int> MethodName()
{
await SomethingAsync();
return 42;//Note we return int not Task<int> and that compiles
}
Sameway, When you return Task<object>
your method's return type should be Task<Task<object>>
public async Task<Task<object>> MethodName()
{
return Task.FromResult<object>(null);//This will compile
}
Since your method is returning Task
, it shouldn't return any value. Otherwise it won't compile.
public async Task MethodName()
{
return;//This should work but return is redundant and also method is useless.
}
Keep in mind that async method without an await
statement is not async
.
Finalize is the backstop method, called by the garbage collector when it reclaims an object. Dispose is the "deterministic cleanup" method, called by applications to release valuable native resources (window handles, database connections, etc.) when they are no longer needed, rather than leaving them held indefinitely until the GC gets round to the object.
As the user of an object, you always use Dispose. Finalize is for the GC.
As the implementer of a class, if you hold managed resources that ought to be disposed, you implement Dispose. If you hold native resources, you implement both Dispose and Finalize, and both call a common method that releases the native resources. These idioms are typically combined through a private Dispose(bool disposing) method, which Dispose calls with true, and Finalize calls with false. This method always frees native resources, then checks the disposing parameter, and if it is true it disposes managed resources and calls GC.SuppressFinalize.
SQlite3 has a method named row_factory. This method would allow you to access the values by column name.
https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name
you can join both tables even on UPDATE
statements,
UPDATE a
SET a.marks = b.marks
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
for faster performance, define an INDEX
on column marks
on both tables.
using SUBQUERY
UPDATE tempDataView
SET marks =
(
SELECT marks
FROM tempData b
WHERE tempDataView.Name = b.Name
)
I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.)
There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the HTMLPrettify.py file - https://github.com/victorporof/Sublime-HTMLPrettify/issues/12
You need to alias the subquery. Thus, your statement should be:
Select Z.id
From (
Select id, time
From dbo.tablea
Union All
Select id, time
From dbo.tableb
) As Z
Group By Z.id
Dictionary Class is exactly what you want, correct.
You can declare the field directly as Dictionary, instead of IDictionary, but that's up to you.
You can also use day names like Mon
for Monday, Tue
for Tuesday, etc. It's more human friendly.
The arguments
object is not actually an instance of an Array, and does not have any of the Array methods. So, arguments.slice(...)
will not work because the arguments object does not have the slice method.
Arrays do have this method, and because the arguments
object is very similar to an array, the two are compatible. This means that we can use array methods with the arguments object. And since array methods were built with arrays in mind, they will return arrays rather than other argument objects.
So why use Array.prototype
? The Array
is the object which we create new arrays from (new Array()
), and these new arrays are passed methods and properties, like slice. These methods are stored in the [Class].prototype
object. So, for efficiency sake, instead of accessing the slice method by (new Array()).slice.call()
or [].slice.call()
, we just get it straight from the prototype. This is so we don't have to initialise a new array.
But why do we have to do this in the first place? Well, as you said, it converts an arguments object into an Array instance. The reason why we use slice, however, is more of a "hack" than anything. The slice method will take a, you guessed it, slice of an array and return that slice as a new array. Passing no arguments to it (besides the arguments object as its context) causes the slice method to take a complete chunk of the passed "array" (in this case, the arguments object) and return it as a new array.
use this code.
in layout:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/my_checkbox" *** here
android:checked="true"/>
add a new drawable : my_checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="false"
android:drawable="@drawable/checkbox_off_background"/>
<item
android:state_checked="true"
android:drawable="@drawable/checkbox_on_background"/>
and end create 2 drawable :
checkbox_off_background.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<size
android:height="25dp" *** your size
android:width="25dp"/>
</shape>
</item>
<item android:drawable="@android:drawable/checkbox_off_background"/>
and too, checkbox_on_background.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<size
android:height="25dp"
android:width="25dp"/>
</shape>
</item>
<item android:drawable="@android:drawable/checkbox_on_background"/>
Use .getMinutes()
to get the current minutes, then add 20 and use .setMinutes()
to update the date object.
var twentyMinutesLater = new Date();
twentyMinutesLater.setMinutes(twentyMinutesLater.getMinutes() + 20);
I was also looking for this a while back. I ran into HTMLDOC http://www.easysw.com/htmldoc/ which is a free open source command line app that takes an HTML file as an argument and spits out a PDF from it. It's worked for me pretty well for my side project, but it all depends on what you actually need.
The company that makes it sells the compiled binaries, but you are free to download and compile from source and use it for free. I managed to compile a pretty recent revision (for version 1.9) and I intend on releasing a binary installer for it in a few days, so if you're interested I can provide a link to it as soon as I post it.
Edit (2/25/2014): Seems like the docs and site moved to http://www.msweet.org/projects.php?Z1
You can use cut
:
cut -c N- file.txt > new_file.txt
-c:
characters
file.txt:
input file
new_file.txt:
output file
N-:
Characters from N to end to be cut and output to the new file.
Can also have other args like: 'N' , 'N-M', '-M' meaning nth character, nth to mth character, first to mth character respectively.
This will perform the operation to each line of the input file.
You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)
Once the user have choose a image you can read the file-path of the chosen image and place it into your html.
Example:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
If I understood what you want:
dictionary.Add("key", new List<string>());
later...
dictionary["key"].Add("string to your list");
do this:
$("tr.item").each(function(i, tr) {
var value = $("span.value", tr).text();
var quantity = $("input.quantity", tr).val();
});
It depends on whether you are using JPA or Hibernate.
From the JPA 2.0 spec, the defaults are:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
And in hibernate, all is Lazy
UPDATE:
The latest version of Hibernate aligns with the above JPA defaults.
You can also get the value by the following way
$(document).ready(function(){
$("#start").click(function(){
alert($(this).find("input[class='myClass']").val());
});
});
Change IDs and data attributes as you wish!
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.
‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.
So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.
The exponential function is e^x
where e
is a mathematical constant called Euler's number, approximately 2.718281
. This value has a close mathematical relationship with pi
and the slope of the curve e^x
is equal to its value at every point. np.exp()
calculates e^x
for each value of x
in your input array.
I spent about an hour looking for a more robust javascript option, and did not find one. It just so happens that in the past few days I've been fiddling with hammer.js (Hammer.js is a library that lets you manipulate all sorts of touch events easily) and mostly failing at what I was trying to do.
With that caveat, and understanding I am by no means a javascript expert, this is a solution I came up with that basically leverages hammer.js to capture the pinch-zoom and double-tap events and then log and discard them.
Make sure you include hammer.js in your page and then try sticking this javascript in the head somewhere:
< script type = "text/javascript" src="http://hammerjs.github.io/dist/hammer.min.js"> < /script >_x000D_
< script type = "text/javascript" >_x000D_
_x000D_
// SPORK - block pinch-zoom to force use of tooltip zoom_x000D_
$(document).ready(function() {_x000D_
_x000D_
// the element you want to attach to, probably a wrapper for the page_x000D_
var myElement = document.getElementById('yourwrapperelement');_x000D_
// create a new hammer object, setting "touchAction" ensures the user can still scroll/pan_x000D_
var hammertime = new Hammer(myElement, {_x000D_
prevent_default: false,_x000D_
touchAction: "pan"_x000D_
});_x000D_
_x000D_
// pinch is not enabled by default in hammer_x000D_
hammertime.get('pinch').set({_x000D_
enable: true_x000D_
});_x000D_
_x000D_
// name the events you want to capture, then call some function if you want and most importantly, add the preventDefault to block the normal pinch action_x000D_
hammertime.on('pinch pinchend pinchstart doubletap', function(e) {_x000D_
console.log('captured event:', e.type);_x000D_
e.preventDefault();_x000D_
})_x000D_
});_x000D_
</script>
_x000D_
int copt = 1;
int element = 0;
int[] array = { 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5 };
for (int i = 0; i < array.Length; i++)
{
for (int j = i + 1; j < array.Length - 1; j++)
{
if (array[i] == array[j])
{
element = array[i];
copt++;
break;
}
}
}
Console.WriteLine("the repeat element is {0} and it's appears {1} times ", element, copt);
Console.ReadKey();
// the output is the element is 3 and appears 9 times
With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.
# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12
# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert
To verify the contents of the JKS, you can use this command:
keytool -list -v -keystore mykeystore.jks
If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.
You can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top:
<input type="text" onChange={e => this.setState({ text: e.target.value })}/>
I used this tutorial to install R on my mac, and it had me install xquartz
and a fortran complier (gfortran
) as well.
My suggestion would be to brew untap homebrew/science
and then brew tap homebrew/science
and try again, also, make sure you don't have any errors when you run brew doctor
Hope this helps
Just Do,
CTRL + X
CTRL + C
It will ask you to save file, Press Y, then you are done.
You could just use glob
with recursive = true
, the pattern **
will match any files and zero or more directories, subdirectories and symbolic links to directories.
import glob, os
os.chdir("C:\\Users\\username\\Desktop\\MAIN_DIRECTORY")
for file in glob.glob("*/.csv", recursive = true):
print(file)
There are 2 ways to do this :
1. From Xml
use :
<TextView
.........
android:gravity="center"/>
2. From Java class
use :
[textview].setGravity(Gravity.CENTER);
Try adding 2 spaces (or a backslash \
) after the first line:
[Name of link](url)
My line of text\
Visually:
[Name of link](url)<space><space>
My line of text\
Output:
<p><a href="url">Name of link</a><br>
My line of text<br></p>
Not sure why your current code isn't working but if you don't specifically need a date object this will work:
$first_date = strtotime($date_raw);
$second_date = strtotime('-1 day', $first_date);
print 'First Date ' . date('Y-m-d', $first_date);
print 'Next Date ' . date('Y-m-d', $second_date);
new Date('2012.08.10').getTime() / 1000
Check the JavaScript Date documentation.
The proper JPA query format would be:
el.name IN :inclList
If you're using an older version of Hibernate as your provider you have to write:
el.name IN (:inclList)
but that is a bug (HHH-5126) (EDIT: which has been resolved by now).
Also, It can be done with LINQ
var str = "Hello@Hello&Hello(Hello)";
var characters = str.Select(c => char.IsLetter(c) ? c : ',')).ToArray();
var output = new string(characters);
Console.WriteLine(output);
You should be able to rebase your branch on master:
git checkout feature1
git rebase master
Manage all conflicts that arise. When you get to the commits with the bugfixes (already in master), Git will say that there were no changes and that maybe they were already applied. You then continue the rebase (while skipping the commits already in master) with
git rebase --skip
If you perform a git log
on your feature branch, you'll see the bugfix commit appear only once, and in the master portion.
For a more detailed discussion, take a look at the Git book documentation on git rebase
(https://git-scm.com/docs/git-rebase) which cover this exact use case.
================ Edit for additional context ====================
This answer was provided specifically for the question asked by @theomega, taking his particular situation into account. Note this part:
I want to prevent [...] commits on my feature branch which have no relation to the feature implementation.
Rebasing his private branch on master is exactly what will yield that result. In contrast, merging master into his branch would precisely do what he specifically does not want to happen: adding a commit that is not related to the feature implementation he is working on via his branch.
To address the users that read the question title, skip over the actual content and context of the question, and then only read the top answer blindly assuming it will always apply to their (different) use case, allow me to elaborate:
git merge master
as in @Sven's answer).Finally, if you're unhappy with the fact that this answer is not the best fit for your situation even though it was for @theomega, adding a comment below won't be particularly helpful: I don't control which answer is selected, only @theomega does.
I have written my own function which takes 2 strings and 1 int (text size)
The full text and the part of the text you want to change the size of it.
It returns a SpannableStringBuilder which you can use it in text view.
public static SpannableStringBuilder setSectionOfTextSize(String text, String textToChangeSize, int size){
SpannableStringBuilder builder=new SpannableStringBuilder();
if(textToChangeSize.length() > 0 && !textToChangeSize.trim().equals("")){
//for counting start/end indexes
String testText = text.toLowerCase(Locale.US);
String testTextToBold = textToChangeSize.toLowerCase(Locale.US);
int startingIndex = testText.indexOf(testTextToBold);
int endingIndex = startingIndex + testTextToBold.length();
//for counting start/end indexes
if(startingIndex < 0 || endingIndex <0){
return builder.append(text);
}
else if(startingIndex >= 0 && endingIndex >=0){
builder.append(text);
builder.setSpan(new AbsoluteSizeSpan(size, true), startingIndex, endingIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}else{
return builder.append(text);
}
return builder;
}
I was getting e.data.indexOf is not a function
error, after debugging it, I found that it was actually a TypeError
, which meant, indexOf()
being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf()
method to make it work
e.data.toString().indexOf('<stringToBeMatchedToPosition>')
Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.
I needed to "set a variable if undefined" in several places. I created a function using @Alnitak answer. Hopefully it helps someone.
function setDefaultVal(value, defaultValue){
return (value === undefined) ? defaultValue : value;
}
Usage:
hasPoints = setDefaultVal(this.hasPoints, true);
Just add a new table
in the td
you want. Example: http://jsfiddle.net/AbE3Q/
<table border="1">
<tr>
<td>ABC</td>
<td>ABC</td>
<td>ABC</td>
<td>ABC</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>
<table border="1">
<tr>
<td>qweqwewe</td>
<td>qweqwewe</td>
</tr>
<tr>
<td>qweqwewe</td>
<td>qweqwewe</td>
</tr>
<tr>
<td>qweqwewe</td>
<td>qweqwewe</td>
</tr>
</table>
</td>
<td>Item3</td>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
_x000D_
I'm not sure about this, but give it a shot.
In your strings.xml define:
<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>
In your layout:
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:entries="@array/array_name"
/>
I've heard this doesn't always work on the designer, but it compiles fine.
To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,
ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = "dodge", stat = 'identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.android.volley:volley:1.1.1'
}
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
fun peticion(){
val jsonObject = JSONObject()
jsonObject.put("user", "jairo")
jsonObject.put("password", "1234")
val queue = Volley.newRequestQueue(this)
val url = "http://192.168.0.3/get_user.php"
// GET: JsonObjectRequest( url, null,
// POST: JsonObjectRequest( url, jsonObject,
val jsonObjectRequest = JsonObjectRequest( url, jsonObject,
Response.Listener { response ->
// Check if the object 'msm' does not exist
if(response.isNull("msm")){
println("Name: "+response.getString("nombre1"))
}
else{
// If the object 'msm' exists we print it
println("msm: "+response.getString("msm"))
}
},
Response.ErrorListener { error ->
error.printStackTrace()
println(error.toString())
}
)
queue.add(jsonObjectRequest)
}
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
// we receive the parameters
$json = file_get_contents('php://input');
$params = json_decode($json);
error_reporting(0);
require_once 'conexion.php';
$mysqli=getConex();
$user=$params->user;
$password=$params->password;
$res=array();
$verifica_usuario=mysqli_query($mysqli,"SELECT * FROM usuarios WHERE usuario='$user' and clave='$password'");
if(mysqli_num_rows($verifica_usuario)>0){
$query="SELECT * FROM usuarios WHERE usuario='$user'";
$result=$mysqli->query($query);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$res=$row;
}
}
else{
$res=array('msm'=>"Incorrect user or password");
}
$jsonstring = json_encode($res);
header('Content-Type: application/json');
echo $jsonstring;
?>
<?php
function getConex(){
$servidor="localhost";
$usuario="root";
$pass="";
$base="db";
$mysqli = mysqli_connect($servidor,$usuario,$pass,$base);
if (mysqli_connect_errno($mysqli)){
echo "Fallo al conectar a MySQL: " . mysqli_connect_error();
}
$mysqli->set_charset('utf8');
return $mysqli;
}
?>
30x30 is points, which means 30px @1x, 60px @2x, not somewhere in-between. Also, it's not a great idea to embed the title of the tab into the image—you're going to have pretty poor accessibility and localization results like that.
If you are using Bearing Token Auth, the above samples do not return an Application User.
Instead, use this:
ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);
This works in apsnetcore 2.0. Have not tried in earlier versions.
You can create an appropriate table through management studio interface and insert data into the table like it's shown below. It may take some time depending on the amount of data, but it is very handy.
double[] arr = new double[] {1.38, 2.56, 4.3};
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( new Supplier<ArrayList<Double>>() {
public ArrayList<Double> get() {
return( new ArrayList<Double>() );
}
} ) );
While I agree about not adhering blindly to dogmatic rules, does the "lock stealing" scenario seem so eccentric to you? A thread could indeed acquire the lock on your object "externally"(synchronized(theObject) {...}
), blocking other threads waiting on synchronized instance methods.
If you don't believe in malicious code, consider that this code could come from third parties (for instance if you develop some sort of application server).
The "accidental" version seems less likely, but as they say, "make something idiot-proof and someone will invent a better idiot".
So I agree with the it-depends-on-what-the-class-does school of thought.
Edit following eljenso's first 3 comments:
I've never experienced the lock stealing problem but here is an imaginary scenario:
Let's say your system is a servlet container, and the object we're considering is the ServletContext
implementation. Its getAttribute
method must be thread-safe, as context attributes are shared data; so you declare it as synchronized
. Let's also imagine that you provide a public hosting service based on your container implementation.
I'm your customer and deploy my "good" servlet on your site. It happens that my code contains a call to getAttribute
.
A hacker, disguised as another customer, deploys his malicious servlet on your site. It contains the following code in the init
method:
synchronized (this.getServletConfig().getServletContext()) { while (true) {} }
Assuming we share the same servlet context (allowed by the spec as long as the two servlets are on the same virtual host), my call on getAttribute
is locked forever. The hacker has achieved a DoS on my servlet.
This attack is not possible if getAttribute
is synchronized on a private lock, because 3rd-party code cannot acquire this lock.
I admit that the example is contrived and an oversimplistic view of how a servlet container works, but IMHO it proves the point.
So I would make my design choice based on security consideration: will I have complete control over the code that has access to the instances? What would be the consequence of a thread's holding a lock on an instance indefinitely?
Quick solution: set PYTHONHOME and PYTHONPATH and include PYTHONHOME on PATH
For example if you installed to c:\Python27
set PYTHONHOME=c:\Python27
set PYTHONPATH=c:\Python27\Lib
set PATH=%PYTHONHOME%;%PATH%
Make sure you don't have a trailing '\' on the PYTHON* vars, this seems to break it aswel.
Add onload listener in componentDidMount
class Comp1 extends React.Component {
constructor(props) {
super(props);
this.handleLoad = this.handleLoad.bind(this);
}
componentDidMount() {
window.addEventListener('load', this.handleLoad);
}
componentWillUnmount() {
window.removeEventListener('load', this.handleLoad)
}
handleLoad() {
$("myclass") // $ is available here
}
}
The following groovy snippet should pass the version (as you've already supplied), and store it in the job's variables as 'miniVersion'.
import hudson.model.*
def env = System.getenv()
def version = env['currentversion']
def m = version =~/\d{1,2}/
def minVerVal = m[0]+"."+m[1]
def pa = new ParametersAction([
new StringParameterValue("miniVersion", minVerVal)
])
// add variable to current job
Thread.currentThread().executable.addAction(pa)
The variable will then be accessible from other build steps. e.g.
echo miniVersion=%miniVersion%
Outputs:
miniVersion=12.34
I believe you'll need to use the "System Groovy Script" (on the Master node only) as opposed to the "Groovy Plugin" - https://wiki.jenkins-ci.org/display/JENKINS/Groovy+plugin#Groovyplugin-GroovyScriptvsSystemGroovyScript
I believe the previous (Jenkins 1.x) behaviour stopped working because of this Security Advisory...
It's possible to restore the previous behaviour by setting the system property hudson.model.ParametersAction.keepUndefinedParameters
to true
. This is potentially very unsafe and intended as a short-term workaround only.
java -Dhudson.model.ParametersAction.keepUndefinedParameters=true -jar jenkins.war
To allow specific, known safe parameter names to be passed to builds, set the system property hudson.model.ParametersAction.safeParameters
to a comma-separated list of safe parameter names.
e.g.
java -Dhudson.model.ParametersAction.safeParameters=miniVersion,FOO,BAR -jar jenkins.war
The answer I have finally found is that the SMTP service on the server is not using the same certificate as https.
The diagnostic steps I had read here make the assumption they use the same certificate and every time I've tried this in the past they have done and the diagnostic steps are exactly what I've done to solve the problem several times.
In this case those steps didn't work because the certificates in use were different, and the possibility of this is something I had never come across.
The solution is either to export the actual certificate from the server and then install it as a trusted certificate on my machine, or to get a different valid/trusted certificate for the SMTP service on the server. That is currently with our IT department who administer the servers to decide which they want to do.
The mPDF docs state that the first argument of Output()
is the file path, second is the saving mode - you need to set it to 'F'
.
$mpdf->Output('filename.pdf','F');
Note that usage of a SerialPort.DataReceived
event is optional. You can set proper timeout using SerialPort.ReadTimeout
and continuously call SerialPort.Read()
after you wrote something to a port until you get a full response.
Moreover you can use SerialPort.BaseStream
property to extract an underlying Stream
instance. The benefit of using a Stream
is that you can easily utilize various decorators with it:
var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and
// overrides needen virtual methods.
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.
For more information check:
(source: scottgu.com)
You need something like this? Use the Linq Dynamic Query Library (download includes examples).
Check out ScottGu's blog for more examples.
I think that an alternative would be to:
Yes, this is a rather dirty and low level approach but it should work without problems
this website shows several formatting options.
Example:
SELECT CONVERT(VARCHAR(10), GETDATE(), 105)
This is the complete basic structure for 100% width layout in Bootstrap v3.0.0. You shouldn't wrap your <div class="row">
with container
class. Cause container
class will take lots of margin and this will not provide you full screen (100% width) layout where bootstrap has removed container-fluid class from their mobile-first version v3.0.0.
So just start writing <div class="row">
without container class and you are ready to go with 100% width layout.
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Basic 100% width Structure</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="http://getbootstrap.com/assets/js/html5shiv.js"></script>
<script src="http://getbootstrap.com/assets/js/respond.min.js"></script>
<![endif]-->
<style>
.red{
background-color: red;
}
.green{
background-color: green;
}
</style>
</head>
<body>
<div class="row">
<div class="col-md-3 red">Test content</div>
<div class="col-md-9 green">Another Content</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>
To see the result by yourself I have created a bootply. See the live output there. http://bootply.com/82136 And the complete basic bootstrap 3 100% width layout I have created a gist. you can use that. Get the gist from here
Reply me if you need more further assistance. Thanks.
Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.
If InStr(myString, "A") > 0 Then
For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.
Left(oldStr, InStr(oldStr, "A"))
I have not changed any package name. The following two steps worked for me. After doing the following, the application was installed as a NEW one , eventhough there was two applications with the same package name.
1) In the build.gradle
applicationId "mynew.mynewpackage.com"
2) In the AndroidManifest.xml android:authorities="mynew.mynewpackage.com.fileprovider"
Yes, that's usually happens after 1440s (24 minutes)
You can look at the docs for the SlugField
to get to know more about it in more descriptive way.
An alternative way without using javascript serializer:
public static string DataTableToJSON(DataTable Dt)
{
string[] StrDc = new string[Dt.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < Dt.Columns.Count; i++)
{
StrDc[i] = Dt.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\":\"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("[");
for (int i = 0; i < Dt.Rows.Count; i++)
{
string TempStr = HeadStr;
for (int j = 0; j < Dt.Columns.Count; j++)
{
TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString().Trim());
}
//Sb.AppendFormat("{{{0}}},",TempStr);
Sb.Append("{"+TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
if(Sb.ToString().Length>0)
Sb.Append("]");
return StripControlChars(Sb.ToString());
}
//To strip control characters:
//A character that does not represent a printable character but //serves to initiate a particular action.
public static string StripControlChars(string s)
{
return Regex.Replace(s, @"[^\x20-\x7F]", "");
}
From the DOCS
Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.
SYNTAX:
number_expression | number[:digitInfo[:locale]]
where expression
is a number:
digitInfo
is a string which has a following format:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
<div class="example" align="center">
<div class="menuholder">
<ul class="menu slide">
<li><a href="index.php?id=1" class="blue">Home</a></li>
<li><a href="index.php?id=14" class="blue">About Us</a></li>
<li><a href="index.php?id=4" class="blue">Mens</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=15">Coats & Jackets</a></dd>
<dd><a href="index.php?id=22">Chinos</a></dd>
<dd><a href="index.php?id=23">Jeans</a></dd>
<dd><a href="index.php?id=24">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=25">Linen</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=26">Polo Shirts</a></dd>
<dd><a href="index.php?id=16">Shirts Casual</a></dd>
<dd><a href="index.php?id=27">Shirts Formal</a></dd>
<dd><a href="index.php?id=28">Shorts</a></dd>
<dd><a href="index.php?id=18">Sportswear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=19">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=20">Trousers Casual</a></dd>
<dd><a href="index.php?id=29">Trousers Formal</a></dd>
<dd><a href="index.php?id=30">Nightwear</a></dd>
<dd><a href="index.php?id=17">Socks</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=21">Underwear</a></dd>
<dd><a href="index.php?id=31">Swimwear</a></dd>
</dl>
</div>
</li>
<!--menu-->
<li><a href="index.php?id=5" class="blue">Ladie's</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=32">Coats & Jackets</a></dd>
<dd><a href="index.php?id=33">Dresses</a></dd>
<dd><a href="index.php?id=34">Jeans</a></dd>
<dd><a href="index.php?id=35">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=36">Jumpsuits</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=37">Leggings & Jeggings</a></dd>
<dd><a href="index.php?id=38">Linen</a></dd>
<dd><a href="index.php?id=39">Lingerie & Underwear</a></dd>
<dd><a href="index.php?id=40">Maternity Wear</a></dd>
<dd><a href="index.php?id=41">Nightwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=42">Shorts</a></dd>
<dd><a href="index.php?id=43">Skirts</a></dd>
<dd><a href="index.php?id=44">Sportswear</a></dd>
<dd><a href="index.php?id=45">Suits & Tailoring</a></dd>
<dd><a href="index.php?id=46">Swimwear & Beachwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=47">Thermals</a></dd>
<dd><a href="index.php?id=48">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=49">Trousers & Chinos</a></dd>
<dd><a href="index.php?id=50">Socks</a></dd>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=7" class="blue">Girls</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=51">Coats & Jackets</a></dd>
<dd><a href="index.php?id=52">Dresses</a></dd>
<dd><a href="index.php?id=53">Jeans</a></dd>
<dd><a href="index.php?id=54">Joggers & Sweatshirts</a></dd>
<dd><a href="index.php?id=55">Jumpers & Cardigans</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=56">Jumpsuits & Playsuits</a></dd>
<dd><a href="index.php?id=57">Leggings</a></dd>
<dd><a href="index.php?id=58">Nightwear</a></dd>
<dd><a href="index.php?id=59">Shorts</a></dd>
<dd><a href="index.php?id=60">Skirts</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=61">Swimwear</a></dd>
<dd><a href="index.php?id=62">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=63">Trousers & Jeans</a></dd>
<dd><a href="index.php?id=64">Socks</a></dd>
<dd><a href="index.php?id=65">Underwear</a></dd>
</dl>
<dl>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=8" class="blue">Boys</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=66">Coats & Jackets</a></dd>
<dd><a href="index.php?id=67">Jeans</a></dd>
<dd><a href="index.php?id=68">Joggers & Sweatshirts</a></dd>
<dd><a href="index.php?id=69">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=70">Nightwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=71">Shirts</a></dd>
<dd><a href="index.php?id=72">Shorts</a></dd>
<dd><a href="index.php?id=73">Sportswear</a></dd>
<dd><a href="index.php?id=74">Swimwear</a></dd>
<dd><a href="index.php?id=75">T-Shirts & Polo Shirts</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=76">Trousers & Jeans</a></dd>
<dd><a href="index.php?id=77">Socks</a></dd>
<dd><a href="index.php?id=78">Underwear</a></dd>
</dl>
<dl>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=9" class="blue">Toddlers</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=79">Newborn</a></dd>
<dd><a href="index.php?id=80">0-2 Years</a></dd>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=10" class="blue">Accessories</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=81">Shoes</a></dd>
<dd><a href="index.php?id=82">Ties</a></dd>
<dd><a href="index.php?id=83">Caps</a></dd>
<dd><a href="index.php?id=84">Belts</a></dd>
</dl>
</div>
</li><!--menu end-->
<li><a href="index.php?id=13" class="blue">Contact Us</a></li>
</ul>
<div class="back"></div>
<div class="shadow"></div>
</div>
<div style="clear:both"></div>
</div>
CSS 3 Coding- Copy and Paste
<style>
body{margin:0px;}
.example {
width:980px;
height:40px;
margin:0px auto;
position:absolute;
margin-bottom:60px;
top:95px;
}
.menuholder {
float:left;
font:normal bold 11px/35px verdana, sans-serif;
overflow:hidden;
position:relative;
}
.menuholder .shadow {
-moz-box-shadow:0 0 20px rgba(0, 0, 0, 1);
-o-box-shadow:0 0 20px rgba(0, 0, 0, 1);
-webkit-box-shadow:0 0 20px rgba(0, 0, 0, 1);
background:#888;
box-shadow:0 0 20px rgba(0, 0, 0, 1);
height:10px;
left:5%;
position:absolute;
top:-9px;
width:100%;
z-index:100;
}
.menuholder .back {
-moz-transition-duration:.4s;
-o-transition-duration:.4s;
-webkit-transition-duration:.4s;
background-color:rgba(0, 0, 0, 0.88);
height:0;
width:980px; /*100%*/
}
.menuholder:hover div.back {
height:280px;
}
ul.menu {
display:block;
float:left;
list-style:none;
margin:0;
padding:0 125px;
position:relative;
}
ul.menu li {
float:left;
margin:0 10px 0 0;
}
ul.menu li > a {
-moz-border-radius:0 0 10px 10px;
-moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-moz-transition:all 0.3s ease-in-out;
-o-border-radius:0 0 10px 10px;
-o-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-o-transition:all 0.3s ease-in-out;
-webkit-border-bottom-left-radius:10px;
-webkit-border-bottom-right-radius:10px;
-webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-webkit-transition:all 0.3s ease-in-out;
border-radius:0 0 10px 10px;
box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
color:#eee;
display:block;
padding:0 10px;
text-decoration:none;
transition:all 0.3s ease-in-out;
}
ul.menu li a.red {
background:#a00;
}
ul.menu li a.orange {
background:#da0;
}
ul.menu li a.yellow {
background:#aa0;
}
ul.menu li a.green {
background:#060;
}
ul.menu li a.blue {
background:#073263;
}
ul.menu li a.violet {
background:#682bc2;
}
.menu li div.subs {
left:0;
overflow:hidden;
position:absolute;
top:35px;
width:0;
}
.menu li div.subs dl {
-moz-transition-duration:.2s;
-o-transition-duration:.2s;
-webkit-transition-duration:.2s;
float:left;
margin:0 130px 0 0;
overflow:hidden;
padding:40px 0 5% 2%;
width:0;
}
.menu dt {
color:#fc0;
font-family:arial, sans-serif;
font-size:12px;
font-weight:700;
height:20px;
line-height:20px;
margin:0;
padding:0 0 0 10px;
white-space:nowrap;
}
.menu dd {
margin:0;
padding:0;
text-align:left;
}
.menu dd a {
background:transparent;
color:#fff;
font-size:12px;
height:20px;
line-height:20px;
padding:0 0 0 10px;
text-align:left;
white-space:nowrap;
width:80px;
}
.menu dd a:hover {
color:#fc0;
}
.menu li:hover div.subs dl {
-moz-transition-delay:0.2s;
-o-transition-delay:0.2s;
-webkit-transition-delay:0.2s;
margin-right:2%;
width:21%;
}
ul.menu li:hover > a,ul.menu li > a:hover {
background:#aaa;
color:#fff;
padding:10px 10px 0;
}
ul.menu li a.red:hover,ul.menu li:hover a.red {
background:#c00;
}
ul.menu li a.orange:hover,ul.menu li:hover a.orange {
background:#fc0;
}
ul.menu li a.yellow:hover,ul.menu li:hover a.yellow {
background:#cc0;
}
ul.menu li a.green:hover,ul.menu li:hover a.green {
background:#080;
}
ul.menu li a.blue:hover,ul.menu li:hover a.blue {
background:#00c;
}
ul.menu li a.violet:hover,ul.menu li:hover a.violet {
background:#8a2be2;
}
.menu li:hover div.subs,.menu li a:hover div.subs {
width:100%;
}
Tensorflow version in Jupyter Notebook:-
!pip list | grep tensorflow
I solved like this
$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
$list=array();
$i=0;
while ($cresult=$stmt->fetch()){
$list[$i][0]=$cde;
$list[$i][1]=$v_off;
$list[$i][2]=$em_nm;
$list[$i][3]=$q_id;
$list[$i][4]=$v_m;
$i=$i+1;
}
echo json_encode($list);
This will be returned to ajax as result set and by using json parse in javascript part like this :
obj = JSON.parse(dataX);
SELECT b.BatchID,
x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM Batches b
CROSS APPLY b.RawXml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol);
Demo: SQLFiddle
You need to initialize UITapGestureRecognizer with a target and action, like so:
let tap = UITapGestureRecognizer(target: self, action: "handleTap:")
tap.delegate = self
myView.addGestureRecognizer(tap)
Then, you should implement the handler, which will be called each time when a tap event occurs:
func handleTap(sender: UITapGestureRecognizer) {
// handling code
}
You want the 'change' event handler, instead of 'click'.
$('#mySelect').change(function(){
var value = $(this).val();
});
contents_re = re.match(r'[^\(]*\((?P<contents>[^\(]+)\)', data)
if contents_re:
print(contents_re.groupdict()['contents'])
I had to reinstall pdAdmin to resolve this issue
brew cask reinstall pgadmin4
Here,all these are cut from Eclipse sample SettingsActivity
.
I have to copy all these too much codes to show how these android developers choose perfectly for more generalized and stable coding style.
I left the codes for adapting the PreferenceActivity
to tablet and greater API.
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setupSummaryUpdatablePreferencesScreen();
}
private void setupSummaryUpdatablePreferencesScreen() {
// In the simplified UI, fragments are not used at all and we instead
// use the older PreferenceActivity APIs.
// Add 'general' preferences.
addPreferencesFromResource(R.xml.pref_general);
// Bind the summaries of EditText/List/Dialog preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
private String TAG = SettingsActivity.class.getSimpleName();
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
Log.i(TAG, "pref changed : " + preference.getKey() + " " + value);
return true;
}
};
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
}
xml/pref_general.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- NOTE: EditTextPreference accepts EditText attributes. -->
<!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
<EditTextPreference
android:capitalize="words"
android:defaultValue="@string/pref_default_display_name"
android:inputType="textCapWords"
android:key="example_text"
android:maxLines="1"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="@string/pref_title_display_name" />
<!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog todismiss it.-->
<!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
<ListPreference
android:defaultValue="-1"
android:entries="@array/pref_example_list_titles"
android:entryValues="@array/pref_example_list_values"
android:key="example_list"
android:negativeButtonText="@null"
android:positiveButtonText="@null"
android:title="@string/pref_title_add_friends_to_messages" />
</PreferenceScreen>
values/strings_activity_settings.xml
<resources>
<!-- Strings related to Settings -->
<!-- Example General settings -->
<string name="pref_title_display_name">Display name</string>
<string name="pref_default_display_name">John Smith</string>
<string name="pref_title_add_friends_to_messages">Add friends to messages</string>
<string-array name="pref_example_list_titles">
<item>Always</item>
<item>When possible</item>
<item>Never</item>
</string-array>
<string-array name="pref_example_list_values">
<item>1</item>
<item>0</item>
<item>-1</item>
</string-array>
</resources>
NOTE: Actually I just want to comment like "Google's sample for PreferenceActivity is also interesting". But I haven't enough reputation points.So please don't blame me.
(Sorry for bad English)
If you are still interested, Chris Wolf made a prototype implementation of SQLite with Stored Procedures. You can find the details at his blog post: Adding Stored Procedures to SQLite
Try the following code to verify whether the file exist. You can create a user function and use it in your stored procedure. modify it as you need:
Set NOCOUNT ON
DECLARE @Filename NVARCHAR(50)
DECLARE @fileFullPath NVARCHAR(100)
SELECT @Filename = N'LogiSetup.log'
SELECT @fileFullPath = N'C:\LogiSetup.log'
create table #dir
(output varchar(2000))
DECLARE @cmd NVARCHAR(100)
SELECT @cmd = 'dir ' + @fileFullPath
insert into #dir
exec master.dbo.xp_cmdshell @cmd
--Select * from #dir
-- This is risky, as the fle path itself might contain the filename
if exists (Select * from #dir where output like '%'+ @Filename +'%')
begin
Print 'File found'
--Add code you want to run if file exists
end
else
begin
Print 'No File Found'
--Add code you want to run if file does not exists
end
drop table #dir
Once I updated my Java version to 8 as suggested by browser. However I had selected to uninstall previous Java 6 version I have been used for coding my projects. When I enter the command in "java -version" in cmd it showed 1.8 and I could not start eclipse IDE run on Java 1.6.
When I installed Java 8 update for the browser it had changed the "PATH" System variable appending "C:\ProgramData\Oracle\Java\javapath" to the beginning. Newly added path pointed to Java vesion 8. So I removed that path from "PATH" System variable and everything worked fine. :)
Thanks for the help everyone, but since i'm on HP-UX (after all: the more you pay, the less features you get...) i've had to resort to perl:
perl -e '@T=localtime(time-86400);printf("%02d/%02d/%04d",$T[3],$T[4]+1,$T[5]+1900)' | read dt
I partially solved it with:
cd "/path/to/pricipal/folder"
for i in $(ls -d .*/); do sudo ln -s "$PWD"/${i%%/} /home/inukaze/${i%%/}; done
ln: «/home/inukaze/./.»: can't overwrite a directory
ln: «/home/inukaze/../..»: can't overwrite a directory
ln: accesing to «/home/inukaze/.config»: too much symbolics links levels
ln: accesing to «/home/inukaze/.disruptive»: too much symbolics links levels
ln: accesing to «/home/inukaze/innovations»: too much symbolics links levels
ln: accesing to «/home/inukaze/sarl»: too much symbolics links levels
ln: accesing to «/home/inukaze/.e_old»: too much symbolics links levels
ln: accesing to «/home/inukaze/.gnome2_private»: too much symbolics links levels
ln: accesing to «/home/inukaze/.gvfs»: too much symbolics links levels
ln: accesing to «/home/inukaze/.kde»: too much symbolics links levels
ln: accesing to «/home/inukaze/.local»: too much symbolics links levels
ln: accesing to «/home/inukaze/.xVideoServiceThief»: too much symbolics links levels
Well, this reduce to me, the major part :)
In node, you can just say
console.log(aa)
and it will format it as it should.
If you need to use the resulting string you should use
JSON.stringify(aa)
Not sure whether it would help you or not but it works to me:
l = ["a", "b", "c", "d", "e"]
outRes = dict((l[i], l[i+1]) if i+1 < len(l) else (l[i], '') for i in xrange(len(l)))
<gradient
android:centerColor="#c1c1c1"
android:endColor="#4f4f4f"
android:gradientRadius="400"
android:startColor="#c1c1c1"
android:type="radial" >
</gradient>
You can use map
function
{Object.keys(tifs).map(key => (
<option value={key}>{tifs[key]}</option>
))}
PAGEIOLATCH_SH
wait type usually comes up as the result of fragmented or unoptimized index.
Often reasons for excessive PAGEIOLATCH_SH
wait type are:
In order to try and resolve having high PAGEIOLATCH_SH
wait type, you can check:
PAGEIOLATCH_SH
wait typesAlways keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH
can be expected.
You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types
I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:
SELECT * FROM match WHERE id NOT IN
( SELECT id FROM email WHERE id IS NOT NULL) ;
SELECT
m.*
FROM
match m
LEFT OUTER JOIN email e ON
m.id = e.id
AND e.id IS NOT NULL
WHERE
e.id IS NULL
The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.
Okay, so here we have two things that are being mixed. First thing, is when you need to mark something to be used only on test, which I agree with @JB Nizet, using the guava annotation would be good.
A different thing, is to test private methods. Why should you test private methods from the outside? I mean.. You should be able to test the object by their public methods, and at the end that its behavior. At least, that we are doing and trying to teach to junior developers, that always try to test private methods (as a good practice).
The smart thing is not to write the crypto yourself but to use something like passlib: https://bitbucket.org/ecollins/passlib/wiki/Home
It is easy to mess up writing your crypto code in a secure way. The nasty thing is that with non crypto code you often immediately notice it when it is not working since your program crashes. While with crypto code you often only find out after it is to late and your data has been compromised. Therefor I think it is better to use a package written by someone else who is knowledgable about the subject and which is based on battle tested protocols.
Also passlib has some nice features which make it easy to use and also easy to upgrade to a newer password hashing protocol if an old protocol turns out to be broken.
Also just a single round of sha512 is more vulnerable to dictionary attacks. sha512 is designed to be fast and this is actually a bad thing when trying to store passwords securely. Other people have thought long and hard about all this sort issues so you better take advantage of this.
%w(foo bar)
is a shortcut for ["foo", "bar"]
. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.
I solved the problem in this way:
and no more error.
You should normally be able to run a php file (after a successful installation) just by running this command:
$ /path/to/php myfile.php // unix way
C:\php\php.exe myfile.php // windows way
You can read more about running PHP in CLI mode here.
It's worth adding that PHP from version 5.4 onwards is able to run a web server on its own. You can do it by running this code in a folder which you want to serve the pages from:
$ php -S localhost:8000
You can read more about running a PHP in a Web Server mode here.
I think the problem is here:
[contains(text()='Some text')]
To break this down,
[]
are a conditional that operates on each individual node in
that node set -- each span node in your case. It matches if any of the individual nodes it operates
on match the conditions inside the brackets. text()
is a selector
that matches all of the text nodes that are children of the context
node -- it returns a node set. contains
is a function that operates
on a string. If it is passed a node set, the node set is converted
into a string by returning the string-value of the node in the
node-set that is first in document order.You should try to change this to
[text()[contains(.,'Some text')]]
The outer []
are a conditional that operates on each individual node
in that node set text()
is a selector that matches all of the text
nodes that are children of the context node -- it returns a node
set.
The inner []
are a conditional that operates on each node in that
node set.
contains
is a function that operates on a string. Here it is passed
an individual text node (.
).
This simple command works like a charm:
git name-rev <SHA>
For example (where test-branch is the branch name):
git name-rev 651ad3a
251ad3a remotes/origin/test-branch
Even this is working for complex scenarios, like:
origin/branchA/
/branchB
/commit<SHA1>
/commit<SHA2>
Here git name-rev commit<SHA2>
returns branchB.
another way
List<int> list=new List<int>();
IEnumerable<int> enumerable =Enumerable.Range(1, 300);
foreach (var item in enumerable )
{
list.add(item);
}
The easiest way is using Ajax Post Request:
$.ajax({
type: "POST",
url: 'http://www.myrestserver.com/api',
data: data,
success: success,
dataType: dataType
});
where:
Then in the success handler redirect the browser with something like window.location.
WordPress 5.0.2:
To remove category slug from existing posts, do this :
/%category%/%postname%/
to: /%postname%/
All posts can now be directly accessed via domain.com/%postname%/
and all categories can be accessed via domain.com/category/xyz/
. WordPress will automatically add all the 301 redirects for the old urls. So, if someone accesses domain.com/%category%/%postname%/
, they will automatically get redirected to domain.com/%postname%/
.
I will explain it verbally first and then with an example:
A pointer object can be declared as a const pointer or a pointer to a const object (or both):
A const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the object that it points to (called the "pointee").
Reference variables are thus an alternate syntax for constpointers.
A pointer to a const object, on the other hand, can be reassigned to point to another object of the same type or of a convertible type, but it cannot be used to modify any object.
A const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object.
Example:
void Foo( int * ptr,
int const * ptrToConst,
int * const constPtr,
int const * const constPtrToConst )
{
*ptr = 0; // OK: modifies the "pointee" data
ptr = 0; // OK: modifies the pointer
*ptrToConst = 0; // Error! Cannot modify the "pointee" data
ptrToConst = 0; // OK: modifies the pointer
*constPtr = 0; // OK: modifies the "pointee" data
constPtr = 0; // Error! Cannot modify the pointer
*constPtrToConst = 0; // Error! Cannot modify the "pointee" data
constPtrToConst = 0; // Error! Cannot modify the pointer
}
Happy to help! Good Luck!
Open Xcode --> Go to Window (from menu bar) --> Devices and Simulators --> Click on Simulator --> Right-click on the simulator that you want to delete --> Click Delete
To delete any unwanted simulators that you installed in the past as an extra Component through Xcode.
Open Terminal
Type open /Library/Developer/CoreSimulator/Profiles/Runtimes
Delete undesired simulators
I had the same error, because instead of deleting a file I simply removed references to it. Locating the file in Finder and removing it helped.
Remove/Delete the project from workspace. and Reimport the project to the workspace. This method worked for me.
It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.
@Request/View/Flow/Session/ApplicationScoped
A @RequestScoped
bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped
bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null
/void
without any navigation/redirect. A @FlowScoped
bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped
bean lives as long as the established HTTP session. An @ApplicationScoped
bean lives as long as the web application runs. Note that the CDI @Model
is basically a stereotype for @Named @RequestScoped
, so same rules apply.
Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped
for simple and non-ajax forms/presentations. Use @ViewScoped
for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped
for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped
for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped
for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.
Abusing an @ApplicationScoped
bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped
bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped
bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped
bean for request, session or application scoped data, and abusing a @SessionScoped
bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.
Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped
beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty
in case of JSF managed beans or @Inject
in case of CDI managed beans.
@CustomScoped/NoneScoped/Dependent
It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped
and @NoneScoped
, which are rarely used in real world. The @CustomScoped
must refer a custom Map<K, Bean>
implementation in some broader scope which has overridden Map#put()
and/or Map#get()
in order to have more fine grained control over bean creation and/or destroy.
The JSF @NoneScoped
and CDI @Dependent
basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped
or @Dependent
is injected in a @SessionScoped
, then it will live as long as the @SessionScoped
bean.
As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.
This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped
. The flash scope is only available as a map via ExternalContext#getFlash()
in managed beans and #{flash}
in EL.
I think the following link will help you. If you want to generate fields dynamically and also want to remove them on the same time you can get the help from here. I had the same question, So i got the answer
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
$post_data = [
"item" => [
'item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts
]
];
$post_data = json_encode(post_data);
$post_data = json_decode(post_data);
return $post_data;
Add your new class "tableresp" with table-responisve class and then add below code in your js file
$(".tableresp").on('click', '.dropdown-toggle', function(event) {
if ($('.dropdown-menu').length) {
var elm = $('.dropdown-menu'),
docHeight = $(document).height(),
docWidth = $(document).width(),
btn_offset = $(this).offset(),
btn_width = $(this).outerWidth(),
btn_height = $(this).outerHeight(),
elm_width = elm.outerWidth(),
elm_height = elm.outerHeight(),
table_offset = $(".tableresp").offset(),
table_width = $(".tableresp").width(),
table_height = $(".tableresp").height(),
tableoffright = table_width + table_offset.left,
tableoffbottom = table_height + table_offset.top,
rem_tablewidth = docWidth - tableoffright,
rem_tableheight = docHeight - tableoffbottom,
elm_offsetleft = btn_offset.left,
elm_offsetright = btn_offset.left + btn_width,
elm_offsettop = btn_offset.top + btn_height,
btn_offsetbottom = elm_offsettop,
left_edge = (elm_offsetleft - table_offset.left) < elm_width,
top_edge = btn_offset.top < elm_height,
right_edge = (table_width - elm_offsetleft) < elm_width,
bottom_edge = (tableoffbottom - btn_offsetbottom) < elm_height;
console.log(tableoffbottom);
console.log(btn_offsetbottom);
console.log(bottom_edge);
console.log((tableoffbottom - btn_offsetbottom) + "|| " + elm_height);
var table_offset_bottom = docHeight - (table_offset.top + table_height);
var touchTableBottom = (btn_offset.top + btn_height + (elm_height * 2)) - table_offset.top;
var bottomedge = touchTableBottom > table_offset_bottom;
if (left_edge) {
$(this).addClass('left-edge');
} else {
$('.dropdown-menu').removeClass('left-edge');
}
if (bottom_edge) {
$(this).parent().addClass('dropup');
} else {
$(this).parent().removeClass('dropup');
}
}
});
var table_smallheight = $('.tableresp'),
positioning = table_smallheight.parent();
if (table_smallheight.height() < 320) {
positioning.addClass('positioning');
$('.tableresp .dropdown,.tableresp .adropup').css('position', 'static');
} else {
positioning.removeClass('positioning');
$('.tableresp .dropdown,.tableresp .dropup').css('position', 'relative');
}
The upcoming version v3.3.0 of ggplot2
will have an option n.breaks
to automatically generate breaks for scale_x_continuous
and scale_y_continuous
devtools::install_github("tidyverse/ggplot2")
library(ggplot2)
plt <- ggplot(mtcars, aes(x = mpg, y = disp)) +
geom_point()
plt +
scale_x_continuous(n.breaks = 5)
plt +
scale_x_continuous(n.breaks = 10) +
scale_y_continuous(n.breaks = 10)
PHP does not have permissions to write on /tmp directory. You need to use chmod
command to open /tmp permissions.
Try below locator.
selenium.click("css=a[href*='listDetails.do'][id='oldcontent']");
or
selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");
Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/')
followed by relative paths for os.system
, subprocess
methods, or whatever...
If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial .exe
file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?
If the data to be encoded contains "exotic" characters, I think you have to encode in "UTF-8"
encoded = base64.b64encode (bytes('data to be encoded', "utf-8"))
Just add these to libraries to your project:
<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"></link>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>
Save and reload. You're good to go.
To understand how a docker image was built, use the
docker history --no-trunc
command.
You can build a docker file from an image, but it will not contain everything you would want to fully understand how the image was generated. Reasonably what you can extract is the MAINTAINER, ENV, EXPOSE, VOLUME, WORKDIR, ENTRYPOINT, CMD, and ONBUILD parts of the dockerfile.
The following script should work for you:
#!/bin/bash
docker history --no-trunc "$1" | \
sed -n -e 's,.*/bin/sh -c #(nop) \(MAINTAINER .*[^ ]\) *0 B,\1,p' | \
head -1
docker inspect --format='{{range $e := .Config.Env}}
ENV {{$e}}
{{end}}{{range $e,$v := .Config.ExposedPorts}}
EXPOSE {{$e}}
{{end}}{{range $e,$v := .Config.Volumes}}
VOLUME {{$e}}
{{end}}{{with .Config.User}}USER {{.}}{{end}}
{{with .Config.WorkingDir}}WORKDIR {{.}}{{end}}
{{with .Config.Entrypoint}}ENTRYPOINT {{json .}}{{end}}
{{with .Config.Cmd}}CMD {{json .}}{{end}}
{{with .Config.OnBuild}}ONBUILD {{json .}}{{end}}' "$1"
I use this as part of a script to rebuild running containers as images: https://github.com/docbill/docker-scripts/blob/master/docker-rebase
The Dockerfile is mainly useful if you want to be able to repackage an image.
The thing to keep in mind, is a docker image can actually just be the tar backup of a real or virtual machine. I have made several docker images this way. Even the build history shows me importing a huge tar file as the first step in creating the image...
protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
using (StreamWriter w = new StreamWriter(Server.MapPath("~/data.txt"), true))
{
w.WriteLine(TextBox1.Text); // Write the text
}
}
Download this file :- (https://pypi.python.org/packages/1f/3b/ee6f354bcb1e28a7cd735be98f39ecf80554948284b41e9f7965951befa6/pyserial-3.2.1.tar.gz#md5=7142a421c8b35d2dac6c47c254db023d):
cd /opt
sudo tar -xvf ~/Downloads/pyserial-3.2.1.tar.gz -C .
cd /opt/pyserial-3.2.1
sudo python setup.py install
This css solution worked for me:
input:active,
input:focus {
border: 1px solid #red
}
input:active,
input:focus {
padding: 2px solid #red /*for firefox and chrome*/
}
/* .ie is a class you would need to set at the html root level */
.ie input:active,
.ie input:focus {
padding: 3px solid #red /* IE needs 1px extra padding*/
}
I understand it is not necessary on FF and Chrome, but IE needs it. And there are circumstances when you need it.
Here is my code:
html:
const upload = (file) => {_x000D_
console.log(file);_x000D_
_x000D_
_x000D_
_x000D_
fetch('http://localhost:8080/files/uploadFile', { _x000D_
method: 'POST',_x000D_
// headers: {_x000D_
// //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",_x000D_
// "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" // ? // multipart/form-data _x000D_
// },_x000D_
body: file // This is your file object_x000D_
}).then(_x000D_
response => response.json() // if the response is a JSON object_x000D_
).then(_x000D_
success => console.log(success) // Handle the success response object_x000D_
).catch(_x000D_
error => console.log(error) // Handle the error response object_x000D_
);_x000D_
_x000D_
//cvForm.submit();_x000D_
};_x000D_
_x000D_
const onSelectFile = () => upload(uploadCvInput.files[0]);_x000D_
_x000D_
uploadCvInput.addEventListener('change', onSelectFile, false);
_x000D_
<form id="cv_form" style="display: none;"_x000D_
enctype="multipart/form-data">_x000D_
<input id="uploadCV" type="file" name="file"/>_x000D_
<button type="submit" id="upload_btn">upload</button>_x000D_
</form>_x000D_
<ul class="dropdown-menu">_x000D_
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>_x000D_
</ul>
_x000D_
Solved, using the following command set:
git reset --hard
git pull --rebase
git rebase --skip
git pull
The trick is to rebase the changes... We had some trouble rebasing one trivial commit, and so we simply skipped it using git rebase --skip (after having copied the files).
This algorithm is based on finding the intersection between the specified line and the orthogonal line, which contains the specified point, and calculating its distance. In case of a line segment, we must check if the intersection is between points of the line segment, if that's not the case then the minimum distance is between the specified point and one of the ending points of the line segment. This is a C# implementation.
Double Distance(Point a, Point b)
{
double xdiff = a.X - b.X, ydiff = a.Y - b.Y;
return Math.Sqrt((long)xdiff * xdiff + (long)ydiff * ydiff);
}
Boolean IsBetween(double x, double a, double b)
{
return ((a <= b && x >= a && x <= b) || (a > b && x <= a && x >= b));
}
Double GetDistance(Point pt, Point pt1, Point pt2, out Point intersection)
{
Double a, x, y, R;
if (pt1.X != pt2.X) {
a = (double)(pt2.Y - pt1.Y) / (pt2.X - pt1.X);
x = (a * (pt.Y - pt1.Y) + a * a * pt1.X + pt.X) / (a * a + 1);
y = a * x + pt1.Y - a * pt1.X; }
else { x = pt1.X; y = pt.Y; }
if (IsBetween(x, pt1.X, pt2.X) && IsBetween(y, pt1.Y, pt2.Y)) {
intersection = new Point((int)x, (int)y);
R = Distance(intersection, pt); }
else {
double d1 = Distance(pt, pt1), d2 = Distance(pt, pt2);
if (d1 < d2) { intersection = pt1; R = d1; }
else { intersection = pt2; R = d2; }}
return R;
}
Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.
I prefer this
if(in_array($id,$user_access_arr) == false)
respective
if (in_array(search_value, array) == false)
// value is not in array
I know this is an older subject, however Mocking a MVC application for unit tests is something we do on very regular basis.
I just wanted to add my experiences Mocking a MVC 3 application using Moq 4 after upgrading to Visual Studio 2013. None of the unit tests were working in debug mode and the HttpContext was showing "could not evaluate expression" when trying to peek at the variables.
Turns out visual studio 2013 has issues evaluating some objects. To get debugging mocked web applications working again, I had to check the "Use Managed Compatibility Mode" in Tools=>Options=>Debugging=>General settings.
I generally do something like this:
public static class FakeHttpContext
{
public static void SetFakeContext(this Controller controller)
{
var httpContext = MakeFakeContext();
ControllerContext context =
new ControllerContext(
new RequestContext(httpContext,
new RouteData()), controller);
controller.ControllerContext = context;
}
private static HttpContextBase MakeFakeContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
context.Setup(c=> c.Request).Returns(request.Object);
context.Setup(c=> c.Response).Returns(response.Object);
context.Setup(c=> c.Session).Returns(session.Object);
context.Setup(c=> c.Server).Returns(server.Object);
context.Setup(c=> c.User).Returns(user.Object);
user.Setup(c=> c.Identity).Returns(identity.Object);
identity.Setup(i => i.IsAuthenticated).Returns(true);
identity.Setup(i => i.Name).Returns("admin");
return context.Object;
}
}
And initiating the context like this
FakeHttpContext.SetFakeContext(moController);
And calling the Method in the controller straight forward
long lReportStatusID = -1;
var result = moController.CancelReport(lReportStatusID);
If you were trying to do what I imagine you were trying to do, then you only have to treat scope like a regular JS object.
This is what I use for an API success response for JSON data array...
function(data){
$scope.subjects = [];
$.each(data, function(i,subject){
//Store array of data types
$scope.subjects.push(subject.name);
//Split data in to arrays
$scope[subject.name] = subject.data;
});
}
Now {{subjects}} will return an array of data subject names, and in my example there would be a scope attribute for {{jobs}}, {{customers}}, {{staff}}, etc. from $scope.jobs, $scope.customers, $scope.staff
Updated answer for ES6+ is here.
arr = [1, 2, 3];
arr.forEach(function(i, idx, array){
if (idx === array.length - 1){
console.log("Last callback call at index " + idx + " with value " + i );
}
});
would output:
Last callback call at index 2 with value 3
The way this works is testing arr.length
against the current index of the array, passed to the callback function.
WITH CTE AS (
SELECT
rownum = ROW_NUMBER() OVER (ORDER BY columns_to_order_by),
value
FROM table
)
SELECT
curr.value - prev.value
FROM CTE cur
INNER JOIN CTE prev on prev.rownum = cur.rownum - 1
If you are using Python2.5 or older try
from operator import mul
def factorial(n):
return reduce(mul, range(1,n+1))
for newer Python, there is factorial in the math module as given in other answers here
An Error Was Encountered Unable to load the requested file:
Sometimes we face this error because the requested file doesn't exist in that directory.
Suppose we have a folder home
in views
directory and trying to load home_view.php
file as:
$this->load->view('home/home_view', $data);// $data is array
If home_view.php
file doesn't exist in views/home
directory then it will raise an error.
An Error Was Encountered Unable to load the requested file: home\home_view.php
So how to fix this error go to views/home
and check the home_view.php
file exist if not then create it.
You will not be able to do that. You can download apps again to the same userid account on different devices, but you cannot transfer those licenses to other userids.
There is no way to do this programatically - I don't think you can do that practically (except for trying to call customer support at the Play Store).
Once upon a time in MySQL you could just copy all the table files to another directory in the mysql tree
mysql cli - create database db2
linux cli - cp db1 db2
Dereferencing just means reading the memory value at a given address. So when you have a pointer to something, to dereference the pointer means to read or write the data that the pointer points to.
In C, the unary *
operator is the dereferencing operator. If x
is a pointer, then *x
is what x
points to. The unary &
operator is the address-of operator. If x
is anything, then &x
is the address at which x
is stored in memory. The *
and &
operators are inverses of each other: if x
is any data, and y
is any pointer, then these equations are always true:
*(&x) == x
&(*y) == y
A null pointer is a pointer that does not point to any valid data (but it is not the only such pointer). The C standard says that it is undefined behavior to dereference a null pointer. This means that absolutely anything could happen: the program could crash, it could continue working silently, or it could erase your hard drive (although that's rather unlikely).
In most implementations, you will get a "segmentation fault" or "access violation" if you try to do so, which will almost always result in your program being terminated by the operating system. Here's one way a null pointer could be dereferenced:
int *x = NULL; // x is a null pointer
int y = *x; // CRASH: dereference x, trying to read it
*x = 0; // CRASH: dereference x, trying to write it
And yes, dereferencing a null pointer is pretty much exactly like a NullReferenceException
in C# (or a NullPointerException
in Java), except that the langauge standard is a little more helpful here. In C#, dereferencing a null reference has well-defined behavior: it always throws a NullReferenceException
. There's no way that your program could continue working silently or erase your hard drive like in C (unless there's a bug in the language runtime, but again that's incredibly unlikely as well).
Using pandas to get the current time, kind of overkilling the problem at hand:
import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)
Output:
2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693
With the Material Components Library you can use the MaterialShapeDrawable
.
<TextView
android:id="@+id/textview"
.../>
Then you can programmatically apply a MaterialShapeDrawable
:
TextView textView = findViewById(R.id.textview);
MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable();
shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,android.R.color.transparent));
shapeDrawable.setStroke(1.0f, ContextCompat.getColor(this,R.color....));
ViewCompat.setBackground(textView,shapeDrawable);
$('element[name="element_name"]').click(function(){
//do stuff
});
in your case:
$('input[name="btnName"]').click(function(){
//do stuff
});
A much simpler solution would be to download the file using Chrome. In this manner you don't have to manually click on the save button.
using System;
using System.Diagnostics;
using System.ComponentModel;
namespace MyProcessSample
{
class MyProcess
{
public static void Main()
{
Process myProcess = new Process();
myProcess.Start("chrome.exe","http://www.com/newfile.zip");
}
}
}
Settings > advanced > security > valid oauth redirect URI
The below seems to work. The enter event handles the tabbing to the control and the MouseDown works when the control is clicked.
private ########### void textBox1_Enter(object sender, EventArgs e)
{
textBox1.SelectAll();
}
private void textBox1_MouseDown(object sender, MouseEventArgs e)
{
if (textBox1.Focused)
textBox1.SelectAll();
}
.pom
dependency
scope
can contain:
compile
- available at Compile-time and Run-timeprovided
- available at Compile-time. (this dependency should be provided by outer container like OS...)runtime
- available at Run-timetest
- test compilation and run timesystem
- is similar to provided
but exposes <systemPath>path/some.jar</systemPath>
to point on .jar
import
- is available from Maven v2.0.9 for <type>pom</type>
and it should be replaced by effective dependency from this file <dependencyManagement/>
In the PHP file first you need to register the session
<? session_start();
$_SESSION['id'] = $userData['user_id'];?>
And in each page of your php application you can retrive the session id
<? session_start()
id = $_SESSION['id'];
?>
As a previous answer mentioned, passing the -F
option to less
causes it to quit if the content is less than one screen. However, after doing so, the screen is reset, and you end up not seeing the content.
The -X
option does away with that behaviour. So, I use the following to enable conditional paging based on the amount of content:
git config --global --replace-all core.pager "less -F -X"
Using Microsoft SQL Server Management Studio you can create Linked Server
. First make connection to current (local) server, then go to Server Objects
> Linked Servers
> context menu > New Linked Server
. In window New Linked Server
you have to specify desired server name for remote server, real server name or IP address (Data Source) and credentials (Security page).
And further you can select data from linked server:
select * from [linked_server_name].[database].[schema].[table]
For the select tag, angular provides the ng-options directive. It gives you the specific framework to set up options and set a default. Here is the updated fiddle using ng-options that works as expected: http://jsfiddle.net/FxM3B/4/
Updated HTML (code stays the same)
<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.value as operator.displayName for operator in operators">
</select>
</body>
It is open-source, and available at http://codeplex.com/elephant
Some one’s made a working example of the gpg6-code, you can find it here: http://www.unseen-academy.de/componentSystem.html
or here: http://www.mcshaffry.com/GameCode/thread.php?threadid=732
regards
I like Felipe Leusin's approach best - make sure browsers get JSON without compromising content negotiation from clients that actually want XML. The only missing piece for me was that the response headers still contained content-type: text/html. Why was that a problem? Because I use the JSON Formatter Chrome extension, which inspects content-type, and I don't get the pretty formatting I'm used to. I fixed that with a simple custom formatter that accepts text/html requests and returns application/json responses:
public class BrowserJsonFormatter : JsonMediaTypeFormatter
{
public BrowserJsonFormatter() {
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
this.SerializerSettings.Formatting = Formatting.Indented;
}
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) {
base.SetDefaultContentHeaders(type, headers, mediaType);
headers.ContentType = new MediaTypeHeaderValue("application/json");
}
}
Register like so:
config.Formatters.Add(new BrowserJsonFormatter());
The following should do what you want:
x <- data.frame(X1=sample(c(1:3,NaN), 200, replace=TRUE), X2=sample(c(4:6,NaN), 200, replace=TRUE))
head(x)
x <- replace(x, is.na(x), 0)
head(x)
I was also facing the same issue
remote: Repository not found
fatal: repository 'https://github.com/MyRepo/project.git/' not found
I uninstalled the git credentials manager and reinstalled it and then I could easily pull and push to the repository. Here are the commands
$ git credential-manager uninstall
$ git credential-manager install
Just had the same issue while using the latest Python 3.6. With Windows OS 10 Home Edition and 64 Bit Operation System
Steps to solve this issue :
Isn't this as simple as adding your git install to your Windows path?
E.g. Win+R rundll32.exe sysdm.cpl,EditEnvironmentVariables
Edit...PATH appending your Mysysgit install path e.g. ;C:\Program Files (x86)\Git\bin
. Re-run Cygwin and voila. As Cygwin automatically loads in the Windows environment, so too will your native install of Git.
I've more recently found a much cleaner approach to this, which can be executed at any time, rather than being forced to do it synchronously when the script loads.
Use stackinfo to get a stacktrace at a current location, and grab the info.file
name off the top of the stack.
info = stackinfo()
console.log('This is the url of the script '+info[0].file)
None of these examples on this page worked for me. This is what I used and it worked well. Some solutions said you cannot combine url with $state.go() but this is not true. The awkward thing is you must define the params for the url and also list the params. Both must be present. Tested on Angular 1.4.8 and UI Router 0.2.15.
In the state add your params to end of state and define the params:
url: 'view?index&anotherKey',
params: {'index': null, 'anotherKey': null}
In your controller your go statement will look like this:
$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' });
Then to pull the params out and use them in your new state's controller (don't forget to pass in $stateParams to your controller function):
var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
console.log(anotherKey); //it works!
It is a function expression, it stands for Immediately Invoked Function Expression (IIFE). IIFE is simply a function that is executed right after it is created. So insted of the function having to wait until it is called to be executed, IIFE is executed immediately. Let's construct the IIFE by example. Suppose we have an add function which takes two integers as args and returns the sum lets make the add function into an IIFE,
Step 1: Define the function
function add (a, b){
return a+b;
}
add(5,5);
Step2: Call the function by wrap the entire functtion declaration into parentheses
(function add (a, b){
return a+b;
})
//add(5,5);
Step 3: To invock the function immediatly just remove the 'add' text from the call.
(function add (a, b){
return a+b;
})(5,5);
The main reason to use an IFFE is to preserve a private scope within your function. Inside your javascript code you want to make sure that, you are not overriding any global variable. Sometimes you may accidentaly define a variable that overrides a global variable. Let's try by example. suppose we have an html file called iffe.html and codes inside body tag are-
<body>
<div id = 'demo'></div>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
Well, above code will execute with out any question, now assume you decleard a variable named document accidentaly or intentional.
<body>
<div id = 'demo'></div>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
const document = "hi there";
console.log(document);
</script>
</body>
you will endup in a SyntaxError: redeclaration of non-configurable global property document.
But if your desire is to declear a variable name documet you can do it by using IFFE.
<body>
<div id = 'demo'></div>
<script>
(function(){
const document = "hi there";
this.document.getElementById("demo").innerHTML = "Hello JavaScript!";
console.log(document);
})();
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
Output:
Let's try by an another example, suppose we have an calculator object like bellow-
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
console.log(calculator.add(5,10));
</script>
</body>
Well it's working like a charm, what if we accidently re-assigne the value of calculator object.
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
console.log(calculator.add(5,10));
calculator = "scientific calculator";
console.log(calculator.mul(5,5));
</script>
</body>
yes you will endup with a TypeError: calculator.mul is not a function iffe.html
But with the help of IFFE we can create a private scope where we can create another variable name calculator and use it;
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
var cal = (function(){
var calculator = {
sub:function(a,b){
return a-b;
},
div:function(a,b){
return a/b;
}
}
console.log(this.calculator.mul(5,10));
console.log(calculator.sub(10,5));
return calculator;
})();
console.log(calculator.add(5,10));
console.log(cal.div(10,5));
</script>
</body>
'*' works as a modifier for the previous item. So 'abc*def' searches for 'ab' followed by 0 or more 'c's follwed by 'def'.
What you probably want is 'abc.*def' which searches for 'abc' followed by any number of characters, follwed by 'def'.
I have tried the Javascript routines at phpjs.org and they have worked well.
I first tried the routines suggested in the chosen answer by Ranhiru Cooray - http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
I found that they did not work in all circumstances. I wrote up a test case where these routines fail and posted them to GitHub at:
https://github.com/scottcarter/base64_javascript_test_data.git
I also posted a comment to the blog post at ntt.cc to alert the author (awaiting moderation - the article is old so not sure if comment will get posted).
If you just want to find and replace all environment variables ($ExampleEnvVar) in a Dockerfile then build it this would work:
envsubst < /path/to/Dockerfile | docker build -t myDockerImage . -f -
?? Indian rupee sign. HTML: ₹
— ₹ or ₹
— also ₹, corresponding to Unicode U+20B9.
Disclaimer: This is just a copy of a comment by bobbaluba made more visible for future visitors. It helped me more than any other answer.
You have to drop the ssh://
prefix when using git clone
as an example
git clone [email protected]:owner/repo.git
May be you have ftped the file in ascii mode instead of binary mode ? If not, this might help.
$ gunzip myarchive.tar.gz
And then untar the resulting tar file using
$ tar xvf myarchive.tar
Hope this helps.
Got into django recently and been looking into a solution to that and found a method that might be useful.
So for example, if using allouth the default redirect is accounts/profile. Make a view that solely redirects to a location of choice using the username field like so:
def profile(request):
name=request.user.username
return redirect('-----choose where-----' + name + '/')
Then create a view that captures it in one of your apps, for example:
def profile(request, name):
user = get_object_or_404(User, username=name)
return render(request, 'myproject/user.html', {'profile': user})
Where the urlpatterns capture would look like this:
url(r'^(?P<name>.+)/$', views.profile, name='user')
Works well for me.
Assuming that your markup looks like:
<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>
Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).
Add a z-index
on header; 1
should be sufficient.
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
L = ['L','O','L']
makeitastring = ''.join(map(str, L))
This example selects a new Range
of Cells
defined by the current cell to a cell 5 to the right.
Note that .Offset
takes arguments of Offset(row, columns)
and can be quite useful.
Sub testForStackOverflow()
Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub
You can make it wait using $RANDOM, a default random number generator. In the below I am using 240 seconds. Hope that helps @
> WAIT_FOR_SECONDS=`/usr/bin/expr $RANDOM % 240` /bin/sleep
> $WAIT_FOR_SECONDS
use
keyword from Command Line Interface:PHP Namespaces don't work on the commandline unless you also include or require the php file. When the php file is sitting in the webspace where it is interpreted by the php daemon then you don't need the require line. All you need is the 'use' line.
Create a new directory /home/el/bin
Make a new file called namespace_example.php
and put this code in there:
<?php
require '/home/el/bin/mylib.php';
use foobarwhatever\dingdong\penguinclass;
$mypenguin = new penguinclass();
echo $mypenguin->msg();
?>
Make another file called mylib.php
and put this code in there:
<?php
namespace foobarwhatever\dingdong;
class penguinclass
{
public function msg() {
return "It's a beautiful day chris, come out and play! " .
"NO! *SLAM!* taka taka taka taka.";
}
}
?>
Run it from commandline like this:
el@apollo:~/bin$ php namespace_example.php
Which prints:
It's a beautiful day chris, come out and play!
NO! *SLAM!* taka taka taka taka
See notes on this in the comments here: http://php.net/manual/en/language.namespaces.importing.php
SWIFT 3
fileprivate func openAppStore() {
let appId = "YOUR_APP_ID"
let url_string = "itms-apps://itunes.apple.com/app/id\(appId)"
if let url = URL(string: url_string) {
UIApplication.shared.openURL(url)
}
}
You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too. .....
I have used this and it works for me.Also include jquery migrate plugin,and jquery file.
if ( $.browser.webkit ) {
alert( "This is WebKit!" );
}
I've used (DB Solo) and I like it a lot. It's only $99 and comparable to many more expensive tools. It supports Oracle, SQL Server, Sybase, MySQL, PostgreSQL and others.
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
command.Text = "UPDATE Student
SET Address = @add, City = @cit
Where FirstName = @fn and LastName = @add";
For those who want to know if an object is a jQuery object without having jQuery installed, the following snippet should do the work :
function isJQuery(obj) {
// Each jquery object has a "jquery" attribute that contains the version of the lib.
return typeof obj === "object" && obj && obj["jquery"];
}
I eventually figured it out. Place:
import warnings
warnings.filterwarnings('ignore')
inside ~/.ipython/profile_default/startup/disable-warnings.py
. I'm leaving this question and answer for the record in case anyone else comes across the same issue.
Quite often it is useful to see a warning once. This can be set by:
warnings.filterwarnings(action='once')
I Used Datatable JS plugin for my purpose of exporting an html table data into various formats. With my experience it was very quick, easy to use and configure with minimal coding.
Below is a sample jquery call using datatable plugin, #example
is your table id
$(document).ready(function() {
$('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
} );
} );
Please find the complete example in below datatable reference link :
https://datatables.net/extensions/buttons/examples/html5/simple.html
This is how it looks after configuration( from reference site) :
You need to have following library references in your html ( some can be found in the above reference link)
jquery-1.12.3.js
jquery.dataTables.min.js
dataTables.buttons.min.js
jszip.min.js
pdfmake.min.js
vfs_fonts.js
buttons.html5.min.js
use
System.out.print( nir[0].length);
look at this for loop which print the content of the 2 dimension array the second loop iterate over the column in each row
for(int row =0 ; row < ntr.length; ++row)
for(int column =0; column<ntr[row].length;++column)
System.out.print(ntr[row][column]);
This doesn't work. only one value is ever pre-selected even though both options are available in the list only the first is shown
('#searchproject').select2('val', ['New Co-location','Expansion']);
You could also set them to float to the right.
#ul_top_hypers li {
float: right;
}
This allows them to still be block level, but will appear on the same line.
use the builtin: (no need for tkinter)
s = input('->>')
print(s) # what you just typed); now use if's
list(your_iterator)
ANDROID_HOME
is deprecated now instead of using ANDROID_HOME
use ANDROID_SDK_ROOT
as per Google android documentation -
ANDROID_SDK_ROOT
sets the path to the SDK installation directory. Once set, the value does not typically change, and can be shared by multiple users on the same machine. ANDROID_HOME, which also points to the SDK installation directory, is deprecated.
If you continue to use it, the following rules apply:
ANDROID_HOME
is defined and contains a valid SDK installation, its value is used instead of the value in ANDROID_SDK_ROOT
.ANDROID_HOME
is not defined, the value in ANDROID_SDK_ROOT
is used.ANDROID_HOME
is defined but does not exist or does not contain a valid SDK installation, the value in ANDROID_SDK_ROOT
is used instead.For details follow this Android Documentation link
Check the IIS settings. I use IIS 7.5 with 32 or 64 bit compilation within the .NET framework. If you have an app that uses 32-bit mode, make sure to enable the App Pool to be able to use 32-bit instruction. Otherwise, nothing seems to work no matter how much you set the security or strong sign the DLL.
Remove the parentheses:
List<string> nameslist = new List<string> {"one", "two", "three"};
I had a similar problem and I searched for the solution for quite a while: It appears that the string parameter is case sensitive. So if your filename is abc.TXT but you search for abc.txt, eclipse will find it - the executable JAR file won't.
That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c
then you should check if you're including correctly the header file.
Check your #include
's and make sure the definition of the struct is done before declaring any variable of that type.
I had the same issue. I'm running a java rest app on a jboss server. But I think the solution is similar on an ASP .NET webapp.
Firefox makes a pre call to your server / rest url to check which options are allowed. That is the "OPTIONS" request which your server doesn't reply to accordingly. If this OPTIONS call is replied correct a second call is performed which is the actual "POST" request with json content.
This only happens when performing a cross-domain call. In your case calling 'http://localhost:16329/Hello
' instead of calling a url path under the same domain '/Hello'
If you intend to make a cross domain call you have to enhance your rest service class with an annotated method the supports a "OPTIONS" http request. This is the according java implementation:
@Path("/rest")
public class RestfulService {
@POST
@Path("/Hello")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public string HelloWorld(string name)
{
return "hello, " + name;
}
//THIS NEEDS TO BE ADDED ADDITIONALLY IF MAKING CROSS-DOMAIN CALLS
@OPTIONS
@Path("/Hello")
@Produces(MediaType.TEXT_PLAIN+ ";charset=utf-8")
public Response checkOptions(){
return Response.status(200)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.header("Access-Control-Allow-Methods", "POST, OPTIONS") //CAN BE ENHANCED WITH OTHER HTTP CALL METHODS
.build();
}
}
So I guess in .NET you have to add an additional method annotated with
[WebInvoke(
Method = "OPTIONS",
UriTemplate = "Hello",
ResponseFormat = WebMessageFormat.)]
where the following headers are set
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.header("Access-Control-Allow-Methods", "POST, OPTIONS")
I can't say this is the most bulletproof or portable solution, but it works for my testing scripts:
.output /tmp/temp_drop_tables.sql
select 'drop table ' || name || ';' from sqlite_master where type = 'table';
.output stdout
.read /tmp/temp_drop_tables.sql
.system rm /tmp/temp_drop_tables.sql
This bit of code redirects output to a temporary file, constructs the 'drop table' commands that I want to run (sending the commands to the temp file), sets output back to standard out, then executes the commands from the file, and finally removes the file.
When you want to remove a string, rather than replace it you can use String#delete
(or its mutator equivalent String#delete!
), e.g.:
x = "foo\nfoo"
x.delete!("\n")
x
now equals "foofoo"
In this specific case String#delete
is more readable than gsub
since you are not actually replacing the string with anything.
Please update your php.ini with
default_socket_timeout = 120
You can create your own php.ini if php is installed a CGI instead of a Apache module
The input.files
attribute is an HTML5 feature. That's why some browsers din't return anything.
Simply add a fallback to the plain old input.value
(string) if files
doesn't exist.
reference: http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-apis.html#dom-input-files
First off, RangeToHTML
. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.
On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.
For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.
Sub Mail_Selection_Range_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
' Only send the visible cells in the selection.
Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected. " & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = RangetoHTML(rng)
' In place of the following statement, you can use ".Display" to
' display the e-mail message.
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' By Ron de Bruin.
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Column values from the SELECT statement are assigned into @low
and @day
local variables; the @adjustedLow
value is not assigned into any variable and it causes the problem:
The problem is here:
select
top 1 @low = low
, @day = day
, @adjustedLow -- causes error!
--select high
from
securityquote sq
...
Detailed explanation and workaround: SQL Server Error Messages - Msg 141 - A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
UPDATED TO SWIFT 5
We can get pretty descriptions of type names using the instance variable through the String
initializer and create new objects of a certain class
Like, for example print(String(describing: type(of: object)))
. Where object
can be an instance variable like array, a dictionary, an Int
, a NSDate
, etc.
Because NSObject
is the root class of most Objective-C class hierarchies, you could try to make an extension for NSObject
to get the class name of every subclass of NSObject
. Like this:
extension NSObject {
var theClassName: String {
return NSStringFromClass(type(of: self))
}
}
Or you could make a static funcion whose parameter is of type Any
(The protocol to which all types implicitly conform) and returns the class name as String. Like this:
class Utility{
class func classNameAsString(_ obj: Any) -> String {
//prints more readable results for dictionaries, arrays, Int, etc
return String(describing: type(of: obj))
}
}
Now you can do something like this:
class ClassOne : UIViewController{ /* some code here */ }
class ClassTwo : ClassOne{ /* some code here */ }
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Get the class name as String
let dictionary: [String: CGFloat] = [:]
let array: [Int] = []
let int = 9
let numFloat: CGFloat = 3.0
let numDouble: Double = 1.0
let classOne = ClassOne()
let classTwo: ClassTwo? = ClassTwo()
let now = NSDate()
let lbl = UILabel()
print("dictionary: [String: CGFloat] = [:] -> \(Utility.classNameAsString(dictionary))")
print("array: [Int] = [] -> \(Utility.classNameAsString(array))")
print("int = 9 -> \(Utility.classNameAsString(int))")
print("numFloat: CGFloat = 3.0 -> \(Utility.classNameAsString(numFloat))")
print("numDouble: Double = 1.0 -> \(Utility.classNameAsString(numDouble))")
print("classOne = ClassOne() -> \((ClassOne).self)") //we use the Extension
if classTwo != nil {
print("classTwo: ClassTwo? = ClassTwo() -> \(Utility.classNameAsString(classTwo!))") //now we can use a Forced-Value Expression and unwrap the value
}
print("now = Date() -> \(Utility.classNameAsString(now))")
print("lbl = UILabel() -> \(String(describing: type(of: lbl)))") // we use the String initializer directly
}
}
Also, once we can get the class name as String, we can instantiate new objects of that class:
// Instantiate a class from a String
print("\nInstantiate a class from a String")
let aClassName = classOne.theClassName
let aClassType = NSClassFromString(aClassName) as! NSObject.Type
let instance = aClassType.init() // we create a new object
print(String(cString: class_getName(type(of: instance))))
print(instance.self is ClassOne)
Maybe this helps someone out there!.
I believe that XDocument
makes a lot more object creation calls. I suspect that for when you're handling a lot of XML documents, XMLDocument
will be faster.
One place this happens is in managing scan data. Many scan tools output their data in XML (for obvious reasons). If you have to process a lot of these scan files, I think you'll have better performance with XMLDocument
.
select package name and sub package name both
press "save" a warning pop ups , press "continue"
name changed successfully
There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.
More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:
ping -s 1472
...)tc
iperf
Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat
or lsof
). If that number is substantial, you might:
ulimit -n
. Still, ~1000 connections (default on my system) is quite a few.iostat -x
?Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.
I hope this provides some help. You're really asking a networking question.
Strongly typed enums aiming to solve multiple problems and not only scoping problem as you mentioned in your question:
Thus, it is impossible to implicitly convert a strongly typed enum to integers, or even its underlying type - that's the idea. So you have to use static_cast
to make conversion explicit.
If your only problem is scoping and you really want to have implicit promotion to integers, then you better off using not strongly typed enum with the scope of the structure it is declared in.
To add to the others, var_export might be handy too:
$email_text = var_export($_POST, true);
I had this issue with a facebook application that I was developing for a fan page tab. If anyone faces this issue with a facebook application then
1-goto https://developers.facebook.com
2-select the application that you are developing
3-make sure that all the link to your application has tailing slash /
my issue was in the https://developers.facebook.com->Apps->MYAPPNAME->settings->Page Tab->Secure Page Tab URL, Page Tab Edit URL, Page Tab URL hope this will help
If you have a string with url that you want to decorate with a param, you could try this:
urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';
This means that ? will be the prefix of the parameter, but if you already have ? in urlstring
, than & will be the prefix.
I would also recommend to do encodeURI( paramvariable )
if you didn't hardcoded parameter, but it is inside a paramvariable
; or if you have funny characters in it.
See javascript URL Encoding for usage of the encodeURI
function.
this in your callback function refers to the clicked element.
$(".addressClick").click(function () {
var addressValue = $(this).attr("href");
alert(addressValue );
});
You can use ArrayUtils.EMPTY_STRING_ARRAY from org.apache.commons.lang3
import org.apache.commons.lang3.ArrayUtils;
class Scratch {
public static void main(String[] args) {
String[] strings = ArrayUtils.EMPTY_STRING_ARRAY;
}
}
Here is a script that I've written that handles both cases: 1) repository with a workspace, 2) bare repository.
https://gist.github.com/jdsumsion/6282953
git-root
(executable file in your path):
#!/bin/bash
GIT_DIR=`git rev-parse --git-dir` &&
(
if [ `basename $GIT_DIR` = ".git" ]; then
# handle normal git repos (with a .git dir)
cd $GIT_DIR/..
else
# handle bare git repos (the repo IS a xxx.git dir)
cd $GIT_DIR
fi
pwd
)
Hopefully this is helpful.