SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;
Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.
N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.
You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?
select a.id, a.object
from table_A a
inner join table_B b on a.id=b.id
where b.tag = 'chair';
Multiple SQL statements must be executed with the mysqli_multi_query()
function.
Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This kind of query should work - after rewriting with explicit JOIN
syntax:
SELECT something
FROM master parent
JOIN master child ON child.parent_id = parent.id
LEFT JOIN second parentdata ON parentdata.id = parent.secondary_id
LEFT JOIN second childdata ON childdata.id = child.secondary_id
WHERE parent.parent_id = 'rootID'
The tripping wire here is that an explicit JOIN
binds before "old style" CROSS JOIN
with comma (,
). I quote the manual here:
In any case
JOIN
binds more tightly than the commas separatingFROM
-list items.
After rewriting the first, all joins are applied left-to-right (logically - Postgres is free to rearrange tables in the query plan otherwise) and it works.
Just to make my point, this would work, too:
SELECT something
FROM master parent
LEFT JOIN second parentdata ON parentdata.id = parent.secondary_id
, master child
LEFT JOIN second childdata ON childdata.id = child.secondary_id
WHERE child.parent_id = parent.id
AND parent.parent_id = 'rootID'
But explicit JOIN
syntax is generally preferable, as your case illustrates once again.
And be aware that multiple (LEFT
) JOIN
can multiply rows:
What you've seen is what you get - and it's exactly what you asked for, here:
(ppc, c) => new { productproductcategory = ppc, category = c}
That's a lambda expression returning an anonymous type with those two properties.
In your CategorizedProducts, you just need to go via those properties:
CategorizedProducts catProducts = query.Select(
m => new {
ProdId = m.productproductcategory.product.Id,
CatId = m.category.CatId,
// other assignments
});
the best way (for me) to make it it's the next infrastructure:
<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>
with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.
First, review route inside index.php
require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
in my case the route did not work, I had to review the directories.
The bitmap constructor has resizing built in.
Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");
http://msdn.microsoft.com/en-us/library/0wh0045z.aspx
If you want control over interpolation modes see this post.
Personally i wouldnt store the image in the database, Instead put it in a folder not accessable from outside, and use the database for keeping track of its location. keeps database size down and you can just include it by using PHP. There would be no way without PHP to access that image then
It looks like you forgot to include the ngRoute module in your dependency for myApp.
In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.
'use strict';
angular.module('myApp', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);
This code worked for me
.navbar .navbar-nav {
display: inline-block;
float: none;
}
.navbar .navbar-collapse {
text-align: center;
}
The goal is to make the <body> element take up the available height of the screen.
If you don't expect your content to take up more than the height of the screen, or you plan to make an inner scrollable element, set
body {
height: 100vh;
}
otherwise, you want <body> to become scrollable when there is more content than the screen can hold, so set
body {
min-height: 100vh;
}
this alone achieves the goal, albeit with a possible, and probably desirable, refinement.
Removing the margin of <body>.
body {
margin: 0;
}
there are two main reasons for doing so.
P.S. if you want the background to be a radial gradient with its center in the center of the screen and not in the bottom right corner as with your example, consider using something like
body {
min-height: 100vh;
margin: 0;
background: radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(0,0,0,1) 100%);
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title>test</title>
</head>
<body>
</body>
</html>
_x000D_
selenium will do exactly what you want and it handles javascript
Easiest way is to use +strVal or Number(strVal)
Examples:
let strVal1 = "123.5"
let strVal2 = "One"
let val1a = +strVal1
let val1b = Number(strVal1)
let val1c = parseFloat(strVal1)
let val1d = parseInt(strVal1)
let val1e = +strVal1 - parseInt(strVal1)
let val2a = +strVal2
console.log("val1a->", val1a) // 123.5
console.log("val1b->", val1b) // 123.5
console.log("val1c->", val1c) // 123.5
console.log("val1d->", val1d) // 123
console.log("val1e->", val1e) // 0.5
console.log("val2a->", val2a) // NaN
try this
html code
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="firstname">
<input type="submit" name="submit" value="Submit">
</form>
php code:
if(isset($_POST['Submit'])){
$firstname=isset($_POST['firstname'])?$_post['firstname']:"";
echo $firstname;
}
Fiddler2 -> Rules -> Custom Rules
then find function OnBeforeRequest on put in the next script at the end:
if (oSession.HostnameIs("mysite.com")){
oSession.host="localhost:39901";
}
barryvdh/laravel-cors works perfectly with Laravel 5.1 with just a few key points in enabling it.
After adding it as a composer dependency, make sure you have published the CORS config file and adjusted the CORS headers as you want them. Here is how mine look in app/config/cors.php
<?php
return [
'supportsCredentials' => true,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE'],
'exposedHeaders' => ['DAV', 'content-length', 'Allow'],
'maxAge' => 86400,
'hosts' => [],
];
After this, there is one more step that's not mentioned in the documentation, you have to add the CORS handler 'Barryvdh\Cors\HandleCors'
in the App kernel. I prefer to use it in the global middleware stack. Like this
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'Barryvdh\Cors\HandleCors',
];
But its up to you to use it as a route middleware and place on specific routes.
This should make the package work with L5.1
A simpler way is to transverse the data, and hide the lines with the Visible
property.
// Prevent exception when hiding rows out of view
CurrencyManager currencyManager = (CurrencyManager)BindingContext[dataGridView3.DataSource];
currencyManager.SuspendBinding();
// Show all lines
for (int u = 0; u < dataGridView3.RowCount; u++)
{
dataGridView3.Rows[u].Visible = true;
x++;
}
// Hide the ones that you want with the filter you want.
for (int u = 0; u < dataGridView3.RowCount; u++)
{
if (dataGridView3.Rows[u].Cells[4].Value == "The filter string")
{
dataGridView3.Rows[u].Visible = true;
}
else
{
dataGridView3.Rows[u].Visible = false;
}
}
// Resume data grid view binding
currencyManager.ResumeBinding();
Just an idea... it works for me.
I experienced the same issue when sending high volume email. Setting the deliveryMethod
property to PickupDirectoryFromIis
fixed it for me.
Also don't create a new SmtpClient everytime.
I just finished writing my own optimised implementation of normalized cross-correlation for N-dimensional arrays. You can get it from here.
It will calculate cross-correlation either directly, using scipy.ndimage.correlate
, or in the frequency domain, using scipy.fftpack.fftn
/ifftn
depending on whichever will be quickest.
In your app.config
, change your appsetting to:
<applicationSettings>
<WpfApplication1.Properties.Settings>
<setting name="appsetting" serializeAs="String">
<value>c:\testdata.xml</value>
</setting>
</WpfApplication1.Properties.Settings>
</applicationSettings>
Then, in the code-behind:
string xmlDataDirectory = WpfApplication1.Properties.Settings.Default.appsetting.ToString()
This is what I did to get around this bug. The windows console (cmd) is just not worth using for anything other than some simple commands. So the following is what I did.
Installed Cygwin (Go here) It is pretty straight forward to install. You can watch this video. It explains very easily how to install cygwin. Make sure when you select the packages that you want to install includes Mintt (it is basically a better shell or cmd) and mysql client package.
Once you are done installing it, you should add the bin folder from cygwin in your PATH Environmental Variables(The above video explains that as well)
Now You will have an icon on the desktop for cygwin. Open it up and login to mysql using the normal commands. You will need to put the ip of the mysql server in the command to make it work. I use the following logging in MySQL which was installed through wamp
mysql -u root -p -h 127.0.0.1
You can add more arguments in there if you want. Once you get in mysql just press ctrl + L and you will clear the screen.
Step: set a button in XML with onClick Action:
<Button
android:id="@+id/btnEditUserInfo"
style="?android:borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="@dimen/txt_height"
android:layout_gravity="center"
android:background="@drawable/round_btn"
android:contentDescription="@string/image_view"
android:onClick="edit_user_info"
android:text="Edit"
android:textColor="#000"
android:textSize="@dimen/login_textSize" />
Step: on button clicked show animation point
//pgrm mark ---- ---- ----- ---- ---- ----- ---- ---- ----- ---- ---- -----
public void edit_user_info(View view) {
// show click effect on button pressed
final AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
view.startAnimation(buttonClick);
Intent intent = new Intent(getApplicationContext(), EditUserInfo.class);
startActivity(intent);
}// end edit_user_info
If you want case-insensitive comparison, use lower
or upper
:
if name.lower() == "jesse":
The benefits of super()
in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.
However, it's almost impossible to use multiple-inheritance without super()
. This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child
and a mixin, their code would not work properly.
The syntax for REPLACE:
REPLACE (string_expression,string_pattern,string_replacement)
So that the SQL you need should be:
UPDATE [DataTable] SET [ColumnValue] = REPLACE([ColumnValue], 'domain2', 'domain1')
Yes, there's str_to_date
mysql> select str_to_date("03/02/2009","%d/%m/%Y");
+--------------------------------------+
| str_to_date("03/02/2009","%d/%m/%Y") |
+--------------------------------------+
| 2009-02-03 |
+--------------------------------------+
1 row in set (0.00 sec)
I do not know how efficient this is, However worked for me in a simple context.
List<int> uniqueNumbers = new ArrayList<>();
public void AddNumberToList(int num)
{
if(!uniqueNumbers .contains(num)) {
uniqueNumbers .add(num);
}
}
In my experience all the files which i have downloaded from internet,gmail
are stored in
/sdcard/download
on ics
/sdcard/Download
You can access it using
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
int h = Screen.PrimaryScreen.WorkingArea.Height;
int w = Screen.PrimaryScreen.WorkingArea.Width;
this.ClientSize = new Size(w , h);
As simply as:
if (numbers.isEmpty()) {...}
Note that a quick look at the documentation would have given you that information.
If you're going to use this as an index into something else, you can use boolean indices if the arrays are broadcastable; you don't need explicit indices. The absolute simplest way to do this is to simply index based on a truth value.
other_array[first_array == item]
Any boolean operation works:
a = numpy.arange(100)
other_array[first_array > 50]
The nonzero method takes booleans, too:
index = numpy.nonzero(first_array == item)[0][0]
The two zeros are for the tuple of indices (assuming first_array is 1D) and then the first item in the array of indices.
You can put the condition after the WHEN
clause, like so:
SELECT
CASE
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
WHEN DS.DES = 'N' THEN 'Early Term'
WHEN DS.DES = 'Y' THEN 'Complete'
END
FROM
....
Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...
If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-
[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb
Mysql would then open this file for each user account read the credentials and open the selected database.
Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.
ORA-04031: unable to allocate 4064 bytes of shared memory ("shared pool","select increment$,minvalue,m...","sga heap(3,0)","kglsim heap")
1.-
ps -ef|grep oracle
2.- Find the smon and kill the pid for it
3.-
SQL> startup mount
ORACLE instance started.
Total System Global Area 4831838208 bytes
Fixed Size 2027320 bytes
Variable Size 4764729544 bytes
Database Buffers 50331648 bytes
Redo Buffers 14749696 bytes
Database mounted.
4.-
SQL> alter system set shared_pool_size=100M scope=spfile;
System altered.
5.-
SQL> shutdown immediate
ORA-01109: database not open
Database dismounted.
ORACLE instance shut down.
6.-
SQL> startup
ORACLE instance started.
Total System Global Area 4831838208 bytes
Fixed Size 2027320 bytes
Variable Size 4764729544 bytes
Database Buffers 50331648 bytes
Redo Buffers 14749696 bytes
Database mounted.
Database opened.
7.-
SQL> create pfile from spfile;
File created.
SOLVED
Please find in the below code which escapes the single quotes as part of the entered string using a regular expression. It validates if the user-entered string is comma-separated and at the same time it even escapes any single quote(s) entered as part of the string.
In order to escape single quotes, just enter a backward slash followed by a single quote like: \’ as part of the string. I used jQuery validator for this example, and you can use as per your convenience.
Valid String Examples:
'Hello'
'Hello', 'World'
'Hello','World'
'Hello','World',' '
'It\'s my world', 'Can\'t enjoy this without me.', 'Welcome, Guest'
HTML:
<tr>
<td>
<label class="control-label">
String Field:
</label>
<div class="inner-addon right-addon">
<input type="text" id="stringField"
name="stringField"
class="form-control"
autocomplete="off"
data-rule-required="true"
data-msg-required="Cannot be blank."
data-rule-commaSeparatedText="true"
data-msg-commaSeparatedText="Invalid comma separated value(s).">
</div>
</td>
JavaScript:
/**
*
* @param {type} param1
* @param {type} param2
* @param {type} param3
*/
jQuery.validator.addMethod('commaSeparatedText', function(value, element) {
if (value.length === 0) {
return true;
}
var expression = new RegExp("^((')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))(((,)|(,\\s))(')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))*$");
return expression.test(value);
}, 'Invalid comma separated string values.');
Apologize for resurrect this thread, but for Windows 8.x users can find my.cnf at this folder:
C:\ProgramData\MySQL\MySQL Server 5.6\my.ini
Then also can find data folder on same folder.
you may use yourArray.length
to findout number of elements in an array.
Make sure yourArray is not null before doing yourArray.length
, otherwise you will end up with NullPointerException
.
There's of course the rather obvious:
Data[...,0] + 1j * Data[...,1]
This suggestion fixed it for me. Clear out the WebSiteCache in C:\Users\username\AppData\Local\Microsoft\WebSiteCache
http://blog.geocortex.com/2007/12/07/slow-visual-studio-performance-solved/
I'm not really too clear what you are asking, but using the -f
command line option just specifies a file - it doesn't tell make to change directories. If you want to do the work in another directory, you need to cd
to the directory:
clean:
cd gtest-1.4.0 && $(MAKE) clean
Note that each line in Makefile
runs in a separate shell, so there is no need to change the directory back.
I don't think you properly understood what you read. If it gets compiled to the correct type, then there is no difference. When I do this:
var i = 42;
The compiler knows it's an int, and generate code as if I had written
int i = 42;
As the post you linked to says, it gets compiled to the same type. It's not a runtime check or anything else requiring extra code. The compiler just figures out what the type must be, and uses that.
You get this behavior, because int array [ROW][COLUMN] = {1};
does not mean "set all items to one". Let me try to explain how this works step by step.
The explicit, overly clear way of initializing your array would be like this:
#define ROW 2
#define COLUMN 2
int array [ROW][COLUMN] =
{
{0, 0},
{0, 0}
};
However, C allows you to leave out some of the items in an array (or struct/union). You could for example write:
int array [ROW][COLUMN] =
{
{1, 2}
};
This means, initialize the first elements to 1 and 2, and the rest of the elements "as if they had static storage duration". There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero.
So in the above example, the first row gets set to 1,2 and the next to 0,0 since we didn't give them any explicit values.
Next, there is a rule in C allowing lax brace style. The first example could as well be written as
int array [ROW][COLUMN] = {0, 0, 0, 0};
although of course this is poor style, it is harder to read and understand. But this rule is convenient, because it allows us to write
int array [ROW][COLUMN] = {0};
which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."
therefore, if you attempt
int array [ROW][COLUMN] = {1};
it means "initialize the very first column in the first row to 1 and set all other items to zero".
The "braces" are making an object literal, i.e. they create an object. It is one argument.
Example:
function someFunc(arg) {
alert(arg.foo);
alert(arg.bar);
}
someFunc({foo: "This", bar: "works!"});
the object can be created beforehand as well:
var someObject = {
foo: "This",
bar: "works!"
};
someFunc(someObject);
I recommend to read the MDN JavaScript Guide - Working with Objects.
Places is a list and not a dictionary. This line below should therefore not work:
print data['places']['latitude']
You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:
print data['places'][0]['post code']
Our Server environment : SQL2008 x64 SP2 Reporting Services on Windows Server 2008 x64,
Client PC environment: Windows XP SP2 with IE6 or higher, all users are login to Active Directory, users are not members of local Administrator or power user group.
Error: When a user printing a report getting an error as "Unable to load client print control"
Solution that work for us: replace following files in sql 2008 with SQL 2008 R2
Program Files\Microsoft SQL Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer\bin RSClientPrint-x86.cab RSClientPrint-x64.cab RSClientPrint-ia64.cab
Once you replace the files one server users wont get above error and they do not required local power user or admin right to download Active X. Recommending to add report server URL as a trusted site (add to Trusted sites) via Active Directory GP.
package com.android.jigsawtest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SurafaceClass extends SurfaceView implements
SurfaceHolder.Callback {
Bitmap mBitmap;
Paint paint =new Paint();
public SurafaceClass(Context context) {
super(context);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
// TODO Auto-generated constructor stub
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(mBitmap, 0, 0, paint);
}
}
The warning comes up because Tomcat scans all Jars for TLDs (Tagging Library Definitions).
Step1: To see which JARs are throwing up this warning, insert he following line to tomcat/conf/logging.properties
org.apache.jasper.servlet.TldScanner.level = FINE
Now you should be able to see warnings with a detail of which JARs are causing the intial warning
Step2 Since skipping unneeded JARs during scanning can improve startup time and JSP compilation time, we will skip un-needed JARS in the catalina.properties
file. You have two options here -
tomcat.util.scan.StandardJarScanFilter.jarsToSkip
. But this can get cumbersome if you have a lot jars or if the jars keep changing.tomcat.util.scan.StandardJarScanFilter.jarsToSkip=*
to skip all the jarsYou should now not see the above warnings and if you have a considerably large application, it should save you significant time in deploying an application.
Note: Tested in Tomcat8
I had that problem with Xamarin Forms and solved it with this:
percent.ToString("0.##"+"%")
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 10, 20,20, 30, 10, 50 ,50,9};
List<int> listadd = new List<int>();
for (int i=0; i <arr.Length;i++)
{
int count = 0;
int flag = 0;
for(int j=0; j < arr.Length; j++)
{
if (listadd.Contains(arr[i]) == false)
{
if (arr[i] == arr[j])
{
count++;
}
}
else
{
flag = 1;
}
}
listadd.Add(arr[i]);
if(flag!=1)
Console.WriteLine("No of occurance {0} \t{1}", arr[i], count);
}
Console.ReadLine();
}
}
Here's a function that returns substring of a given substring when start and end indices are provided. For complete reference you can visit the links given below.
func substring(string: String, fromIndex: Int, toIndex: Int) -> String? {
if fromIndex < toIndex && toIndex < string.count /*use string.characters.count for swift3*/{
let startIndex = string.index(string.startIndex, offsetBy: fromIndex)
let endIndex = string.index(string.startIndex, offsetBy: toIndex)
return String(string[startIndex..<endIndex])
}else{
return nil
}
}
Here's a link to the blog post that I have created to deal with string manipulation in swift. String manipulation in swift (Covers swift 4 as well)
If you're using ASP.NET MVC, I found Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1")
in a code block in _Layout to work quite well:
@Code
Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1")
End Code
<!DOCTYPE html>
everything else
Everyone: I Solved the problem like this. In Android Studio go to File menu and select the Invalidate Caches/Restart... I hope it will work for you. Thanks
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.
import pandas as pd
df = pd.read_csv('/PathToFile.txt', sep = ',')
This will import your .txt or .csv file into a DataFrame.
As lyyons pointed out in the comments, more idiomatic and lodashy way to do this would be to use _.remove
, like this
_.remove(obj.subTopics, {
subTopicId: stToDelete
});
Apart from that, you can pass a predicate function whose result will be used to determine if the current element has to be removed or not.
_.remove(obj.subTopics, function(currentObject) {
return currentObject.subTopicId === stToDelete;
});
Alternatively, you can create a new array by filtering the old one with _.filter
and assign it to the same object, like this
obj.subTopics = _.filter(obj.subTopics, function(currentObject) {
return currentObject.subTopicId !== stToDelete;
});
Or
obj.subTopics = _.filter(obj.subTopics, {subTopicId: stToKeep});
To ignore some folder from eslint rules we could create the file .eslintignore
in root directory and add there the path to the folder we want omit (the same way as for .gitignore
).
Here is the example from the ESLint docs on Ignoring Files and Directories:
# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default
# Ignore built files except build/index.js
build/*
!build/index.js
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
In addition to the above you can use the System.exit()
to return an exit code which may be very usuefull specially if your calling the process automatically using the System.exit(code);
this can help you determine for example if an error has occured during the run.
It seems that at the moment Ubuntu 15.10 has a but with python3 and pip3.
As elaborated in this article.
The problem makes pip3 install to python3.5 while python3 is actually running python3.4 :(
Until a proper solution will be available via the updates you can do one of the following:
run
python3 -m pip install pymysql
instead of
pip3 install pymysql
(or any other package)
Now
import pymysql
should work in python3 and in idle3.
Alternatively, if you explicitly need 3.5 you can use explicit python3.5 instead of python3. but idle3 will still point to 3.4...
Here's a one-liner:
List changed files & pack them as *.zip:
git diff --name-only | zip patched.zip -@
List last committed changed files & pack them as *.zip:
git diff --name-only HEAD~ HEAD | zip patched.zip -@
Syntax for Describe table
db2 describe table <tablename>
or For all table details
select * from syscat.tables
or For all table details
select * from sysibm.tables
You need a parameter with Direction set to ParameterDirection.ReturnValue
in code but no need to add an extra parameter in SP. Try this
SqlParameter returnParameter = cmd.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int id = (int) returnParameter.Value;
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
You can style the button using CSS or use an image-input. Additionally you might use the button
element which supports inline content.
<button type="submit"><img src="/path/to/image" alt="Submit"></button>
To bring together a number of different points above, here's a script that will run any arguments passed to the script vim new_tab.sh
:
#!/bin/bash
#
# Dependencies:
# sudo apt install xdotool
WID=$(xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"| awk '{print $5}')
xdotool windowfocus $WID
xdotool key ctrl+shift+t
wmctrl -i -a $WID
sleep 1; xdotool type --delay 1 --clearmodifiers "$@"; xdotool key Return;
Next make it executable:
chmod +x new_tab.sh
Now you can use it to run whatever you'd like in a new tab:
./new_tab.sh "watch ls -l"
By Java class, I am assuming you mean a Servlet class as setting session attribute in arbitrary Java class does not make sense.You can do something like this in your servlet's doGet/doPost methods
public void doGet(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
String username = (String)request.getAttribute("un");
session.setAttribute("UserName", username);
}
You can deserialize this really easily. The data's structure in C# is just List<string[]>
so you could just do;
List<string[]> data = JsonConvert.DeserializeObject<List<string[]>>(jsonString);
The above code is assuming you're using json.NET.
EDIT: Note the json is technically an array of string arrays. I prefer to use List<string[]>
for my own declaration because it's imo more intuitive. It won't cause any problems for json.NET, if you want it to be an array of string arrays then you need to change the type to (I think) string[][]
but there are some funny little gotcha's with jagged and 2D arrays in C# that I don't really know about so I just don't bother dealing with it here.
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
This can be caused by a vcxproj that originated in previous versions of Visual Studio OR changing the Platform Toolset in Configuration Properties -> General.
If so, possible Solution:
1) Go to Configuration Properties -> VC++ Directories
2) Select drop down for Executable Directories
3) Select "Inherit from parent or Project Defaults"
I have found these system properties on Samsung S8
SystemProperties.getInt("ro.multisim.simslotcount", 1) > 1
Also, according to the source: https://android.googlesource.com/platform/frameworks/base/+/master/telephony/java/com/android/internal/telephony/TelephonyProperties.java
getprop persist.radio.multisim.config
returns "dsds
" or "dsda
" on multi sim.
I have tested this on Samsung S8 and it works
Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.
An example:
function changeParam(x, y, z) {
x = 3;
y = "new string";
z["key2"] = "new";
z["key3"] = "newer";
z = {"new" : "object"};
}
var a = 1,
b = "something",
c = {"key1" : "whatever", "key2" : "original value"};
changeParam(a, b, c);
// at this point a is still 1
// b is still "something"
// c still points to the same object but its properties have been updated
// so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
// c definitely doesn't point to the new object created as the last line
// of the function with z = ...
Check target-membership of PrimeNumberModel.swift in your testing target.
Give the container class
.container{
height: 100vh;
width: 100vw;
display: flex;
}
Give the div that's inside the container:
align-content: center;
All the content inside this div will show up in the middle of the page.
$options = array(
'options' => array('min_range' => 0)
);
if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
// you're good
}
Try this:
var hms = '02:04:33'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
console.log(seconds);
As a heads up to others, I've oberserved that at least as manifested by TypeScript compiled by WebPack for Angular 2, you quietly get overWRITTEN instead of overLOADED methods.
myComponent {
method(): { console.info("no args"); },
method(arg): { console.info("with arg"); }
}
Calling:
myComponent.method()
seems to execute the method with arguments, silently ignoring the no-arg version, with output:
with arg
public static bool IsPositive<T>(T value)
where T : struct, IComparable<T>
{
return value.CompareTo(default(T)) > 0;
}
I am always used DateDiff(day,date1,date2) to compare two date.
Checkout following example. Just copy that and run in Ms sql server. Also, try with change date by 31 dec to 30 dec and check result
BEGIN
declare @firstDate datetime
declare @secondDate datetime
declare @chkDay int
set @firstDate ='2010-12-31 15:13:48.593'
set @secondDate ='2010-12-31 00:00:00.000'
set @chkDay=Datediff(day,@firstDate ,@secondDate )
if @chkDay=0
Begin
Print 'Date is Same'
end
else
Begin
Print 'Date is not Same'
end
End
I had this same issue and found that pkg-config
package was missing.
After installing the package, everything generated correctly.
There are several ways to do plots in R; lattice
is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:
Reasonstats <- read.table(text="Category Reason Species
Decline Genuine 24
Improved Genuine 16
Improved Misclassified 85
Decline Misclassified 41
Decline Taxonomic 2
Improved Taxonomic 7
Decline Unclear 41
Improved Unclear 117", header=T)
ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3 <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason
windows()
barplot(t(Reasonstats3), beside=TRUE, ylab="number of species",
cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
box(bty="l")
Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline
and for Improved
. Then I made those categories the column names. I also made the Reason
s the row names. The barplot()
function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot()
function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot()
wants for your intended output.
Don't do things like [A-Z] or [0-9]. Do \p{Lu} and \d instead. Of course, this is valid for perl based regex flavours. This includes java.
I would suggest that you don't make some huge regex. First split the text in sentences. then tokenize it (split into words). Use a regex to check each token/word. Skip the first token from sentence. Check if all tokens are uppercase beforehand and skip the whole sentence if so, or alter the regex in this case.
I just got this error and it was caused by a duplicate static content MIME type in the web.config
This error was being returned only on static files - eg images, css, js files were all saying this error (text by itself, no other html or text in the response).
The way to debug this is to look in web config under static content. Here we have a json file extension loaded. This was required on IIS7 but will kill the app if used on IIS8 because json is now pre-loaded at the server level.
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
So solution is to remove any of these mimeType entries one at a time to confirm which are needed and which kill your app!
Update
Actually the best solution was provided by a commenter here. You can remove and then add, which will always work regardless of whether it is already defined or not. Like this:
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
Like Jonathan said, yes, renaming can help to work around this problem. But ,e.g. I was forced to rename target executable many times, it's some tedious and not good.
The problem lies there that when you run your project and later get an error that you can't build your project - it's so because this executable (your project) is still runnning (you can check it via task manager.) If you just rename target build, some time later you will get the same error with new name too and if you open a task manager, you will see that you rubbish system with your not finished projects.
Visual studio for making a new build need to remove previous executable and create new instead of old, it can't do it while executable is still runinng. So, if you want to make a new build, process of old executable has to be closed! (it's strange that visual studio doesn't close it by itself and yes, it looks like some buggy behaviour).
It's some tedious to do it manually, so you may just a bat file and just click it when you have such problem:
taskkill /f /im name_of_target_executable.exe
it works for me at least. Like a guess - I don't close my program properly in C++, so may be it's normal for visual studio to hold it running.
ADDITION: There is a great chance to be so , because of not finished application. Check whether you called PostQuitMessage in the end, in order to give know Windows that you are done.
With expressjs, public it:
app.use('/stylesheets/fontawesome', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/'));
And you can see it at: yourdomain.com/stylesheets/fontawesome/css/all.min.css
"self" keyword holds the reference of class and it is upto you if you want to use it or not but if you notice, whenever you create a new method in python, python automatically write self keyword for you. If you do some R&D, you will notice that if you create say two methods in a class and try to call one inside another, it does not recognize method unless you add self (reference of class).
class testA:
def __init__(self):
print('ads')
def m1(self):
print('method 1')
self.m2()
def m2(self):
print('method 2')
Below code throws unresolvable reference error.
class testA:
def __init__(self):
print('ads')
def m1(self):
print('method 1')
m2() #throws unresolvable reference error as class does not know if m2 exist in class scope
def m2(self):
print('method 2')
Now let see below example
class testA:
def __init__(self):
print('ads')
def m1(self):
print('method 1')
def m2():
print('method 2')
Now when you create object of class testA, you can call method m1() using class object like this as method m1() has included self keyword
obj = testA()
obj.m1()
But if you want to call method m2(), because is has no self reference so you can call m2() directly using class name like below
testA.m2()
But keep in practice to live with self keyword as there are other benefits too of it like creating global variable inside and so on.
DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back ... As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.
From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
in Xcode 8 use:
DispatchQueue.global(qos: .userInitiated).async { }
You can do the following. Add your ggplot code after the first line of code and end with dev.off()
.
tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()
res=300
specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.
Change width
and height
in the code above depending on the desired output.
Note that this also works for other R
plots including plot
, image
, and pheatmap
.
Other file formats
In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.
You can use PapaParse to help. https://www.papaparse.com/
Here is a CodePen. https://codepen.io/sandro-wiggers/pen/VxrxNJ
Papa.parse(e, {
header:true,
before: function(file, inputElem){ console.log('Attempting to Parse...')},
error: function(err, file, inputElem, reason){ console.log(err); },
complete: function(results, file){ $.PAYLOAD = results; }
});
Download javax.mail.jar
and add it to your project using the following steps:
I had the same error message. I had the file in a simple .html, when I passed the file to php in Apache it worked
html2canvas(document.querySelector('#toPrint')).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
took the challenge to solve this issue. comment number 5 (M.Ali) asked for --"The required answer is 97.36 % (not 0.97 %) .." so for that i'm attaching a photo who compare between post number 3 (sqluser) to my solution. (i'm using the postgre_sql on a mac)
Note: cuongle's helfpul answer has all the ingredients, but the solution can be streamlined (no need for .ItemArray
) and can be reframed to better match the question as asked.
To create an (isolated) clone of a given System.Data.DataRow
instance, you can do the following:
// Assume that variable `table` contains the source data table.
// Create an auxiliary, empty, column-structure-only clone of the source data table.
var tableAux = table.Clone();
// Note: .Copy(), by contrast, would clone the data rows also.
// Select the data row to clone, e.g. the 2nd one:
var row = table.Rows[1];
// Import the data row of interest into the aux. table.
// This creates a *shallow clone* of it.
// Note: If you'll be *reusing* the aux. table for single-row cloning later, call
// tableAux.Clear() first.
tableAux.ImportRow(row);
// Extract the cloned row from the aux. table:
var rowClone = tableAux.Rows[0];
Note: Shallow cloning is performed, which works as-is with column values that are value type instances, but more work would be needed to also create independent copies of column values containing reference type instances (and creating such independent copies isn't always possible).
Roman, if you want to do your layout in Java code (ViewGroup descendant), it is possible. The trick is that you have to implement both onMeasure and onLayout methods. The onMeasure gets called first and you need to "measure" the subview (effectively sizing it to the desired value) there. You need to size it again in the onLayout call. If you fail to do this sequence or fail to call setMeasuredDimension() at the end of your onMeasure code, you won't get results. Why is this designed in such complicated and fragile way is beyond me.
git checkout master -- myplugin.js
master = branch name
myplugin.js = file name
Since Google takes you to this post when searching for C# Web API Referrer
here's the deal: Web API
uses a different type of Request
from normal MVC Request
called HttpRequestMessage
which does not include UrlReferrer
. Since a normal Web API
request does not include this information, if you really need it, you must have your clients go out of their way to include it. Although you could make this be part of your API Object
, a better way is to use Headers
.
First, you can extend HttpRequestMessage
to provide a UrlReferrer()
method:
public static string UrlReferrer(this HttpRequestMessage request)
{
return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}
Then your clients need to set the Referrer Header
to their API Request
:
// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);
And now the Web API Request
includes the referrer data which you can access like this from your Web API
:
Request.UrlReferrer();
My personal convention, which I describe below, is this:
Always prefer
interface
overtype
.
When to use type
:
type
when defining an alias for primitive types (string, boolean, number, bigint, symbol, etc)type
when defining tuple typestype
when defining function typestype
when defining a uniontype
when trying to overload functions in object types via compositiontype
when needing to take advantage of mapped typesWhen to use interface
:
interface
for all object types where using type
is not required (see above)interface
when you want to take advatange of declaration merging.The easiest difference to see between type
and interface
is that only type
can be used to alias a primitive:
type Nullish = null | undefined;
type Fruit = 'apple' | 'pear' | 'orange';
type Num = number | bigint;
None of these examples are possible to achieve with interfaces.
When providing a type alias for a primitive value, use the type
keyword.
Tuples can only be typed via the type
keyword:
type row = [colOne: number, colTwo: string];
Use the type
keyword when providing types for tuples.
Functions can be typed by both the type
and interface
keywords:
// via type
type Sum = (x: number, y: number) => number;
// via interface
interface Sum {
(x: number, y: number): number;
}
Since the same effect can be achieved either way, the rule will be to use type
in these scenarios since it's a little easier to read (and less verbose).
Use type
when defining function types.
Union types can only be achieved with the type
keyword:
type Fruit = 'apple' | 'pear' | 'orange';
type Vegetable = 'broccoli' | 'carrot' | 'lettuce';
// 'apple' | 'pear' | 'orange' | 'broccoli' | 'carrot' | 'lettuce';
type HealthyFoods = Fruit | Vegetable;
When defining union types, use the type
keyword
An object in javascript is a key/value map, and an "object type" is typescript's way of typing those key/value maps. Both interface
and type
can be used when providing types for an object as the original question makes clear. So when do you use type
vs interface
for object types?
With types and composition, I can do something like this:
type NumLogger = {
log: (val: number) => void;
}
type StrAndNumLogger = NumLogger & {
log: (val: string) => void;
}
const logger: StrAndNumLogger = {
log: (val: string | number) => console.log(val)
}
logger.log(1)
logger.log('hi')
Typescript is totally happy. What about if I tried that with interfaces:
interface NumLogger {
log: (val: number) => void;
}
interface StrAndNumLogger extends NumLogger {
log: (val: string) => void;
};
The declaration of StrAndNumLogger
gives me an error:
With interfaces, the subtypes have to exactly match the types declared in the super type, otherwise TS will throw an error like the one above.
When trying to overload functions in object types, you'll be better off using the type
keyword.
The key aspect to interfaces in typescript that distinguish them from types is that they can be extended with new functionality after they've already been declared. A common use case for this feature occurs when you want to extend the types that are exported from a node module. For example, @types/jest
exports types that can be used when working with the jest library. However, jest also allows for extending the main jest
type with new functions. For example, I can add a custom test like this:
jest.timedTest = async (testName, wrappedTest, timeout) =>
test(
testName,
async () => {
const start = Date.now();
await wrappedTest(mockTrack);
const end = Date.now();
console.log(`elapsed time in ms: ${end - start}`);
},
timeout
);
And then I can use it like this:
test.timedTest('this is my custom test', () => {
expect(true).toBe(true);
});
And now the time elapsed for that test will be printed to the console once the test is complete. Great! There's only one problem - typescript has no clue that i've added a timedTest
function, so it'll throw an error in the editor (the code will run fine, but TS will be angry).
To resolve this, I need to tell TS that there's a new type on top of the existing types that are already available from jest. To do that, I can do this:
declare namespace jest {
interface It {
timedTest: (name: string, fn: (mockTrack: Mock) => any, timeout?: number) => void;
}
}
Because of how interfaces work, this type declaration will be merged with the type declarations exported from @types/jest
. So I didn't just re-declare jest.It
; I extended jest.It
with a new function so that TS is now aware of my custom test function.
This type of thing is not possible with the type
keyword. If @types/jest
had declared their types with the type
keyword, I wouldn't have been able to extend those types with my own custom types, and therefore there would have been no good way to make TS happy about my new function. This process that is unique to the interface
keyword is called declaration merging.
Declaration merging is also possible to do locally like this:
interface Person {
name: string;
}
interface Person {
age: number;
}
// no error
const person: Person = {
name: 'Mark',
age: 25
};
If I did the exact same thing above with the type
keyword, I would have gotten an error since types cannot be re-declared/merged. In the real world, javascript objects are much like this interface
example; they can be dynamically updated with new fields at runtime.
Because interface declarations can be merged, interfaces more accurately represent the dynamic nature of javascript objects than types do, and they should be preferred for that reason.
With the type
keyword, I can take advantage of mapped types like this:
type Fruit = 'apple' | 'orange' | 'banana';
type FruitCount = {
[key in Fruit]: number;
}
const fruits: FruitCount = {
apple: 2,
orange: 3,
banana: 4
};
This cannot be done with interfaces:
type Fruit = 'apple' | 'orange' | 'banana';
// ERROR:
interface FruitCount {
[key in Fruit]: number;
}
When needing to take advantage of mapped types, use the type
keyword
I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.
$.ajax({
type: 'POST',
url: 'somescript.php',
data: someData,
complete: function(jqXHR) {
if(jqXHR.readyState === 4) {
... run some code ...
}
}
});
in jQuery 1.5 you can also do it like this.
var ajax = $.ajax({
type: 'POST',
url: 'somescript.php',
data: 'someData'
});
ajax.complete(function(jqXHR){
if(jqXHR.readyState === 4) {
... run some code ...
}
});
A bit more readable and simple approach could be achieved with the script below:
$Directory = "./"
Get-ChildItem $Directory -Recurse | % {
if ($_.Attributes -eq "Directory") {
Write-Host $_.FullName
}
}
Hope this helps!
If you want to do multiple $ne
then do
db.users.find({name : {$nin : ["mary", "dick", "jane"]}})
You can use this, just think Job is the name of the model to which you are adding index cader_id:
class AddCaderIdToJob < ActiveRecord::Migration[5.2]
def change
change_table :jobs do |t|
t.integer :cader_id
t.index :cader_id
end
end
end
You can build up a dictionary from a set of length-2 sequences. Extremely handy when you have a list of values and a list of arrays.
>>> dict([ ('foo','bar'),('a',1),('b',2) ])
{'a': 1, 'b': 2, 'foo': 'bar'}
>>> names = ['Bob', 'Marie', 'Alice']
>>> ages = [23, 27, 36]
>>> dict(zip(names, ages))
{'Alice': 36, 'Bob': 23, 'Marie': 27}
changing the SVG file was not a fair solution for me so instead, I used relative CSS units.
vh
, vw
, %
are very handy. I used a CSS like height: 2.4vh;
to set a dynamic size to my SVG images.
I found my answer.
<?php
$profpic = "bg.jpg";
?>
<html>
<head>
<style type="text/css">
body {
background-image: url('<?php echo $profpic;?>');
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button rtn = (Button)findViewById(R.id.button);
EditText edit_text = (EditText)findViewById(R.id.edittext1);
rtn .setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText value=", edit_text.getText().toString());
}
});
}
For me, It's working like this one.
C:\Program Files\PostgreSQL\12\bin> psql -U postgres -p 5432 -d dummy -f C:\Users\Downloads\d2cm_test.sql
Both of the previous 2 answers have at least O(n) time complexity and the string conversion has O(n) space complexity too. Here's a solution for constant time and space:
num // 10 ** (int(math.log(num, 10)) - 1)
import math
def first_n_digits(num, n):
return num // 10 ** (int(math.log(num, 10)) - n + 1)
>>> first_n_digits(123456, 1)
1
>>> first_n_digits(123456, 2)
12
>>> first_n_digits(123456, 3)
123
>>> first_n_digits(123456, 4)
1234
>>> first_n_digits(123456, 5)
12345
>>> first_n_digits(123456, 6)
123456
You will need to add some checks if it's possible that your input number has less digits than you want.
On the menu go to: "Run" --> "Run..." (or just press F5).
py -2 -i "$(FULL_CURRENT_PATH)"
py -3 -i "$(FULL_CURRENT_PATH)"
To understand the py
command better:
py -h
Another helpful link to understand the py
command: How do I run python 2 and 3 in windows 7?
Thanks to Reshure for his answer that got me on the right track to figure this out.
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
Add this to your python script.
import os
os.system("exec /path/to/another/script")
This executes that command as if it were typed into the shell.
HTML:
<button type="submit" name="submit" class="button">
<img src="images/free.png" />
</button>
CSS:
.button { }
It should be possible using the command
sudo /etc/init.d/apache2 reload
I hope that helps.
If you want a more accurate measurement than the answer above:
set statistics time on
-- Query 1 goes here
-- Query 2 goes here
set statistics time off
The results will be in the Messages window.
Update (2015-07-29):
By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by sys.dm_exec_procedure_stats
that may also be of value:
-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.
-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';
SELECT CONVERT(TIME(3),DATEADD(ms,ROUND(last_elapsed_time/1000.0,0),0))
AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
(OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
(DB_NAME(database_id)=@DbName OR @DbName IS NULL)
$('#cmd2').click(function() {_x000D_
var options = {_x000D_
//'width': 800,_x000D_
};_x000D_
var pdf = new jsPDF('p', 'pt', 'a4');_x000D_
pdf.addHTML($("#content2"), -1, 220, options, function() {_x000D_
pdf.save('admit_card.pdf');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>_x000D_
_x000D_
<div id="content2" style="background: #fff;border-bottom: 1px solid #ffffff;">_x000D_
<div class="tokenDet" style="padding: 15px;border: 1px solid #000;width: 80%;margin: 0 auto;position: relative;overflow: hidden;">_x000D_
<div class="title" style="text-align: center;border-bottom: 1px solid #000;margin-bottom: 15px;">_x000D_
<h2>Entrance Exam Hall Ticket</h2>_x000D_
</div>_x000D_
<div class="parentdiv" style="display: inline-block;width: 100%;position: relative;">_x000D_
<div class="innerdiv" style="width: 80%;float: left;">_x000D_
<div class="restDet">_x000D_
<div class="div">_x000D_
<div class="label" style="width: 30%;float: left;">_x000D_
<strong>Name</strong>_x000D_
</div>_x000D_
<div class="data" style="width: 70%;display: inline-block;">_x000D_
<span>Santanu Patra</span>_x000D_
</div>_x000D_
<div class="label" style="width: 30%;float: left;">_x000D_
<strong>D.O.B.</strong>_x000D_
</div>_x000D_
<div class="data" style="width: 70%;display: inline-block;">_x000D_
<span>17th April, 1995</span>_x000D_
</div>_x000D_
<div class="label" style="width: 30%;float: left;">_x000D_
<strong>Address</strong>_x000D_
</div>_x000D_
<div class="data" style="width: 70%;display: inline-block;">_x000D_
<span>P.S. Srijan Corporate Park, Saltlake, Sector 5, Kolkata-91</span>_x000D_
</div>_x000D_
<div class="label" style="width: 30%;float: left;">_x000D_
<strong>Contact Number</strong>_x000D_
</div>_x000D_
<div class="data" style="width: 70%;display: inline-block;">_x000D_
<span>9874563210</span>_x000D_
</div>_x000D_
<div class="label" style="width: 30%;float: left;">_x000D_
<strong>Email Id</strong>_x000D_
</div>_x000D_
<div class="data" style="width: 70%;display: inline-block;">_x000D_
<span>[email protected]</span>_x000D_
</div>_x000D_
<div class="label" style="width: 30%;float: left;">_x000D_
<strong>Parent(s) Name</strong>_x000D_
</div>_x000D_
<div class="data" style="width: 70%;display: inline-block;">_x000D_
<span>S. Patra</span><br /><span>7896541230</span>_x000D_
</div>_x000D_
<div class="label" style="width: 30%;float: left;">_x000D_
<strong>Exam Center</strong>_x000D_
</div>_x000D_
<div class="data" style="width: 70%;display: inline-block;">_x000D_
<span>Institute of Engineering & Management</span>_x000D_
</div>_x000D_
<div class="label" style="width: 30%;float: left;">_x000D_
<strong>Hall Number</strong>_x000D_
</div>_x000D_
<div class="data" style="width: 70%;display: inline-block;">_x000D_
<span>COM-32</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="sideDiv" style="width: 20%;float: left;">_x000D_
<div class="atts" style="float: left;width: 100%;">_x000D_
<div class="photo" style="width: 115px;height: 150px;float: right;">_x000D_
<img src="images/candidateImg.gif" style="width: 100%;"/>_x000D_
</div>_x000D_
<div class="sign" style="position: absolute;bottom: 0;right: 0;border-top: 1px dashed #000;left: 80%;text-align: right;">_x000D_
<small>Self Attested</small>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<button class="btn btn-info" id="cmd2">Download Token</button>
_x000D_
How about either of:
>>> df
date duration user_id
0 2013-04-01 30 0001
1 2013-04-01 15 0001
2 2013-04-01 20 0002
3 2013-04-02 15 0002
4 2013-04-02 30 0002
>>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
duration user_id
date
2013-04-01 65 2
2013-04-02 45 1
>>> df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()})
duration user_id
date
2013-04-01 65 2
2013-04-02 45 1
apt-get install postgres-xc-client
apt-get install postgres-xc
As mentioned by Karan Dua this is now possible in iOS8 using UIApplicationOpenSettingsURLString
see Apple's Documentation.
Example:
Swift 4.2
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
In Swift 3:
UIApplication.shared.open(URL(string:UIApplicationOpenSettingsURLString)!)
In Swift 2:
UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!)
In Objective-C
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
Prior to iOS 8:
You can not. As you said this has been covered many times and that pop up asking you to turn on location services is supplied by Apple and not by the App itself. That is why it is able to the open the settings application.
Here are a few related questions & articles:
is it possible to open Settings App using openURL?
Programmatically opening the settings app (iPhone)
How can I open the Settings app when the user presses a button?
iPhone: Opening Application Preferences Panel From App
Open UIPickerView by clicking on an entry in the app's preferences - How to?
Since ng-show
is an angular attribute i think, we don't need to put the evaluation flower brackets ({{}}
)..
For attributes like class
we need to encapsulate the variables with evaluation flower brackets ({{}}
).
If the column expanded only by contiguously added dates as in my case - I used just MAX function to get last date.
The final formula will be:
=DAYS360(A2; MAX(A2:A))
You are looking for the float.h
header.
Use Radium!
The following is an example from their website:
var Radium = require('radium');_x000D_
var React = require('react');_x000D_
var color = require('color');_x000D_
_x000D_
@Radium_x000D_
class Button extends React.Component {_x000D_
static propTypes = {_x000D_
kind: React.PropTypes.oneOf(['primary', 'warning']).isRequired_x000D_
};_x000D_
_x000D_
render() {_x000D_
// Radium extends the style attribute to accept an array. It will merge_x000D_
// the styles in order. We use this feature here to apply the primary_x000D_
// or warning styles depending on the value of the `kind` prop. Since its_x000D_
// all just JavaScript, you can use whatever logic you want to decide which_x000D_
// styles are applied (props, state, context, etc)._x000D_
return (_x000D_
<button_x000D_
style={[_x000D_
styles.base,_x000D_
styles[this.props.kind]_x000D_
]}>_x000D_
{this.props.children}_x000D_
</button>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
// You can create your style objects dynamically or share them for_x000D_
// every instance of the component._x000D_
var styles = {_x000D_
base: {_x000D_
color: '#fff',_x000D_
_x000D_
// Adding interactive state couldn't be easier! Add a special key to your_x000D_
// style object (:hover, :focus, :active, or @media) with the additional rules._x000D_
':hover': {_x000D_
background: color('#0074d9').lighten(0.2).hexString()_x000D_
}_x000D_
},_x000D_
_x000D_
primary: {_x000D_
background: '#0074D9'_x000D_
},_x000D_
_x000D_
warning: {_x000D_
background: '#FF4136'_x000D_
}_x000D_
};
_x000D_
Delete data that is 30 days and older
DELETE FROM Table
WHERE DateColumn < GETDATE()- 30
I had a situation where i was working with a custom component and i needed to clear the form data.
But only if the page was in 'create' form state, and if the page was not being used to edit an existing item. So I made a method.
I called this method inside a watcher on custom component file, and not the vue page that uses the custom component. If that makes sense.
The entire form $ref was only available to me on the Base Custom Component.
<!-- Custom component HTML -->
<template>
<v-form ref="form" v-model="valid" @submit.prevent>
<slot v-bind="{ formItem, formState, valid }"></slot>
</v-form>
</template>
watch: {
value() {
// Some other code here
this.clearFormDataIfNotEdit(this)
// Some other code here too
}
}
... some other stuff ....
methods: {
clearFormDataIfNotEdit(objct) {
if (objct.formstate === 'create' && objct.formItem.id === undefined) {
objct.$refs.form.reset()
}
},
}
Basically i checked to see if the form data had an ID, if it did not, and the state was on create, then call the obj.$ref.form.reset()
if i did this directly in the watcher, then it would be this.$ref.form.reset()
obvs.
But you can only call the $ref from the page which it's referenced. Which is what i wanted to call out with this answer.
You use a shebang line at the start of your script:
#!/usr/bin/env python
make the file executable:
chmod +x arbitraryname
and put it in a directory on your PATH (can be a symlink):
cd ~/bin/
ln -s ~/some/path/to/myscript/arbitraryname
All the calls to UI should be asynchronous, anything you change on the UI like updating table or changing text label should be done from main thread. using DispatchQueue.main will add your operation to the queue on the main thread.
Swift 4
DispatchQueue.main.async{
self.tableView.reloadData()
}
You can use this command to repeat your command 10 times or more
for i in {1..10}; do **your command**; done
for example
for i in {1..10}; do **speedtest**; done
Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision
How about:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("input.xml"));
NodeList nodeList = document.getElementsByTagName("Item");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue());
}
}
}
Use:
string json = "{\r\n \"LOINC_NUM\": \"10362-2\",\r\n}";
var result = JObject.Parse(json.Replace(System.Environment.NewLine, string.Empty));
A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.
A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.
(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).
The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:
You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.
In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.
This topic is very well covered in the documentation.
http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523
12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm
You can also add hash when page is loading:
location.hash = "noBack";
Then just handle location hash change to add another hash:
$(window).on('hashchange', function() {
location.hash = "noBack";
});
That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.
This solution worked well for me: http://www.apachefriends.org/f/viewtopic.php?f=17&t=50902&p=196185#p196185
Edit /opt/lampp/etc/extra/httpd-xampp.conf and adding Require all granted line at bottom of block <Directory "/opt/lampp/phpmyadmin">
to have the following code:
<Directory "/opt/lampp/phpmyadmin">
AllowOverride AuthConfig Limit
Order allow,deny
Allow from all
Require all granted
</Directory>
First navigate to below location and open it in a text editor
<TOMCAT_HOME>/conf/tomcat-users.xml
For tomcat 7, Add the following xml code somewhere between <tomcat-users>
I find the following solution.
<role rolename="manager-gui"/>
<user username="username" password="password" roles="manager-gui"/>
Now restart the tomcat server.
Enter the following command to insert data into the testlog table with some condition:
INSERT INTO TABLE testlog SELECT * FROM table1 WHERE some condition;
All the above answers are valid, but something that I don't think is mentioned is that once you add a file from that directory into the repo, you can't ignore that directory/subdirectory that contains that file (git will ignore that directive).
To ignore already added files run
$ git rm --cached
Otherwise you'll have to remove all files from the repo's target directory first - and then you can ignore that folder.
None of this worked for me as I was using a grid rather than a StackPanel.
I finally found this example: http://spin.atomicobject.com/2013/03/06/xaml-wpf-textbox-focus/
and modified it to this:
In the 'Resources' section:
<Style x:Key="FocusTextBox" TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=textBoxName, Path=IsVisible}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=textBoxName}"/>
</DataTrigger>
</Style.Triggers>
</Style>
In my grid definition:
<Grid Style="{StaticResource FocusTextBox}" />
/**
* Extension of TreeMap to provide default value getter/creator.
*
* NOTE: This class performs no null key or value checking.
*
* @author N David Brown
*
* @param <K> Key type
* @param <V> Value type
*/
public abstract class Hash<K, V> extends TreeMap<K, V> {
private static final long serialVersionUID = 1905150272531272505L;
/**
* Same as {@link #get(Object)} but first stores result of
* {@link #create(Object)} under given key if key doesn't exist.
*
* @param k
* @return
*/
public V getOrCreate(final K k) {
V v = get(k);
if (v == null) {
v = create(k);
put(k, v);
}
return v;
}
/**
* Same as {@link #get(Object)} but returns specified default value
* if key doesn't exist. Note that default value isn't automatically
* stored under the given key.
*
* @param k
* @param _default
* @return
*/
public V getDefault(final K k, final V _default) {
V v = get(k);
return v == null ? _default : v;
}
/**
* Creates a default value for the specified key.
*
* @param k
* @return
*/
abstract protected V create(final K k);
}
Example Usage:
protected class HashList extends Hash<String, ArrayList<String>> {
private static final long serialVersionUID = 6658900478219817746L;
@Override
public ArrayList<Short> create(Short key) {
return new ArrayList<Short>();
}
}
final HashList haystack = new HashList();
final String needle = "hide and";
haystack.getOrCreate(needle).add("seek")
System.out.println(haystack.get(needle).get(0));
What ever attribute is added to the button/anchor/link to disable it, bootstrap is just adding style to it and user will still be able to click it while there is still onclick event. So my simple solution is to check if it is disabled and remove/add onclick event:
if (!('#button').hasAttr('disabled'))
$('#button').attr('onclick', 'someFunction();');
else
$('#button').removeattr('onclick');
The algorithm has been designed to support arbitrary input length. I.e you can compute hashes of big files like ISO of a DVD...
If there is a limitation for the input it could come from the environment where the hash function is used. Let's say you want to compute a file and the environment has a MAX_FILE limit.
But the output string will be always the same: 32 hex chars (128 bits)!
this solution is robust even in executables
import inspect, os.path
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
You should use datetime
object, not str
.
>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'
To get the datetime object from the string, use datetime.datetime.strptime
:
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'
Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:
240p 360p 480p 720p 1080p
Resolution 426 x 240 640 x 360 854x480 1280x720 1920x1080
Video Bitrates
Maximum 700 Kbps 1000 Kbps 2000 Kbps 4000 Kbps 6000 Kbps
Recommended 400 Kbps 750 Kbps 1000 Kbps 2500 Kbps 4500 Kbps
Minimum 300 Kbps 400 Kbps 500 Kbps 1500 Kbps 3000 Kbps
It would appear as though this is the case, although the numbers dont sync up to the google table above:
// the bitrates, video width and file names for this clip
bitrates: [
{ url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
{ url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
{ url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
],
Here is a sample function: 'df.name = file` : Sixth line in the code below
def df_list():
filename_list = current_stage_files(PATH)
df_list = []
for file in filename_list:
df = pd.read_csv(PATH+file)
df.name = file
df_list.append(df)
return df_list
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
Your module name must be camelCase eg. pdfLib. I had same issue because I my module name was 'PdfLib' and after renaming it to 'pdfLib'. It worked. The issue was not in my device but in jenkins server. So, check and see if you have such modulenames
Once you have your string in a double/decimal to get it into the correct formatting for a specific locale use
double amount = 1234.95;
amount.ToString("C") // whatever the executing computer thinks is the right fomat
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ie")) // €1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("es-es")) // 1.234,95 €
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) // £1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-au")) // $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us")) // $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ca")) // $1,234.95
You could use :focus
which will remain the style as long as the user doesn't click elsewhere.
button:active {
border: 2px solid green;
}
button:focus {
border: 2px solid red;
}
Apache Server:
I spend the same, but it was because I had no quotation marks (") the asterisk in my file that provided access to the server, eg '.htaccess.':
Header add Access-Control-Allow-Origin: *
Header add Access-Control-Allow-Origin "*"
You may also have a file '.htaccess' in a folder with another '.htaccess' out, eg
/
- .htaccess
- public_html / .htaccess (problem here)
In your case instead of '*' asterisk would be the ip (http://127.0.0.1:9000
) server that you give permission to serve data.
ASP.NET:
Check that there is no 'Access-Control-Allow-Origin' duplicate in your code.
Developer Tools:
With Chrome you can verify your request headers. Press the F12 key and go to the 'Network' tab, now run the AJAX request and will appear on the list, click and give all the information is there.
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
I had a similar problem and since I couldn't find a sufficient solution, I also created a serialization library for javascript: https://github.com/wavesoft/jbb (as a matter of fact it's a bit more, since it's mainly intended for bundling resources)
It is close to Binary-JSON but it adds a couple of additional features, such as metadata for the objects being encoded and some extra optimizations like data de-duplication, cross-referencing to other bundles and structure-level compression.
However there is a catch: In order to keep the bundle size small there are no type information in the bundle. Such information are provided in a separate "profile" that describes your objects for encoding and decoding. For optimization reasons this information is given in a form of script.
But you can make your life easier using the gulp-jbb-profile
(https://github.com/wavesoft/gulp-jbb-profile) utility for generating the encodeing/decoding scripts from simple YAML object specifications like this:
# The 'Person' object has the 'age' and 'isOld'
# properties
Person:
properties:
- age
- isOld
For example you can have a look on the jbb-profile-three
profile.
When you have your profile ready, you can use JBB like this:
var JBBEncoder = require('jbb/encode');
var MyEncodeProfile = require('profile/profile-encode');
// Create a new bundle
var bundle = new JBBEncoder( 'path/to/bundle.jbb' );
// Add one or more profile(s) in order for JBB
// to understand your custom objects
bundle.addProfile(MyEncodeProfile);
// Encode your object(s) - They can be any valid
// javascript object, or objects described in
// the profiles you added previously.
var p1 = new Person(77);
bundle.encode( p1, 'person' );
var people = [
new Person(45),
new Person(77),
...
];
bundle.encode( people, 'people' );
// Close the bundle when you are done
bundle.close();
And you can read it back like this:
var JBBDecoder = require('jbb/decode');
var MyDecodeProfile = require('profile/profile-decode');
// Instantiate a new binary decoder
var binaryLoader = new JBBDecoder( 'path/to/bundle' );
// Add your decoding profile
binaryLoader.addProfile( MyDecodeProfile );
// Add one or more bundles to load
binaryLoader.add( 'bundle.jbb' );
// Load and callback when ready
binaryLoader.load(function( error, database ) {
// Your objects are in the database
// and ready to use!
var people = database['people'];
});
Just to add that there is also java.text.MessageFormat with the benefit of having numeric argument indexes.
Appending the 1st example from the documentation
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
planet, new Date(), event);
Result:
At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
A really fast way to solve this problem is to make a database link from the Oracle database to the MySQL database. You can create database links to non-Oracle databases. After you have created the database link you can retrieve your data from the MySQL database with a ... create table mydata as select * from ... statement. This is called heterogeneous connectivity. This way you don't have to do anything in your .net application to move the data.
Another way is to use ODP.NET. In ODP.NET you can use the OracleBulkCopy-class.
But I don't think that inserting 160k records in an Oracle table with System.Data.OracleClient should take 25 minutes. I think you commit too many times. And do you bind your values to the insert statement with parameters or do you concatenate your values. Binding is much faster.
There is fastcache, which is "C implementation of Python 3 functools.lru_cache. Provides speedup of 10-30x over standard library."
Same as chosen answer, just different import:
from fastcache import lru_cache
@lru_cache(maxsize=128, typed=False)
def f(a, b):
pass
Also, it comes installed in Anaconda, unlike functools which needs to be installed.
Use Jquery and wait till the source is loaded, This is how I have achieved(Used angular interval, you can use javascript setInterval method):
var addCssToIframe = function() {
if ($('#myIframe').contents().find("head") != undefined) {
$('#myIframe')
.contents()
.find("head")
.append(
'<link rel="stylesheet" href="app/css/iframe.css" type="text/css" />');
$interval.cancel(addCssInterval);
}
};
var addCssInterval = $interval(addCssToIframe, 500, 0, false);
npm install
now supports thisnpm install --save ../path/to/mymodule
For this to work mymodule
must be configured as a module with its own package.json
. See Creating NodeJS modules.
As of npm 2.0, local dependencies are supported natively. See danilopopeye's answer to a similar question. I've copied his response here as this question ranks very high in web search results.
This feature was implemented in the version 2.0.0 of npm. For example:
{ "name": "baz", "dependencies": { "bar": "file:../foo/bar" } }
Any of the following paths are also valid:
../foo/bar ~/foo/bar ./foo/bar /foo/bar
Since npm install
copies mymodule
into node_modules
, changes in mymodule
's source will not automatically be seen by the dependent project.
There are two ways to update the dependent project with
Update the version of mymodule
and then use npm update
: As you can see above, the package.json
"dependencies" entry does not include a version specifier as you would see for normal dependencies. Instead, for local dependencies, npm update
just tries to make sure the latest version is installed, as determined by mymodule
's package.json
. See chriskelly's answer to this specific problem.
Reinstall using npm install
. This will install whatever is at mymodule
's source path, even if it is older, or has an alternate branch checked out, whatever.
My case - Trying to use a Class from a swift framework in my objective c project, I got this error. Solution was to add Module (swift framework) of the class in Interface builder/ Storyboard as shown below. Nothing else
The ISO 7000 / IEC 60417 Symbol for Pause; Interruption is #5111B. See Media_Controls
Laravel min
and max
validation do not work properly with a numeric
rule validation. Instead of numeric, min and max
, Laravel provided a rule digits_between
.
$this->validate($request,[
'field_name'=>'digits_between:2,5',
]);
The easiest way would probably be to put your web resources into the assets folder then call:
webView.loadUrl("file:///android_asset/filename.html");
For Complete Communication between Java and Webview See This
Update: The assets folder is usually the following folder:
<project>/src/main/assets
This can be changed in the asset folder configuration setting in your <app>.iml
file as:
<option name=”ASSETS_FOLDER_RELATIVE_PATH” value=”/src/main/assets” />
See Article Where to place the assets folder in Android Studio
try yo write document.getElementById('id').style.visibility="hidden";
sys.exit()
raises a SystemExit
exception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit
mysqldump
will backup by default all the triggers but NOT the stored procedures/functions. There are 2 mysqldump parameters that control this behavior:
--routines
– FALSE by default--triggers
– TRUE by defaultso in mysqldump
command , add --routines
like :
mysqldump <other mysqldump options> --routines > outputfile.sql
Is JSTL's join()
, what you searched for?
<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />
In Command prompt go to project folder and execute following:
ng g s servicename
Oracle's security model is such that when executing dynamic SQL using Execute Immediate (inside the context of a PL/SQL block or procedure), the user does not have privileges to objects or commands that are granted via role membership. Your user likely has "DBA" role or something similar. You must explicitly grant "drop table" permissions to this user. The same would apply if you were trying to select from tables in another schema (such as sys or system) - you would need to grant explicit SELECT privileges on that table to this user.
You are trying to call DeckOfCards::shuffle
with a deckOfCards
parameter:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck
But the method takes a vector<Card>&
:
void deckOfCards::shuffle(vector<Card>& deck)
The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.
Error:
[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'
Paraphrased:
Hey, pal. You're trying to call a function called
shuffle
which apparently takes a single parameter of type reference-to-deckOfCards
, but there is no such function.
Error:
[Note] candidate is:
In file included from main.cpp
[Note] void deckOfCards::shuffle(std::vector&)
Paraphrased:
I mean, maybe you meant this other function called
shuffle
, but that one takes a reference-tovector<something>
.
Error:
[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'
Which I'd be happy to call if I knew how to convert from a
deckOfCards
to avector
; but I don't. So I won't.
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("Python Spark SQL basic example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
df = spark.read.csv("/home/stp/test1.csv",header=True,sep="|")
print(df.collect())
I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).
The only difference would be if you try to reassign it before the end of this very file.
For more complex DataFrames that have a Multi-Index (say "Stock" and "Date") and one wants to remove the last row for each Stock not just the last row of the last Stock, then the solution reads:
# To remove last n rows
df = df.groupby(level='Stock').apply(lambda x: x.head(-1)).reset_index(0, drop=True)
# To remove first n rows
df = df.groupby(level='Stock').apply(lambda x: x.tail(-1)).reset_index(0, drop=True)
As the groupby()
is adding an additional level to the Multi-Index we just drop it at the end using reset_index()
. The resulting df keeps the same type of Multi-Index as before the operation.
For me I forgot default
. So I wrote export class MyComponent
instead of export default class MyComponent
set -x
or set -o xtrace
expands variables and prints a little + sign before the line.
set -v
or set -o verbose
does not expand the variables before printing.
Use set +x
and set +v
to turn off the above settings.
On the first line of the script, one can put #!/bin/sh -x
(or -v
) to have the same effect as set -x
(or -v
) later in the script.
The above also works with /bin/sh
.
See the bash-hackers' wiki on set
attributes, and on debugging.
$ cat shl
#!/bin/bash
DIR=/tmp/so
ls $DIR
$ bash -x shl
+ DIR=/tmp/so
+ ls /tmp/so
$
Swift 5 Extension
This can be used as a Extension and called with: UIApplication.topSafeAreaHeight
extension UIApplication {
static var topSafeAreaHeight: CGFloat {
var topSafeAreaHeight: CGFloat = 0
if #available(iOS 11.0, *) {
let window = UIApplication.shared.windows[0]
let safeFrame = window.safeAreaLayoutGuide.layoutFrame
topSafeAreaHeight = safeFrame.minY
}
return topSafeAreaHeight
}
}
Extension of UIApplication is optional, can be an extension of UIView or whatever is preferred, or probably even better a global function.
See below link : http://www.asciitable.com/
public static char randomSeriesForThreeCharacter() {
Random r = new Random();
char random_3_Char = (char) (48 + r.nextInt(47));
return random_3_Char;
}
Now you can generate a character at one time of calling.
I use Ude that is a C# port of Mozilla Universal Charset Detector. It is easy to use and gives some really good results.
Another intuitive solution could be:
class Post
{
public $title;
public $date;
}
$posts = array();
$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';
$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';
foreach ($posts as $post) {
echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}
This question's bit old, but, there's a tricky scenario which also leads to this error:
In controller:
ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());
The above code will lead to an error in this part: .Select(a=>a.ToString())
because of the below reason:
You're passing a ViewBag.id
to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:
GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)
So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.
According to the latest updates for OpenCV 3.0 and higher, you need to change the Property Identifiers as follows in the code by Mehran:
cv2.cv.CV_CAP_PROP_POS_FRAMES
to
cv2.CAP_PROP_POS_FRAMES
and same applies to cv2.CAP_PROP_POS_FRAME_COUNT
.
Hope it helps.
Just use the name of that variable.
In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitely by typing the var
keyword before the name of the variable.
If the name of the local value has the same name as the global value, use the window
object
See this jsfiddle
x = 1;_x000D_
y = 2;_x000D_
z = 3;_x000D_
_x000D_
function a(y) {_x000D_
// y is local to the function, because it is a function parameter_x000D_
console.log('local y: should be 10:', y); // local y through function parameter_x000D_
y = 3; // will only overwrite local y, not 'global' y_x000D_
console.log('local y: should be 3:', y); // local y_x000D_
// global value could be accessed by referencing through window object_x000D_
console.log('global y: should be 2:', window.y) // global y, different from local y ()_x000D_
_x000D_
var x; // makes x a local variable_x000D_
x = 4; // only overwrites local x_x000D_
console.log('local x: should be 4:', x); // local x_x000D_
_x000D_
z = 5; // overwrites global z, because there is no local z_x000D_
console.log('local z: should be 5:', z); // local z, same as global_x000D_
console.log('global z: should be 5 5:', window.z, z) // global z, same as z, because z is not local_x000D_
}_x000D_
a(10);_x000D_
console.log('global x: should be 1:', x); // global x_x000D_
console.log('global y: should be 2:', y); // global y_x000D_
console.log('global z: should be 5:', z); // global z, overwritten in function a
_x000D_
With ES2015 there came two more keywords const
and let
, which also affect the scope of a variable (Language Specification)
If the XAMPP server
is running for the moment, stop XAMPP server.
Follow these steps to change the port number.
Open the file in following location.
[XAMPP Installation Folder]/apache/conf/httpd.conf
Open the httpd.conf
file and search for the String:
Listen 80
This is the port number used by XAMMP.
Then search for the string ServerName and update the Port Number which you entered earlier for Listen
Now save and re-start XAMPP server.
If you are using JetBrains Idea IDE (and derivatives) you can select several lines, right click for the context menu, then Git -> Show history for selection. You will see list of commits which were affecting the selected lines:
For someone who needs quick reference of C# Escape Sequences that can be used in string
literals:
\t Horizontal tab (ASCII code value: 9)
\n Line feed (ASCII code value: 10)
\r Carriage return (ASCII code value: 13)
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\x12 ASCII character in hexadecimal notation (e.g. for 0x12)
\x1234 Unicode character in hexadecimal notation (e.g. for 0x1234)
It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline
which gets adjusted to current OS settings. With .Net Core it gets really important.
For Django users:
Recently came across TypeError: Decimal('2337.00') is not JSON serializable
while JSON encoding i.e. json.dumps(data)
Solution:
# converts Decimal, Datetime, UUIDs to str for Encoding
from django.core.serializers.json import DjangoJSONEncoder
json.dumps(response.data, cls=DjangoJSONEncoder)
But, now the Decimal value will be a string, now we can explicitly set the decimal/float value parser when decoding data, using parse_float
option in json.loads
:
import decimal
data = json.loads(data, parse_float=decimal.Decimal) # default is float(num_str)
For Windows, it is quite easy to stop/kill flask server -
I think Scapy is what are you looking for.
http://www.secdev.org/projects/scapy/
you can build and send frames (packets) with it
I've never had a problem with doing it like this:
<form>
<div>
<input type="checkbox" id="cb" /> <label for="cb">Label text</label>
</div>
</form>
A subscript and referring to a stored value...
a <- 10
plot(c(0,1), c(0,1), type = 'n', ann = FALSE, xaxt = 'n', yaxt = 'n')
text(0.2, 0.6, cex = 1.5, bquote(paste('S'['f']*' = ', .(a))))
Other answers have given clear enough examples of a record referencing another record in the same table.
There are even valid use cases for a record referencing itself in the same table. For example, a point of sale system accepting many tenders may need to know which tender to use for change when the payment is not the exact value of the sale. For many tenders that's the same tender, for others that's domestic cash, for yet other tenders, no form of change is allowed.
All this can be pretty elegantly represented with a single tender attribute which is a foreign key referencing the primary key of the same table, and whose values sometimes match the respective primary key of same record. In this example, the absence of value (also known as NULL value) might be needed to represent an unrelated meaning: this tender can only be used at its full value.
Popular relational database management systems support this use case smoothly.
Take-aways:
When inserting a record, the foreign key reference is verified to be present after the insert, rather than before the insert.
When inserting multiple records with a single statement, the order in which the records are inserted matters. The constraints are checked for each record separately.
Certain other data patterns, such as those involving circular dependences on record level going through two or more tables, cannot be purely inserted at all, or at least not with all the foreign keys enabled, and they have to be established using a combination of inserts and updates (if they are truly necessary).
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
This answer is more like an addition and a slight modification to the answers above.
In some versions of Visual Studio (and possibly other compilers) there is a bug that is really annoying and doesn't make sense. So if you declare/define your swap
function like this:
friend void swap(A& first, A& second) {
std::swap(first.size, second.size);
std::swap(first.arr, second.arr);
}
... the compiler will yell at you when you call the swap
function:
This has something to do with a friend
function being called and this
object being passed as a parameter.
A way around this is to not use friend
keyword and redefine the swap
function:
void swap(A& other) {
std::swap(size, other.size);
std::swap(arr, other.arr);
}
This time, you can just call swap
and pass in other
, thus making the compiler happy:
After all, you don't need to use a friend
function to swap 2 objects. It makes just as much sense to make swap
a member function that has one other
object as a parameter.
You already have access to this
object, so passing it in as a parameter is technically redundant.
The tsc -v
command run technically reads the TypeScript compiler version within the SDK directory set within the Windows Path
variable. This doesn't necessarily reflect the latest version installed as the Path
variable is not updated with subsequent installations.
The version that VS.NET uses to compile the TypeScript is what's in the project's configuration:
<TypeScriptToolsVersion>1.5</TypeScriptToolsVersion>
To help explain this more in detail I created the following post which has the specifics on the TypeScript versions installed, and which version VS.NET uses to compile the TypeScript files.
Which Version of TypeScript is Installed and Which Version is Visual Studio Using?
I also added a feature request on Microsoft Connect to make viewing and switching the TypeScript targeted version in VS.NET easier. This isn't really a TypeScript feature request as much as it is a VS.NET IDE enhancement.
Allow switching TypeScript configured version from Project Properties IDE
I must add :
I had the same problem, it was coming from the fact that my teammate had a different version of cordova, and commited plugins on the repo with his version.
For all cordova plugins, I had to :
cordova plugin rm <plugin-name>
cordova plugin add <plugin-name>
And ask my teammate to update his cordova to match my version
I know this is an old thread, but hope it helps some one.
public static void SetRequest(string mXml)
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://dork.com/service");
webRequest.Method = "POST";
webRequest.Headers["SOURCE"] = "WinApp";
// Decide your encoding here
//webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentType = "text/xml; charset=utf-8";
// You should setContentLength
byte[] content = System.Text.Encoding.UTF8.GetBytes(mXml);
webRequest.ContentLength = content.Length;
var reqStream = await webRequest.GetRequestStreamAsync();
reqStream.Write(content, 0, content.Length);
var res = await httpRequest(webRequest);
}
For the record and Google search users, If you are a .NET Core developer, you should set the content-types manually, because their default value is null or empty:
var provider = new FileExtensionContentTypeProvider();
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider
});
What I have done was to use: html_entity_decode
, then use strip_tags
to removed them.
Turns out, when the table name is different than the model name, you have to change the annotations to:
@Entity
@Table(name = "table_name")
class WhateverNameYouWant {
...
Instead of simply using the @Entity annotation.
What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.
Please visit the website and you will get Facebook, google+ and Twitter share links http://www.sharelinkgenerator.com/
Supergeek, your non recursive function did not producte the correct result, but mine does. I believe yours does one too many additions.
private Point LocationOnClient(Control c)
{
Point retval = new Point(0, 0);
for (; c.Parent != null; c = c.Parent)
{ retval.Offset(c.Location); }
return retval;
}
I tried cleaning the project and then invalidating the cache, neither of which worked. What worked for me was to comment out all my dependencies in build.gradle (app), then sync, then uncomment the dependencies again, then sync again. Bob's your uncle.