webm format is the best solution for Chrome > 29, but it is not supported in Firefox IE and Safari, the best solution is using Flash (wmode="transparent"). but you have to forget "ios".
What about this?
{ git symbolic-ref HEAD 2> /dev/null || git rev-parse --short HEAD 2> /dev/null } | sed "s#refs/heads/##"
Another small point: If you used the import some_module as sm
syntax, then you have to re-load the module with its aliased name (sm
in this example):
>>> import some_module as sm
...
>>> import importlib
>>> importlib.reload(some_module) # raises "NameError: name 'some_module' is not defined"
>>> importlib.reload(sm) # works
Add the below lines in the log4j property file and it will shut the http logs :- log4j.logger.org.apache.http=OFF
After Php 7.1, The accepted answer won't work for all types of relationships.
Because depending of type the relationship, Eloquent will return a Collection
, a Model
or Null
. And in Php 7.1 count(null)
will throw an error
.
So, to check if the relation exist you can use:
For relationships single: For example hasOne
and belongsTo
if(!is_null($model->relation)) {
....
}
For relationships multiple: For Example: hasMany
and belongsToMany
if ($model->relation->isNotEmpty()) {
....
}
You can try this:
NSLog(@"%@", NSStringFromCGPoint(cgPoint));
There are a number of functions provided by UIKit that convert the various CG structs into NSString
s. The reason it doesn't work is because %@
signifies an object. A CGPoint
is a C struct (and so are CGRect
s and CGSize
s).
Check RRViewControllerExtension, which is dedicated on UINavigation bar appearance management.
with RRViewControllerExtension in your project, you just need to override
-(BOOL)prefersNavigationBarTransparent;
in you viewcontroller.
I'm surprised no one has suggested this variation:
SELECT SUM(c)
FROM (
SELECT COUNT(*) AS c FROM foo1 WHERE ID = '00123244552000258'
UNION ALL
SELECT COUNT(*) FROM foo2 WHERE ID = '00123244552000258'
UNION ALL
SELECT COUNT(*) FROM foo3 WHERE ID = '00123244552000258'
);
from this wiki : https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin
for latin letters, I use
/^[A-zÀ-ÖØ-öø-ÿ]+$/
it avoids hyphens and specials chars
I am posting a way to use _netrc
to download materials from the site www.course.com.
If someone is going to use the coursera-dl to download the open-class materials on www.coursera.com, and on the Windows OS someone wants to use a file like ".netrc" which is in like-Unix OS to add the option -n
instead of -U <username> -P <password>
for convenience. He/she can do it like this:
Check the home path on Windows OS: setx HOME %USERPROFILE%
(refer to VonC's answer). It will save the HOME
environment variable as C:\Users\"username"
.
Locate into the directory C:\Users\"username"
and create a file name _netrc
.NOTE: there is NOT any suffix.
the content is like: machine coursera-dl login <user> password <pass>
Use a command like coursera-dl -n --path PATH <course name>
to download the class materials. More coursera-dl options details for this page.
To check with current branch:
git diff -- projects/components/some.component.ts ... origin
git diff -- projects/components/some.component.html ... origin
To check with some other branch say staging:
git diff -- projects/components/some.component.ts ... origin/staging
git diff -- projects/components/some.component.html ... origin/staging
Let's not forget Jerry, its jQuery in java: a fast and concise Java Library that simplifies HTML document parsing, traversing and manipulating; includes usage of css3 selectors.
Example:
Jerry doc = jerry(html);
doc.$("div#jodd p.neat").css("color", "red").addClass("ohmy");
Example:
doc.form("#myform", new JerryFormHandler() {
public void onForm(Jerry form, Map<String, String[]> parameters) {
// process form and parameters
}
});
Of course, these are just some quick examples to get the feeling how it all looks like.
Late to the party:
Below is a solution that also deals with y < 0
as best as it can.
intmax_t
for maximum range. There is no provision for answers that do not fit in intmax_t
. powjii(0, 0) --> 1
which is a common result for this case.pow(0,negative)
, another undefined result, returns INTMAX_MAX
intmax_t powjii(int x, int y) {
if (y < 0) {
switch (x) {
case 0:
return INTMAX_MAX;
case 1:
return 1;
case -1:
return y % 2 ? -1 : 1;
}
return 0;
}
intmax_t z = 1;
intmax_t base = x;
for (;;) {
if (y % 2) {
z *= base;
}
y /= 2;
if (y == 0) {
break;
}
base *= base;
}
return z;
}
This code uses a forever loop for(;;)
to avoid the final base *= base
common in other looped solutions. That multiplication is 1) not needed and 2) could be int*int
overflow which is UB.
It is very simple to adding an image into project and view the image. First create a folder into in your project which can contain any type of images.
Then Right click on Project ->>
Go to Build Path ->>
configure Build Path ->>
add Class folder ->>
choose your folder (which you just created for store the images) under the project name.
class Surface extends JPanel {
private BufferedImage slate;
private BufferedImage java;
private BufferedImage pane;
private TexturePaint slatetp;
private TexturePaint javatp;
private TexturePaint panetp;
public Surface() {
loadImages();
}
private void loadImages() {
try {
slate = ImageIO.read(new File("images\\slate.png"));
java = ImageIO.read(new File("images\\java.png"));
pane = ImageIO.read(new File("images\\pane.png"));
} catch (IOException ex) {
Logger.`enter code here`getLogger(Surface.class.getName()).log(
Level.SEVERE, null, ex);
}
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));
javatp = new TexturePaint(java, new Rectangle(0, 0, 90, 60));
panetp = new TexturePaint(pane, new Rectangle(0, 0, 90, 60));
g2d.setPaint(slatetp);
g2d.fillRect(10, 15, 90, 60);
g2d.setPaint(javatp);
g2d.fillRect(130, 15, 90, 60);
g2d.setPaint(panetp);
g2d.fillRect(250, 15, 90, 60);
g2d.dispose();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
public class TexturesEx extends JFrame {
public TexturesEx() {
initUI();
}
private void initUI() {
add(new Surface());
setTitle("Textures");
setSize(360, 120);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
TexturesEx ex = new TexturesEx();
ex.setVisible(true);
}
});
}
}
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
No formulas required. This works on as many columns as you need, but will only compare columns in the same worksheet:
NOTE: remove any duplicates from the individual columns first!
Duplicates are now highlighted in red
You need to move the unique_ptr
:
vec.push_back(std::move(ptr2x));
unique_ptr
guarantees that a single unique_ptr
container has ownership of the held pointer. This means that you can't make copies of a unique_ptr
(because then two unique_ptr
s would have ownership), so you can only move it.
Note, however, that your current use of unique_ptr
is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:
std::unique_ptr<int> ptr(new int(1));
In C++14 we have an even better way to do so:
make_unique<int>(5);
This code will always fail.
As written, it says: "Look for a property named "Employee" on my DataContext property, and set it to the DataContext property". Clearly that isn't right.
To get your code to work, as is, change your window declaration to:
<Window x:Class="SampleApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:Employee/>
</Window.DataContext>
This declares a new XAML namespace (local) and sets the DataContext to an instance of the Employee class. This will cause your bindings to display the default data (from your constructor).
However, it is highly unlikely this is actually what you want. Instead, you should have a new class (call it MainViewModel) with an Employee
property that you then bind to, like this:
public class MainViewModel
{
public Employee MyEmployee { get; set; } //In reality this should utilize INotifyPropertyChanged!
}
Now your XAML becomes:
<Window x:Class="SampleApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
...
<TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding MyEmployee.EmpID}" />
<TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding MyEmployee.EmpName}" />
Now you can add other properties (of other types, names), etc. For more information, see Implementing the Model-View-ViewModel Pattern
If you had the problem, opened SDK manager, installed the requested updates, returned to Android Studio and had the problem again, IT IS RECOMMENDED TO RESTART ANDROID STUDIO befor trying anything else.
Gradle will run automatically and chances are that your problem will be over. You will very possibly be told install the appropriate SDK TOOLS package, which is found in your SDK MANAGER under the second tab (sdk's are not the same as sdk tools, they are complementary packages).
You don't even need to hunt the tools package, if you click on the link under the error message, Android Studio should call SDK Manager to install the package automatically.
Restart Android Studio again and you should be up and running much faster than if you attempted workarounds.
RULE OF THUMB> restart your application before messing with options and configurations.
I always return multiple values by using a combination of list()
and array()
s:
function DecideStuffToReturn() {
$IsValid = true;
$AnswerToLife = 42;
// Build the return array.
return array($IsValid, $AnswerToLife);
}
// Part out the return array in to multiple variables.
list($IsValid, $AnswerToLife) = DecideStuffToReturn();
You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.
See list()
for more information.
Use %0D%0A
for a line break in your body
Example (Demo):
<a href="mailto:[email protected]?subject=Suggestions&body=name:%0D%0Aemail:">test</a>?
^^^^^^
On your own system, try
install.packages("foo", dependencies=...)
with the dependencies=
argument is documented as
dependencies: logical indicating to also install uninstalled packages
which these packages depend on/link to/import/suggest (and so
on recursively). Not used if ‘repos = NULL’. Can also be a
character vector, a subset of ‘c("Depends", "Imports",
"LinkingTo", "Suggests", "Enhances")’.
Only supported if ‘lib’ is of length one (or missing), so it
is unambiguous where to install the dependent packages. If
this is not the case it is ignored, with a warning.
The default, ‘NA’, means ‘c("Depends", "Imports",
"LinkingTo")’.
‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
"Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
‘c("Depends", "Imports", "LinkingTo")’ for added
dependencies: this installs all the packages needed to run
‘pkgs’, their examples, tests and vignettes (if the package
author specified them correctly).
so you probably want a value TRUE
.
In your package, list what is needed in Depends:
, see the
Writing R Extensions manual which is pretty clear on this.
This works for me.
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then this command with sudo:
python3.7 get-pip.py
Based on this instruction.
A YAML sequence is an array. So this is the right way to express it:
key:
- string1
- string2
- string3
- string4
- string5
- string6
That's identical in meaning to:
key: ['string1', 'string2', 'string3', 'string4', 'string5', 'string6']
It's also legal to split a single-line array over several lines:
key: ['string1', 'string2', 'string3',
'string4', 'string5',
'string6']
and even have multi-line strings in single-line arrays:
key: ['string1', 'long
string', 'string3', 'string4', 'string5', 'string6']
declare @data as varchar(50)
set @data='ciao335'
--get text
Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1) ---->>ciao
--get numeric
Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) ) ---->>335
Update: the official type-definitions for React have been including event types as generic types for some time now, so you now have full compile-time checking, and this answer is obsolete.
Is it possible to retrieve the value in a type-safe manner without casting to any?
Yes. If you are certain about the element your handler is attached to, you can do:
<select onChange={ e => this.selectChangeHandler(e) }>
...
</select>
private selectChangeHandler(e: React.FormEvent)
{
var target = e.target as HTMLSelectElement;
var intval: number = target.value; // Error: 'string' not assignable to 'number'
}
The TypeScript compiler will allow this type-assertion, because an HTMLSelectElement is an EventTarget. After that, it should be type-safe, because you know that e.target is an HTMLSelectElement, because you just attached your event handler to it.
However, to guarantee type-safety (which, in this case, is relevant when refactoring), it is also needed to check the actual runtime-type:
if (!(target instanceof HTMLSelectElement))
{
throw new TypeError("Expected a HTMLSelectElement.");
}
It is very simple.. Here you go !!
import gzip
#path_to_file_to_be_extracted
ip = sample.gzip
#output file to be filled
op = open("output_file","w")
with gzip.open(ip,"rb") as ip_byte:
op.write(ip_byte.read().decode("utf-8")
wf.close()
Try this. I set the blue box to float right, gave left and right a fixed height, and added a white border on the right of the left div. Also added rounded corners to more match your example (These won't work in ie 8 or less). I also took out the position: relative. You don't need it. Block level elements are set to position relative by default.
See it here: http://jsfiddle.net/ZSgLJ/
#left {
float: left;
width: 44%;
margin: 0;
padding: 0;
border-right: 1px solid white;
height:400px;
}
#right {
position: relative;
float: right;
width: 49%;
margin: 0;
padding: 0;
height:400px;
}
#blue_box {
background-color:blue;
border-radius: 10px;
-moz-border-radius:10px;
-webkit-border-radius: 10px;
width: 45%;
min-width: 400px;
max-width: 600px;
padding: 2%;
float: right;
}
How do you send the message?
The classes in the System.Net.Mail
namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials
property.
UPDATE - I do not have Total DNS enabled at GoDaddy because the domain is hosted at DiscountASP. As such, I could not add an A Record and that is why GoDaddy was only offering to forward my subdomain to a different site. I finally realized that I had to go to DiscountASP to add the A Record to point to DreamHost. Now waiting to see if it all works!
Of course, use the stinkin' IP! I'm not sure why that wasn't registering for me. I guess their helper text example of pointing to another url was throwing me off.
Thanks for both of the replies. I 'got it' as soon as I read Bryant's response which was first but Saif kicked it up a notch and added a little more detail.
Thanks!
The problem here is the line 292 (Using Python 3.4.3 here) in $python_install_prefix/Lib/distutils/msvc9compiler.py
which says:
VERSION = get_build_version()
This only checks for the MSVC version that your python was built with. Just replacing this line with your actual Visual Studio version, eg. 12.0
for MSVC2013
VERSION = 12.0
will fix the issue.
UPDATE: Turns out that there is a good reason why this version is hardcoded. MSVC C runtime is not required to be compatible between major versions. Hence when you use a different VS version you might run into runtime problems. So I advise to use VS 2008 (for Python 2.6 up to 3.2) and VS2010 for (Python 3.3 and later) until this issue is sorted out.
Binary compatibility will arrive with VS 2015 (see here) along with Python 3.5 .
For Python 2.7 users Microsoft released a special Microsoft Visual C++ Compiler for Python 2.7 which can be used without installing the whole VS 2008.
This should help clear up any questions you may have: C# literals
Here is a table from the linked content:
Regular literal Verbatim literal Resulting string "Hello"
@"Hello"
Hello
"Backslash: \\"
@"Backslash: \"
Backslash: \
"Quote: \""
@"Quote: """
Quote: "
"CRLF:\r\nPost CRLF"
@"CRLF:
Post CRLF"CRLF:
Post CRLF
For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:
@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);
The simple solution is to cast CLOB to BLOB and then request length of BLOB !
The problem is that Oracle doesn't have a function that cast CLOB to BLOB, but we can simply define a function to do that
create or replace
FUNCTION clob2blob (p_in clob) RETURN blob IS
v_blob blob;
v_desc_offset PLS_INTEGER := 1;
v_src_offset PLS_INTEGER := 1;
v_lang PLS_INTEGER := 0;
v_warning PLS_INTEGER := 0;
BEGIN
dbms_lob.createtemporary(v_blob,TRUE);
dbms_lob.converttoblob
( v_blob
, p_in
, dbms_lob.getlength(p_in)
, v_desc_offset
, v_src_offset
, dbms_lob.default_csid
, v_lang
, v_warning
);
RETURN v_blob;
END;
The SQL command to use to obtain number of bytes is
SELECT length(clob2blob(fieldname)) as nr_bytes
or
SELECT dbms_lob.getlength(clob2blob(fieldname)) as nr_bytes
I have tested this on Oracle 10g without using Unicode(UTF-8). But I think that this solution must be correct using Unicode(UTF-8) Oracle instance :-)
I want render thanks to Nashev that has posted a solution to convert clob to blob How convert CLOB to BLOB in Oracle? and to this post written in german (the code is in PL/SQL) 13ter.info.blog that give additionally a function to convert blob to clob !
Can somebody test the 2 commands in Unicode(UTF-8) CLOB so I'm sure that this works with Unicode ?
It doesn't sound like you're working with a list of lists, so I'll keep this short. You want to use pop since it will remove elements not elements that are lists, you should use del for that. To call the last element in python it's "-1"
>>> test = ['item1', 'item2']
>>> test.pop(-1)
'item2'
>>> test
['item1']
I just put one simple declaration of the app
var app = angular.module("app", ["xeditable"]);
Then I built one service and two controllers
For each controller I had a line in the JS
app.controller('EditableRowCtrl', function ($scope, CRUD_OperService) {
And in the HTML I declared the app scope in a surrounding div
<div ng-app="app">
and each controller scope separately in their own surrounding div (within the app div)
<div ng-controller="EditableRowCtrl">
This worked fine
I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect
<?php
$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion = $_POST['seccion'];
$precio = $_POST['precio'];
$fecha = $_POST['fecha'];
$importado = $_POST['importado'];
$paisdeorigen = $_POST['paisdeorigen'];
try {
$server = 'mysql: host=localhost; dbname=usuarios';
$user = 'root';
$pass = '';
$base = new PDO($server, $user, $pass);
$base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$base->query("SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'");
$base->exec("SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'");
$sql = "
INSERT INTO productos
(CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
VALUES
(:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
$result = $base->prepare($sql);
// se pasan por parametros aqui
$result->bindParam(':c_art', $codigoarticulo);
$result->bindParam(':n_art', $nombrearticulo);
$result->bindParam(':sec', $seccion);
$result->bindParam(':pre', $precio);
$result->bindParam(':fecha_art', $fecha);
$result->bindParam(':import', $importado);
$result->bindParam(':p_orig', $paisdeorigen);
$result->execute();
echo 'Articulo agregado';
} catch (Exception $e) {
echo 'Error';
echo $e->getMessage();
} finally {
}
?>
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
Seems you need to create user for your database and grant privileges for created user
--> create user for Data base
CREATE USER <'username'>@'%'IDENTIFIED BY <'password'>;
ex - CREATE USER 'root'@'%'IDENTIFIED BY 'root';
--> Grant Privileges
FLUSH PRIVILEGES;
GRANT ALL PRIVILEGES ON <db name>.* TO '<username>'@'%';
ex- GRANT ALL PRIVILEGES ON mydb.* TO 'root'@'%';
An old thread, but it may help someone like me. I resolved the issue by setting up SMTP server value to a legitimate value in PHP.ini
You can have a responsive canvas in 3 short and simple steps:
Remove the width
and height
attributes from your <canvas>
.
<canvas id="responsive-canvas"></canvas>
Using CSS, set the width
of your canvas to 100%
.
#responsive-canvas {
width: 100%;
}
Using JavaScript, set the height to some ratio of the width.
var canvas = document.getElementById('responsive-canvas');
var heightRatio = 1.5;
canvas.height = canvas.width * heightRatio;
Maybe not very elegant, but it does the job:
exec(open("script.py").read())
function handleFileSelect(evt) {_x000D_
var files = evt.target.files;_x000D_
_x000D_
// Loop through the FileList and render image files as thumbnails._x000D_
for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
// Only process image files._x000D_
if (!f.type.match('image.*')) {_x000D_
continue;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
_x000D_
// Closure to capture the file information._x000D_
reader.onload = (function(theFile) {_x000D_
return function(e) {_x000D_
// Render thumbnail._x000D_
var span = document.createElement('span');_x000D_
span.innerHTML = _x000D_
[_x000D_
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
e.target.result,_x000D_
'" title="', escape(theFile.name), _x000D_
'"/>'_x000D_
].join('');_x000D_
_x000D_
document.getElementById('list').insertBefore(span, null);_x000D_
};_x000D_
})(f);_x000D_
_x000D_
// Read in the image file as a data URL._x000D_
reader.readAsDataURL(f);_x000D_
}_x000D_
}_x000D_
_x000D_
document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
Sometimes these warnings occur when it isn't something we've done, but something we've forgotten to do!
I encountered this warning when I installed the dotenv package with npm, but was interrupted before I got around to adding the require('dotenv').load() statement at the beginning of my app. When I returned to the project, I started getting the "Possible EventEmitter memory leak detected" warnings.
I assumed the problem was from something I had done, not something I had not done!
Once I discovered my oversight and added the require statement, the memory leak warning cleared.
This snippet is straight from Stroustrup's The C++ Programming Language (4th Edition), §40.7; it requires C++11:
#include <functional>
#include <random>
class Rand_double
{
public:
Rand_double(double low, double high)
:r(std::bind(std::uniform_real_distribution<>(low,high),std::default_random_engine())){}
double operator()(){ return r(); }
private:
std::function<double()> r;
};
#include <iostream>
int main() {
// create the random number generator:
Rand_double rd{0,0.5};
// print 10 random number between 0 and 0.5
for (int i=0;i<10;++i){
std::cout << rd() << ' ';
}
return 0;
}
If you're using Devise, please note that
For Rails 5,
protect_from_forgery
is no longer prepended to thebefore_action
chain, so if you have setauthenticate_user
beforeprotect_from_forgery
, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or useprotect_from_forgery prepend: true
.
For me I tried following 2 steps which sadly did not work :
Instead, I tried to solve keychain certificate related another issue given here This certificate has an invalid issuer Apple Push Services
This certificate has an invalid issuer
Now go to xcode app. target ? Build Setting ? Provisioning Profile . Select value from 'automatic' to appropriate Provisioning profile . Bingo!!! profile mismatch issue is solved.
If it's a string that you trust meaning that you have checked it before hand then the following would also work.
$date = new DateTime('2015-03-27');
Where do these characters occur? Do you see them if you examine the XML data in, say, notepad? Or do you see them when examining the XML data in the debugger. If it is the latter, they are only escape characters for the "
characters, and so part of the actual XML data.
public static T DeserializeFromXml<T>(string xml)
{
T result;
XmlSerializerFactory serializerFactory = new XmlSerializerFactory();
XmlSerializer serializer =serializerFactory.CreateSerializer(typeof(T));
using (StringReader sr3 = new StringReader(xml))
{
XmlReaderSettings settings = new XmlReaderSettings()
{
CheckCharacters = false // default value is true;
};
using (XmlReader xr3 = XmlTextReader.Create(sr3, settings))
{
result = (T)serializer.Deserialize(xr3);
}
}
return result;
}
Your solution is ok. only try it in this way:
files=$(grep -rl oldstr path) && echo $files | xargs sed....
so execute the xargs
only when grep return 0
, e.g. when found the string in some files.
MySql Connector/NET also includes a stored procedure debugger integrated in visual studio as of version 6.6, You can get the installer and the source here: http://dev.mysql.com/downloads/connector/net/
Some documentation / screenshots: https://dev.mysql.com/doc/visual-studio/en/visual-studio-debugger.html
You can follow the annoucements here: http://forums.mysql.com/read.php?38,561817,561817#msg-561817
UPDATE: The MySql for Visual Studio was split from Connector/NET into a separate product, you can pick it (including the debugger) from here https://dev.mysql.com/downloads/windows/visualstudio/1.2.html (still free & open source).
DISCLAIMER: I was the developer who authored the Stored procedures debugger engine for MySQL for Visual Studio product.
If you have an empty table the Export method won't work. As a workaround. I used the Table View of Oracle SQL Developer. and clicked on Columns. Sorted by Nullable so NO was on top. And then selected these non nullable values using shift + select for the range.
This allowed me to do one base insert. So that Export could prepare a proper all columns insert.
I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.
scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop
The username@remotecomputer
is the same string you used with ssh initially.
This is taken from snippets.dzone.com:
Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost '\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
in windows, simply adding shell: true
option solved my problem:
incorrect:
const { spawn } = require('child_process');
const child = spawn('dir');
correct:
const { spawn } = require('child_process');
const child = spawn('dir', [], {shell: true});
Here's a solution with flexbox
for images with variable width and height:
.container {
display: flex;
flex-wrap: no-wrap;
overflow-x: auto;
margin: 20px;
}
img {
flex: 0 0 auto;
width: auto;
height: 100px;
max-width: 100%;
margin-right: 10px;
}
Example: JsFiddle
In file php.ini you should try this for all errors:
error_reporting = off
Here is an answer coming right from the libc6
!
Taking a look at /usr/include/x86_64-linux-gnu/bits/byteswap.h
, I found the trick you were looking for.
A few critics of previous solutions:
auto
keyword, that's fine, but feel free to use the known/expected type instead.The trick is to use both the (expr,expr)
construct and a {}
scope:
#define MACRO(X,Y) \
( \
{ \
register int __x = static_cast<int>(X), __y = static_cast<int>(Y); \
std::cout << "1st arg is:" << __x << std::endl; \
std::cout << "2nd arg is:" << __y << std::endl; \
std::cout << "Sum is:" << (__x + __y) << std::endl; \
__x + __y; \
} \
)
Note the use of the register
keyword, it's only a hint to the compiler.
The X
and Y
macro parameters are (already) surrounded in parenthesis and casted to an expected type.
This solution works properly with pre- and post-increment as parameters are evaluated only once.
For the example purpose, even though not requested, I added the __x + __y;
statement, which is the way to make the whole bloc to be evaluated as that precise expression.
It's safer to use void();
if you want to make sure the macro won't evaluate to an expression, thus being illegal where an rvalue
is expected.
However, the solution is not ISO C++ compliant as will complain g++ -pedantic
:
warning: ISO C++ forbids braced-groups within expressions [-pedantic]
In order to give some rest to g++
, use (__extension__ OLD_WHOLE_MACRO_CONTENT_HERE)
so that the new definition reads:
#define MACRO(X,Y) \
(__extension__ ( \
{ \
register int __x = static_cast<int>(X), __y = static_cast<int>(Y); \
std::cout << "1st arg is:" << __x << std::endl; \
std::cout << "2nd arg is:" << __y << std::endl; \
std::cout << "Sum is:" << (__x + __y) << std::endl; \
__x + __y; \
} \
))
In order to improve my solution even a bit more, let's use the __typeof__
keyword, as seen in MIN and MAX in C:
#define MACRO(X,Y) \
(__extension__ ( \
{ \
__typeof__(X) __x = (X); \
__typeof__(Y) __y = (Y); \
std::cout << "1st arg is:" << __x << std::endl; \
std::cout << "2nd arg is:" << __y << std::endl; \
std::cout << "Sum is:" << (__x + __y) << std::endl; \
__x + __y; \
} \
))
Now the compiler will determine the appropriate type. This too is a gcc
extension.
Note the removal of the register
keyword, as it would the following warning when used with a class type:
warning: address requested for ‘__x’, which is declared ‘register’ [-Wextra]
If the array element is not integer you can use something like below :
$skus = array('LDRES10','LDRES12','LDRES11'); //sample data
if(!empty($skus)){
$sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "
}
$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');
while($row = mysql_fetch_array($sql_results))
{
$subArray[location_id]=$row['location']; //location_id is key and $row['location'] is value which come fron database.
$subArray[x]=$row['x'];
$subArray[y]=$row['y'];
$array[] = $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';
You don't need to pass both arguments when performing a remount. You can simply pass the mount point (here /system). And /system is universal amongst Android devices.
Another solution would be to make use of a server-side scripting language and to simply include json-data inline. Here's an example that uses PHP:
<script id="data" type="application/json"><?php include('stuff.json'); ?></script>
<script>
var jsonData = JSON.parse(document.getElementById('data').textContent)
</script>
The above example uses an extra script tag with type application/json
. An even simpler solution is to include the JSON directly into the JavaScript:
<script>var jsonData = <?php include('stuff.json');?>;</script>
The advantage of the solution with the extra tag is that JavaScript code and JSON data are kept separated from each other.
ObjectPath is a library that provides ability to query JSON and nested structures of dicts and lists. For example, you can search for all attributes called "foo" regardless how deep they are by using $..foo
.
While the documentation focuses on the command line interface, you can perform the queries programmatically by using the package's Python internals. The example below assumes you've already loaded the data into Python data structures (dicts & lists). If you're starting with a JSON file or string you just need to use load
or loads
from the json module first.
import objectpath
data = [
{'foo': 1, 'bar': 'a'},
{'foo': 2, 'bar': 'b'},
{'NoFooHere': 2, 'bar': 'c'},
{'foo': 3, 'bar': 'd'},
]
tree_obj = objectpath.Tree(data)
tuple(tree_obj.execute('$..foo'))
# returns: (1, 2, 3)
Notice that it just skipped elements that lacked a "foo" attribute, such as the third item in the list. You can also do much more complex queries, which makes ObjectPath handy for deeply nested structures (e.g. finding where x has y that has z: $.x.y.z
). I refer you to the documentation and tutorial for more information.
here is easier way.
- name: create dir
command: mkdir -p dir dir/a dir/b
There is: Path.ChangeExtension
method. E.g.:
var result = Path.ChangeExtension(myffile, ".jpg");
In the case if you also want to physically change the extension, you could use File.Move
method:
File.Move(myffile, Path.ChangeExtension(myffile, ".jpg"));
Just install PowerShell 7 (go here, and scroll and expand the assets section). This release has implemented the pipeline chain operators.
You can use below codes for get different parameters of Current URL
alert("document.URL : "+document.URL);
alert("document.location.href : "+document.location.href);
alert("document.location.origin : "+document.location.origin);
alert("document.location.hostname : "+document.location.hostname);
alert("document.location.host : "+document.location.host);
alert("document.location.pathname : "+document.location.pathname);
The only thing that assisted me was to set margin:0px
on the topmost <div class="row">
in my html DOM.
This again wasn't the most appealing way to solve the issue, but as it is only in one place I put it inline.
As an fyi the container-fluid and apparent bootstrap fixes only introduced an increased whitespace on either side of the visible page... :( Although I came across my solution by reading through the back and forth on the github issue - so worthwhile reading.
Following this question, in Angular 7.2 you can pass data from parent to child using the history state. So you can do something like
Send:
this.router.navigate(['action-selection'], { state: { example: 'bar' } });
Retrieve:
constructor(private router: Router) { console.log(this.router.getCurrentNavigation().extras.state.example); }
But be careful to be consistent. For example, suppose you want to display a list on a left side bar and the details of the selected item on the right by using a router-outlet. Something like:
Item 1 (x) | ..............................................
Item 2 (x) | ......Selected Item Details.......
Item 3 (x) | ..............................................
Item 4 (x) | ..............................................
Now, suppose you have already clicked some items. Clicking the browsers back buttons will show the details from the previous item. But what if, meanwhile, you have clicked the (x) and delete from your list that item? Then performing the back click, will show you the details of a deleted item.
I've just been trying to figure out how to do this and couldn't find a good guide online but eventually figured it out. As Steve Pomeroy suggested, you do have to do something more involved. In order to get the outlined text effect, you draw the text twice: once with a thick outline and then the second time we draw the main text over the outline. But, the task is made easier because you can very easily adapt one of the code samples provided with the SDK, namely the one under this name in your SDK directory: "/samples/android-/ApiDemos/src/com/example/android/apis/view/LabelView.java". Which can also found on the Android developer website here.
Depending on what you're doing, it's very easy to see you will only need to make minor modifications to that code, such as changing it to extend from TextView, etc. Before I discovered this sample I forgot to override onMeasure() (which you must do in addition to overriding onDraw() as is mentioned in the "Building Custom Components" guide on the Android Developer website), which is part of why I was having trouble.
Once you've done that, you can do what I did:
public class TextViewOutline extends TextView {
private Paint mTextPaint;
private Paint mTextPaintOutline; //add another paint attribute for your outline
...
//modify initTextViewOutline to setup the outline style
private void initTextViewOutline() {
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(16);
mTextPaint.setColor(0xFF000000);
mTextPaint.setStyle(Paint.Style.FILL);
mTextPaintOutline = new Paint();
mTextPaintOutline.setAntiAlias(true);
mTextPaintOutline.setTextSize(16);
mTextPaintOutline.setColor(0xFF000000);
mTextPaintOutline.setStyle(Paint.Style.STROKE);
mTextPaintOutline.setStrokeWidth(4);
setPadding(3, 3, 3, 3);
}
...
//make sure to update other methods you've overridden to handle your new paint object
...
//and finally draw the text, mAscent refers to a member attribute which had
//a value assigned to it in the measureHeight and Width methods
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent,
mTextPaintOutline);
canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, mTextPaint);
}
So, in order to get the outlined text effect, you draw the text twice: once with a thick outline and then the second time we draw the main text over the outline.
Just use like this
$("#sample_id").css("width", "");
$("#sample_id").css("height", "");
Try grep -E for extended regular expression support
Also take a look at:
I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.
The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.
A clean and flexible solution in MS SQL Server 2005/2008 is to create a CLR Agregate function.
You'll find quite a few articles (with code) on google.
It looks like this article walks you through the whole process using C#.
Since nobody posted the modern C++ approach yet,
#include <iostream>
#include <random>
int main()
{
std::random_device rd; // obtain a random number from hardware
std::mt19937 gen(rd()); // seed the generator
std::uniform_int_distribution<> distr(25, 63); // define the range
for(int n=0; n<40; ++n)
std::cout << distr(gen) << ' '; // generate numbers
}
My use case is simpler, and fits simply your title but not your further detail.
That is, I want to install a new package which is not yet in my composer.json
without updating all the other packages.
The solution here is composer require x/y
The biggest disadvantage of Text
(together with NText
and Image
) is that it will be removed in a future version of SQL Server, as by the documentation. That will effectively make your schema harder to upgrade when that version of SQL Server will be released.
If you don't care about this question being specifically about a tableview, and you'd just like to center one view on top of another view here's to do it:
let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: parentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
parentView.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: parentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
parentView.addConstraint(verticalConstraint)
select column_name, count(column_name)
from table_name
group by column_name
having count (column_name) > 1;
This is how it worked for me:
Make sure composer is installed without no errors.
Open "System Properties" on windows and go to the "Advanced" tab. (You can just press the windows button on your keyboard and type in "Edit the system environment variables`
"Environment variables"
Under "System variables" Edit "PATH"
Click on "New".
Type in: C:\ProgramData\ComposerSetup\bin\composer.phar
Close all folders & CMDs + restart you WAMP server.
Go to whatever directory you want to install a package in and type in
composer.phar create-project slim/slim-skeleton
for example.
Here's an alternate solution that actually adds your certificate to the built in list of default certificates: Trusting all certificates using HttpClient over HTTPS
However, it will only work for your application. There's no way to programmatically do it for all applications on a user's device, since that would be a security risk.
I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:
We can enable TCP/IP protocol with WMI:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocol " _
& "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")
if tcpProtocols.Count = 1 then
' set tcpProtocol = tcpProtocols(0)
' I wish this worked, but unfortunately
' there's no int-indexed Item property in this type
' Doing this instead
for each tcpProtocol in tcpProtocols
dim setEnableResult
setEnableResult = tcpProtocol.SetEnable()
if setEnableResult <> 0 then
Wscript.Echo "Failed!"
end if
next
end if
I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)
We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456
:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocolProperty " _
& "where InstanceName='SQLEXPRESS' and " _
& "ProtocolName='Tcp' and IPAddressName='IPAll'")
for each tcpProperty in tcpProperties
dim setValueResult, requestedValue
if tcpProperty.PropertyName = "TcpPort" then
requestedValue = "3456"
elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
requestedValue = ""
end if
setValueResult = tcpProperty.SetStringValue(requestedValue)
if setValueResult = 0 then
Wscript.Echo "" & tcpProperty.PropertyName & " set."
else
Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
end if
next
Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.
Just a reminder that when working with WMI, WBEMTest.exe is your best friend!
I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:
Use LoginMode
property of Microsoft.SqlServer.Management.Smo.Server
class, as described here.
Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS
, so for my SQL Server 2008 R2 Express instance the right registry key was
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer
.
You got this one covered.
Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.
SQLCMD -U sa -P newPassword -S 192.168.0.120,3456
Please let me know if this works for you (fingers crossed!).
Before you begin, if you are uncomfortable with a command line, you can do all the following steps using SourceTree, GitExtension, GitHub Desktop, or your favorite tool.
To solve the issue, you might have two scenarios:
1) Fix only remote repository branch which is behind commit
Example: Both branches are on the remote side
ahead === Master branch
behind === Develop branch
Solution:
Clone the repository to the local workspace: this will give you the Master branch which is ahead with commit
git clone repositoryUrl
Create a branch with Develop name and checkout to that branch locally
git checkout -b DevelopBranchName // this command creates and checkout the branch
Pull from the remote Develop branch. Conflict might occur. if so, fix the conflict and commit the changes.
git pull origin DevelopBranchName
Merge the local Develop branch with the remote Develop branch
git merge origin develop
Push the merged branch to the remote Develop branch
git push origin develop
2) Local Master branch is behind the remote Master branch
This means every locally created branch is behind.
Before preceding, you have to commit or stash all the changes you made on the branch that is behind commits.
Solution:
Checkout your local Master branch
git checkout master
Pull from remote Master branch
git pull origin master
Now your local Master is in sync with the remote Branch but other local branches, that branched from the local Master branch, are not in sync with your local Master branch because of the above command. To fix that:
Checkout the branch that is behind your local Master branch
git checkout BranchNameBehindCommit
Merge with the local Master branch
git merge master // Now your branch is in sync with local Master branch
If this branch is on the remote repository, you have to push your changes
git push origin branchBehindCommit
You can add/remove Appender programmatically to Log4j:
ConsoleAppender console = new ConsoleAppender(); //create appender
//configure the appender
String PATTERN = "%d [%p|%c|%C{1}] %m%n";
console.setLayout(new PatternLayout(PATTERN));
console.setThreshold(Level.FATAL);
console.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(console);
FileAppender fa = new FileAppender();
fa.setName("FileLogger");
fa.setFile("mylog.log");
fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
fa.setThreshold(Level.DEBUG);
fa.setAppend(true);
fa.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(fa);
//repeat with all other desired appenders
I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with
Logger.getRootLogger().getLoggerRepository().resetConfiguration();
and start with adding your own. You need log4j in the classpath of course for this to work.
Remark:
You can take any Logger.getLogger(...)
you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).
If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:
Logger fizz = LoggerFactory.getLogger("com.fizz")
will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to
Logger.getLogger("com.fizz").addAppender(newAppender)
then logging from fizz
will be handled by alle the appenders from the root logger and the newAppender
.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.
Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.
<telerik:RadScriptBlock ID="radSript1" runat="server">
<script type="text/javascript">
//Your javascript
</script>
</telerik>
Regards Örvar
This would be highly dependent on the underlying architecture that the C is compiled to. Some processors and architectures might have explicit instructions for equal to, or less than and equal to, which execute in different numbers of cycles.
That would be pretty unusual though, as the compiler could work around it, making it irrelevant.
Once you declare the type of a variable, you don't need to cast it to that same type. So you can write a=&b;
. Finally, you declared c
incorrectly. Since you assign it to be the address of a
, where a
is a pointer to int
, you must declare it to be a pointer to a pointer to int
.
#include <stdio.h>
int main(void)
{
int b=10;
int *a=&b;
int **c=&a;
printf("%d", **c);
return 0;
}
Move doSomething
definition outside of its class declaration and after B
and also make add
accessible to A
by public
-ing it or friend
-ing it.
class B;
class A
{
void doSomething(B * b);
};
class B
{
public:
void add() {}
};
void A::doSomething(B * b)
{
b->add();
}
People use it because they're inherently lazy when building dynamic SQL queries. If you start with a "where 1 = 1"
then all your extra clauses just start with "and"
and you don't have to figure out.
Not that there's anything wrong with being inherently lazy. I've seen doubly-linked lists where an "empty" list consists of two sentinel nodes and you start processing at the first->next
up until last->prev
inclusive.
This actually removed all the special handling code for deleting first
and last
nodes. In this set-up, every node was a middle node since you weren't able to delete first
or last
. Two nodes were wasted but the code was simpler and (ever so slightly) faster.
The only other place I've ever seen the "1 = 1" construct is in BIRT. Reports often use positional parameters and are modified with Javascript to allow all values. So the query:
select * from tbl where col = ?
when the user selects "*"
for the parameter being used for col
is modified to read:
select * from tbl where ((col = ?) or (1 = 1))
This allows the new query to be used without fiddling around with the positional parameter details. There's still exactly one such parameter. Any decent DBMS (e.g., DB2/z) will optimize that query to basically remove the clause entirely before trying to construct an execution plan, so there's no trade-off.
# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password
encrypted and test with the current Password not encrypted to verify
if it's the same User.
For example :
public function updateUser(Request $req)
{
$entityManager = $this->getDoctrine()->getManager();
$repository = $entityManager->getRepository(User::class);
$user = $repository->find($req->get(id)); /// get User from your DB
if($user == null){
throw $this->createNotFoundException('User don't exist!!', $user);
}
$password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
$passwordToUpdate = $req->get('password'); // not encrypted yet from request.
$passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);
////////////VERIFY IF IT'S THE SAME PASSWORD
$isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );
if($isPass === false){ // failure
throw $this->createNotFoundException('Your password it's not verify', null);
}
return $isPass; //// true!! it's the same password !!!
}
Example HTML:
//jQuery extension method:_x000D_
jQuery.fn.filterByText = function(textbox) {_x000D_
return this.each(function() {_x000D_
var select = this;_x000D_
var options = [];_x000D_
$(select).find('option').each(function() {_x000D_
options.push({_x000D_
value: $(this).val(),_x000D_
text: $(this).text()_x000D_
});_x000D_
});_x000D_
$(select).data('options', options);_x000D_
_x000D_
$(textbox).bind('change keyup', function() {_x000D_
var options = $(select).empty().data('options');_x000D_
var search = $.trim($(this).val());_x000D_
var regex = new RegExp(search, "gi");_x000D_
_x000D_
$.each(options, function(i) {_x000D_
var option = options[i];_x000D_
if (option.text.match(regex) !== null) {_x000D_
$(select).append(_x000D_
$('<option>').text(option.text).val(option.value)_x000D_
);_x000D_
}_x000D_
});_x000D_
});_x000D_
});_x000D_
};_x000D_
_x000D_
// You could use it like this:_x000D_
_x000D_
$(function() {_x000D_
$('select').filterByText($('input'));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option value="hello">hello</option>_x000D_
<option value="world">world</option>_x000D_
<option value="lorem">lorem</option>_x000D_
<option value="ipsum">ipsum</option>_x000D_
<option value="lorem ipsum">lorem ipsum</option>_x000D_
</select>_x000D_
<input type="text">
_x000D_
Live demo here: http://www.lessanvaezi.com/filter-select-list-options/
With FluidXML you can generate and store an XML document very easily.
$doc = fluidxml();
$doc->add('Album', true)
->add('Track', 'Track Title');
$doc->save('album.xml');
Loading a document from a file is equally simple.
$doc = fluidify('album.xml');
$doc->query('//Track')
->attr('id', 123);
Based on @ofer.sheffer answer, this is the CMD variant for adding an affix (this is not the question, but this page is still the #1 google result if you search affix). It is a bit different because of the extension.
for %a in (*.*) do ren "%~a" "%~na-affix%~xa"
You can change the "-affix" part.
class() exactly works like Javascript's typeof operator.
To get more details about variables you can use whos command or whos() function.
Here is the example code executed on MATLAB R2017a's Command Window.
>> % Define a number
>> num = 67
num =
67
>> % Get type of variable num
>> class(num)
ans =
'double'
>> % Define character vector
>> myName = 'Rishikesh Agrawani'
myName =
'Rishikesh Agrwani'
>> % Check type of myName
>> class(myName)
ans =
'char'
>> % Define a cell array
>> cellArr = {'This ', 'is ', 'a ', 'big chance to learn ', 'MATLAB.'}; % Cell array
>>
>> class(cellArr)
ans =
'cell'
>> % Get more details including type
>> whos num
Name Size Bytes Class Attributes
num 1x1 8 double
>> whos myName
Name Size Bytes Class Attributes
myName 1x17 34 char
>> whos cellArr
Name Size Bytes Class Attributes
cellArr 1x5 634 cell
>> % Another way to use whos i.e using whos(char_vector)
>> whos('cellArr')
Name Size Bytes Class Attributes
cellArr 1x5 634 cell
>> whos('num')
Name Size Bytes Class Attributes
num 1x1 8 double
>> whos('myName')
Name Size Bytes Class Attributes
myName 1x17 34 char
>>
php artisan migrate:fresh
Should do the job, if you are in development and the desired outcome is to start all over.
In production, that maybe not the desired thing, so you should be adverted. (The migrate:fresh command will drop all tables from the database and then execute the migrate command).
In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...
@Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)
This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...
model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;
May not be the best way, but it does work.
Be sure that your actual repo is the lastest version
.gitignore
as you wishgit rm -r --cached .
(remove all files)git add .
(re-add all files)then commit as usual
You can also add the following line to your build script:
println "Running gradle version: $gradle.gradleVersion"
or (it won't be printed with -q
switch)
logger.lifecycle "Running gradle version: $gradle.gradleVersion"
if you want to submit two forms with one button you need to do this:
1- use setTimeout()
2- allow show pop up
<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);
}
</script>
<form target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>
javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.
edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.
I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.
Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")
'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
'Select Range
sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
End Sub
If you already know the filename
, you can use the boto3
builtin download_fileobj
import boto3
from io import BytesIO
session = boto3.Session()
s3_client = session.client("s3")
f = BytesIO()
s3_client.download_fileobj(bucket_name, filename, f)
f.seek(0)
print(f.getvalue())
You import one dependency, and this dependency is dependent on com.sun.jmx:jmxri:jar:1.2.1
and others, but com.sun.jmx:jmxri:jar:1.2.1
cannot be found in central repository,
so you'd better try to import another version.
Here suppose your dependency may be log4j, and you can try to import log4j:log4j:jar:1.2.13
.
I think you wanted to do this:
while( $row = mysql_fetch_assoc( $result)){
$new_array[] = $row; // Inside while loop
}
Or maybe store id as key too
$new_array[ $row['id']] = $row;
Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5]
.
IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.
FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
and decrypt that.
setState
takes new state and optional callback function which is called after the state has been updated.
this.setState(
{newState: 'whatever'},
() => {/*do something after the state has been updated*/}
)
I'm not sure I really understood what you want to do, but the suggested way to communicate between fragments is to use callbacks with the Activity, never directly between fragments. See here http://developer.android.com/training/basics/fragments/communicating.html
Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction.
That's incorrect, and suggests you should treat other advice from that person with a degree of skepticism.
The mantra of "only have one return statement" (or more generally, only one exit point) is important in languages where you have to manage all resources yourself - that way you can make sure you put all your cleanup code in one place.
It's much less useful in Java: as soon as you know that you should return (and what the return value should be), just return. That way it's simpler to read - you don't have to take in any of the rest of the method to work out what else is going to happen (other than finally
blocks).
You can also use DBMS_METADATA:
select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY', 'PADCAMPAIGN')
from dual
In SQL Server, row-oriented storage both clustered and nonclustered indexes are organized as B trees.
The key difference between clustered indexes and non clustered indexes is that the leaf level of the clustered index is the table. This has two implications.
Non clustered indexes can also do point 1 by using the INCLUDE
clause (Since SQL Server 2005) to explicitly include all non-key columns but they are secondary representations and there is always another copy of the data around (the table itself).
CREATE TABLE T
(
A INT,
B INT,
C INT,
D INT
)
CREATE UNIQUE CLUSTERED INDEX ci ON T(A, B)
CREATE UNIQUE NONCLUSTERED INDEX nci ON T(A, B) INCLUDE (C, D)
The two indexes above will be nearly identical. With the upper-level index pages containing values for the key columns A, B
and the leaf level pages containing A, B, C, D
There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.
The above quote from SQL Server books online causes much confusion
In my opinion, it would be much better phrased as.
There can be only one clustered index per table because the leaf level rows of the clustered index are the table rows.
The book's online quote is not incorrect but you should be clear that the "sorting" of both non clustered and clustered indices is logical, not physical. If you read the pages at leaf level by following the linked list and read the rows on the page in slot array order then you will read the index rows in sorted order but physically the pages may not be sorted. The commonly held belief that with a clustered index the rows are always stored physically on the disk in the same order as the index key is false.
This would be an absurd implementation. For example, if a row is inserted into the middle of a 4GB table SQL Server does not have to copy 2GB of data up in the file to make room for the newly inserted row.
Instead, a page split occurs. Each page at the leaf level of both clustered and non clustered indexes has the address (File: Page
) of the next and previous page in logical key order. These pages need not be either contiguous or in key order.
e.g. the linked page chain might be 1:2000 <-> 1:157 <-> 1:7053
When a page split happens a new page is allocated from anywhere in the filegroup (from either a mixed extent, for small tables or a non-empty uniform extent belonging to that object or a newly allocated uniform extent). This might not even be in the same file if the filegroup contains more than one.
The degree to which the logical order and contiguity differ from the idealized physical version is the degree of logical fragmentation.
In a newly created database with a single file, I ran the following.
CREATE TABLE T
(
X TINYINT NOT NULL,
Y CHAR(3000) NULL
);
CREATE CLUSTERED INDEX ix
ON T(X);
GO
--Insert 100 rows with values 1 - 100 in random order
DECLARE @C1 AS CURSOR,
@X AS INT
SET @C1 = CURSOR FAST_FORWARD
FOR SELECT number
FROM master..spt_values
WHERE type = 'P'
AND number BETWEEN 1 AND 100
ORDER BY CRYPT_GEN_RANDOM(4)
OPEN @C1;
FETCH NEXT FROM @C1 INTO @X;
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO T (X)
VALUES (@X);
FETCH NEXT FROM @C1 INTO @X;
END
Then checked the page layout with
SELECT page_id,
X,
geometry::Point(page_id, X, 0).STBuffer(1)
FROM T
CROSS APPLY sys.fn_PhysLocCracker( %% physloc %% )
ORDER BY page_id
The results were all over the place. The first row in key order (with value 1 - highlighted with an arrow below) was on nearly the last physical page.
Fragmentation can be reduced or removed by rebuilding or reorganizing an index to increase the correlation between logical order and physical order.
After running
ALTER INDEX ix ON T REBUILD;
I got the following
If the table has no clustered index it is called a heap.
Non clustered indexes can be built on either a heap or a clustered index. They always contain a row locator back to the base table. In the case of a heap, this is a physical row identifier (rid) and consists of three components (File:Page: Slot). In the case of a Clustered index, the row locator is logical (the clustered index key).
For the latter case if the non clustered index already naturally includes the CI key column(s) either as NCI key columns or INCLUDE
-d columns then nothing is added. Otherwise, the missing CI key column(s) silently gets added to the NCI.
SQL Server always ensures that the key columns are unique for both types of indexes. The mechanism in which this is enforced for indexes not declared as unique differs between the two index types, however.
Clustered indexes get a uniquifier
added for any rows with key values that duplicate an existing row. This is just an ascending integer.
For non clustered indexes not declared as unique SQL Server silently adds the row locator into the non clustered index key. This applies to all rows, not just those that are actually duplicates.
The clustered vs non clustered nomenclature is also used for column store indexes. The paper Enhancements to SQL Server Column Stores states
Although column store data is not really "clustered" on any key, we decided to retain the traditional SQL Server convention of referring to the primary index as a clustered index.
I did an attempt to port cocos2d-iphone to GNUstep so that you can Develop game based on cocos2d. However for publishing you need a mac. cocos2d-GNUstep.
If you installed mysql through brew then we can use command to uninstall mysql.
$ brew uninstall mysql
Uninstalling /usr/local/Cellar/mysql/5.6.19...
This worked for me.
The situation becomes a little bit problematic if we want to create a branch from a tag with the same name.
In this, and in similar scenarios, the important thing is to know: branches and tags are actually single-line text files in .git/refs
directory, and we can reference them explicitly using their pathes below .git
. Branches are called here "heads", to make our life more simple.
Thus, refs/heads/master
is the real, explicit name of the master
branch. And refs/tags/cica
is the exact name of the tag named cica
.
The correct command to create a branch named cica
from the tag named cica
is:
git branch cica refs/tags/cica
In my case, i had opened Pycharm in sudo mode, and was running pip install nltk in pycharm terminal which showed this error. running with sudo pip install solves the error.
Both
-Djavax.net.ssl.trustStore=path/to/trustStore.jks
and
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore
in javax.net.ssl.trustStore.
You can also get the API key in the android studio. Switch to Project view in android then find the google-services.json. Scroll down and you will find the api_key
if your using sqlsrv_connect you have to download and install MS sql driver for your php. download it here http://www.microsoft.com/en-us/download/details.aspx?id=20098 extract it to your php folder or ext in xampp folder then add this on the end of the line in your php.ini file
extension=php_pdo_sqlsrv_55_ts.dll
extension=php_sqlsrv_55_ts.dll
im using xampp version 5.5 so its name php_pdo_sqlsrv_55_ts.dll & php_sqlsrv_55_ts.dll
if you are using xampp version 5.5 dll files is not included in the link...hope it helps
All you need is a ADODB.Connection
Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset ' Microsoft ActiveX Data Objects Library
Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"
Set rs = cnn.Execute(SQLQuery) ' Retrieve the data
Lets say you have a form similar to this
<form action="membersDeleteAllData.html" method="post">
<button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>
Here is the javascript for the confirmAction function
<script type="text/javascript">
function confirmAction(e)
{
var confirmation = confirm("Are you sure about this ?") ;
if (!confirmation)
{
e.preventDefault() ;
returnToPreviousPage();
}
return confirmation ;
}
</script>
This one works on Firefox, Chrome, Internet Explorer(edge), Safari, etc.
If that is not the case let me know
I'm unclear about your question. From http://effbot.org/tkinterbook/entry.htm#patterns, it seems you just need to do an assignment after you called the delete. To add entry text to the widget, use the insert method. To replace the current text, you can call delete before you insert the new text.
e = Entry(master)
e.pack()
e.delete(0, END)
e.insert(0, "")
Could you post a bit more code?
If you type:
if { number.value.length!= 10}...
It will sure work because the value is the quantity which will be driven from the object.
You've started right - now you just need to fill the each student
structure in the array:
struct student
{
public int s_id;
public String s_name, c_name, dob;
}
class Program
{
static void Main(string[] args)
{
student[] arr = new student[4];
for(int i = 0; i < 4; i++)
{
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
arr[i].s_id = Int32.Parse(Console.ReadLine());
arr[i].s_name = Console.ReadLine();
arr[i].c_name = Console.ReadLine();
arr[i].s_dob = Console.ReadLine();
}
}
}
Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.
Not at the SQL level and that's a pity There is one in PLSQL though
Add a shortcut:
$.Shortcuts.add({
type: 'down',
mask: 'Ctrl+A',
handler: function() {
debug('Ctrl+A');
}
});
Start reacting to shortcuts:
$.Shortcuts.start();
Add a shortcut to “another” list:
$.Shortcuts.add({
type: 'hold',
mask: 'Shift+Up',
handler: function() {
debug('Shift+Up');
},
list: 'another'
});
Activate “another” list:
$.Shortcuts.start('another');
Remove a shortcut:
$.Shortcuts.remove({
type: 'hold',
mask: 'Shift+Up',
list: 'another'
});
Stop (unbind event handlers):
$.Shortcuts.stop();
fig.add_subplot(ROW,COLUMN,POSITION)
Examples
`fig.add_subplot(111)` #There is only one subplot or graph
`fig.add_subplot(211)` *and* `fig.add_subplot(212)`
There are total 2 rows,1 column therefore 2 subgraphs can be plotted. Its location is 1st. There are total 2 rows,1 column therefore 2 subgraphs can be plotted.Its location is 2nd
I will add a StackBlitz example and a comment to the answer from @tahiche.
The return value is a function to remove the event listener after you have added it. It is considered good practice to remove event listeners when you don't need them anymore. So you can store this return value and call it inside your ngOnDestroy
method.
I admit that it might seem confusing at first, but it is actually a very useful feature. How else can you clean up after yourself?
export class MyComponent implements OnInit, OnDestroy {
public removeEventListener: () => void;
constructor(
private renderer: Renderer2,
private elementRef: ElementRef
) {
}
public ngOnInit() {
this.removeEventListener = this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
if (event.target instanceof HTMLAnchorElement) {
// Prevent opening anchors the default way
event.preventDefault();
// Your custom anchor click event handler
this.handleAnchorClick(event);
}
});
}
public ngOnDestroy() {
this.removeEventListener();
}
}
You can find a StackBlitz here to show how this could work for catching clicking on anchor elements.
I added a body with an image as follows:
<img src="x" onerror="alert(1)"></div>
to show that the sanitizer is doing its job.
Here in this fiddle you find the same body attached to an innerHTML
without sanitizing it and it will demonstrate the issue.
I had a similar problem that I solved by using the following sequence:
use the CELL("filename")
function to get the full path to the current sheet of the current file.
use the SEARCH()
function to find the start of the [FileName]SheetName string of your current excel file and the sheet.
use the LEFT
function to extract the full path name of the directory that contains your current file.
Concatenate the directory path name found in step #3 with the name of the file, the name of the worksheet, and the cell reference that you want to access.
use the INDIRECT()
function to access the CellPathName
that you created in step #4.
Note: these same steps can also be used to access cells in files whose names are created dynamically. In step #4, use a text string that is dynamically created from the contents of cells, the current date or time, etc. etc.
A cell reference example (with each piece assembled separately) that includes all of these steps is:
=INDIRECT("'" & LEFT(CELL("filename"),SEARCH("[MyFileName]MySheetName",CELL("filename")) - 1) & "[" & "OtherFileName" & "]" & "OtherSheetName" & "'!" & "$OtherColumn$OtherRow" & "'")
Note that LibreOffice uses a slightly different CellPatnName syntax, as in the following example:
=INDIRECT(LEFT(CELL("filename"),SEARCH("[MyFileName]MySheetName",CELL("filename")) - 1) & "OtherFileName" & "'#$" & "OtherSheetName" & "." & "$OtherColumn$OtherRow")
{
"success": true,
"data": {
"BLR": {
"origin": "JAI",
"destination": "BLR",
"price": 127,
"transfers": 0,
"airline": "LB",
"flight_number": 655,
"departure_at": "2017-06-03T18:20:00Z",
"return_at": "2017-06-07T08:30:00Z",
"expires_at": "2017-03-05T08:40:31Z"
}
}
};
A UUID created by CFUUIDCreate
is unique if a user uninstalls and re-installs the app: you will get a new one each time.
But you might want it to be not unique, i. e. it should stay the same when the user uninstalls and re-installs the app. This requires a bit of effort, since the most reliable per-device-identifier seems to be the MAC address. You could query the MAC and use that as UUID.
Edit: One needs to always query the MAC of the same interface, of course. I guess the best bet is with en0
. The MAC is always present, even if the interface has no IP/is down.
Edit 2: As was pointed out by others, the preferred solution since iOS 6 is -[UIDevice identifierForVendor]. In most cases, you should be able use it as a drop-in replacement to the old -[UIDevice uniqueIdentifier]
(but a UUID that is created when the app starts for the first time is what Apple seems to want you to use).
Edit 3: So this major point doesn't get lost in the comment noise: do not use the MAC as UUID, create a hash using the MAC. That hash will always create the same result every time, even across reinstalls and apps (if the hashing is done in the same way). Anyways, nowadays (2013) this isn't necessary any more except if you need a "stable" device identifier on iOS < 6.0.
Edit 4: In iOS 7, Apple now always returns a fixed value when querying the MAC to specifically thwart the MAC as base for an ID scheme. So you now really should use -[UIDevice identifierForVendor] or create a per-install UUID.
See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):
var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );
https.createServer({
key: privateKey,
cert: certificate
}, app).listen(port);
Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
I'd like to offer an updated Python 3 version of Vishal's excellent answer, which was using Python 2, along with some explanation of the adaptations / changes, which may have been already mentioned.
from io import BytesIO
from zipfile import ZipFile
import urllib.request
url = urllib.request.urlopen("http://www.unece.org/fileadmin/DAM/cefact/locode/loc162txt.zip")
with ZipFile(BytesIO(url.read())) as my_zip_file:
for contained_file in my_zip_file.namelist():
# with open(("unzipped_and_read_" + contained_file + ".file"), "wb") as output:
for line in my_zip_file.open(contained_file).readlines():
print(line)
# output.write(line)
Necessary changes:
StringIO
module in Python 3 (it's been moved to io.StringIO
). Instead, I use io.BytesIO
]2, because we will be handling a bytestream -- Docs, also this thread.urllib.urlopen
function from Python 2.6 and earlier has been discontinued; urllib.request.urlopen()
corresponds to the old urllib2.urlopen
.", Docs and this thread.Note:
b'some text'
. This is expected, as they aren't strings - remember, we're reading a bytestream. Have a look at Dan04's excellent answer.A few minor changes I made:
with ... as
instead of zipfile = ...
according to the Docs..namelist()
to cycle through all the files in the zip and print their contents.ZipFile
object into the with
statement, although I'm not sure if that's better."unzipped_and_read_"
to the beginning of the filename and a ".file"
extension (I prefer not to use ".txt"
for files with bytestrings). The indenting of the code will, of course, need to be adjusted if you want to use it.
"wb"
; I have a feeling that writing binary opens a can of worms anyway...What I didn't do:
Here's a way:
import urllib.request
import shutil
with urllib.request.urlopen("http://www.unece.org/fileadmin/DAM/cefact/locode/2015-2_UNLOCODE_SecretariatNotes.pdf") as response, open("downloaded_file.pdf", 'w') as out_file:
shutil.copyfileobj(response, out_file)
I just did this for fun
>>> s = 'a,b,c,d'
>>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
['a,b,c', 'd']
Caution: Refer to the first comment in below where this answer can go wrong.
Of course it returns a string. If you wanted to round the numeric variable you'd use Math.round() instead. The point of toFixed is to format the number with a fixed number of decimal places for display to the user.
sys.executable
contains full path of the currently running Python interpreter.
import sys
print(sys.executable)
which is now documented here
If your table doesn't have any records you can just drop then create your table.
If it has records you can do it using your SQL Server Management Studio.
Just click your table > right click > click Design then you can now arrange the order of the columns by dragging the fields on the order that you want then click save.
Best Regards
For what it's worth, I got inspired by the other answers and wrote a small utility which calls the platform specific APIs to be used universally from either Node.js or a browser:
/**
* Encode a string of text as base64
*
* @param data The string of text.
* @returns The base64 encoded string.
*/
function encodeBase64(data: string) {
if (typeof btoa === "function") {
return btoa(data);
} else if (typeof Buffer === "function") {
return Buffer.from(data, "utf-8").toString("base64");
} else {
throw new Error("Failed to determine the platform specific encoder");
}
}
/**
* Decode a string of base64 as text
*
* @param data The string of base64 encoded text
* @returns The decoded text.
*/
function decodeBase64(data: string) {
if (typeof atob === "function") {
return atob(data);
} else if (typeof Buffer === "function") {
return Buffer.from(data, "base64").toString("utf-8");
} else {
throw new Error("Failed to determine the platform specific decoder");
}
}
_x000D_
on delete button click event
public void delete(View v){
ListView listview1;
ArrayList<E> datalist;
final int position = listview1.getPositionForView((View) v.getParent());
datalist.remove(position);
myAdapter.notifyDataSetChanged();
}
It is worth pointing out that if you use json_decode(file_get_contents("php://input"))
(as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params)
above may result in subtle errors, as json_last_error()
does not change when null
or a blank string is passed, as shown here:
http://ideone.com/va3u8U
You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.
used like: window.Promise
https://www.npmjs.com/package/promise-polyfill
If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill
Found this:
If
items()
,keys()
,values()
,iteritems()
,iterkeys()
, anditervalues()
are called with no intervening modifications to the dictionary, the lists will directly correspond.
On 2.x documentation and 3.x documentation.
In case, if anyone prefers a simpler solution, especially on Linux (e.g. Ubuntu), a very easy way out is to create a symbolic link to the intended folder in the htdocs folder. For example, if I want to be able to serve files from a folder called "/home/some/projects/testserver/" and my htdocs is located in "/opt/lampp/htdocs/". Just create a symbolic link like so:
ln -s /home/some/projects/testserver /opt/lampp/htdocs/testserver
The command for symbolic link works like so:
ln -s target source
where,
target - The existing file/directory you would like to link TO.
source - The file/folder to be created, copying the contents of the target. The LINK itself.
For more help see ln --help Source: Create Symbolic Links in Ubuntu
And that's done. just visit http://localhost/testserver/ In fact, you don't even need to restart your server.
I came across this really great talk by Facebook engineers about the Efficient Storage of Billions of Photos in a database
You can add the following to the <head>
of your HTML file:
<script src="https://smtpjs.com/v3/smtp.js"></script>
<script type="text/javascript">
function sendEmail() {
Email.send({
SecureToken: "security token of your smtp",
To: "[email protected]",
From: "[email protected]",
Subject: "Subject...",
Body: document.getElementById('text').value
}).then(
message => alert("mail sent successfully")
);
}
</script>
and below is the HMTL part:
<textarea id="text">write text here...</textarea>
<input type="button" value="Send Email" onclick="sendEmail()">
So the sendEmail() function gets the inputs using:
document.getElementById('id_of_the_element').value
For example, you can add another HTML element such as the subject (with id="subject"):
<textarea id="subject">write text here...</textarea>
and get its value in the sendEmail() function:
Subject: document.getElementById('subject').value
And you are done!
Note: If you do not have a SMTP server you can create one for free here. And then encrypt your SMTP credentials here (the SecureToken attribute in sendEmail() corresponds to the encrypted credentials generated there).
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
i had the same issue and find the solution lately.
you should check if your route is rather inside a route::group
like here:
Route::group(['prefix' => 'Auth', 'as' => 'Auth.', 'namespace' => 'Auth', 'middleware' => 'Auth']
if so you should use it in the view file. like here:
!! Form::model(Auth::user(), ['method' => 'PATCH', 'route' => 'Auth.preferences/' . Auth::user()->id]) !!}
The code from http://code.activestate.com/recipes/410469-xml-as-dictionary/ works well, but if there are multiple elements that are the same at a given place in the hierarchy it just overrides them.
I added a shim between that looks to see if the element already exists before self.update(). If so, pops the existing entry and creates a lists out of the existing and the new. Any subsequent duplicates are added to the list.
Not sure if this can be handled more gracefully, but it works:
import xml.etree.ElementTree as ElementTree
class XmlDictConfig(dict):
def __init__(self, parent_element):
if parent_element.items():
self.updateShim(dict(parent_element.items()))
for element in parent_element:
if len(element):
aDict = XmlDictConfig(element)
if element.items():
aDict.updateShim(dict(element.items()))
self.updateShim({element.tag: aDict})
elif element.items():
self.updateShim({element.tag: dict(element.items())})
else:
self.updateShim({element.tag: element.text.strip()})
def updateShim (self, aDict ):
for key in aDict.keys():
if key in self:
value = self.pop(key)
if type(value) is not list:
listOfDicts = []
listOfDicts.append(value)
listOfDicts.append(aDict[key])
self.update({key: listOfDicts})
else:
value.append(aDict[key])
self.update({key: value})
else:
self.update(aDict)
As multi-threading is very easy with Java, here is a variant that searches for a seed using all cores available: http://ideone.com/ROhmTA
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class SeedFinder {
static class SearchTask implements Callable<Long> {
private final char[] goal;
private final long start, step;
public SearchTask(final String goal, final long offset, final long step) {
final char[] goalAsArray = goal.toCharArray();
this.goal = new char[goalAsArray.length + 1];
System.arraycopy(goalAsArray, 0, this.goal, 0, goalAsArray.length);
this.start = Long.MIN_VALUE + offset;
this.step = step;
}
@Override
public Long call() throws Exception {
final long LIMIT = Long.MAX_VALUE - this.step;
final Random random = new Random();
int position, rnd;
long seed = this.start;
while ((Thread.interrupted() == false) && (seed < LIMIT)) {
random.setSeed(seed);
position = 0;
rnd = random.nextInt(27);
while (((rnd == 0) && (this.goal[position] == 0))
|| ((char) ('`' + rnd) == this.goal[position])) {
++position;
if (position == this.goal.length) {
return seed;
}
rnd = random.nextInt(27);
}
seed += this.step;
}
throw new Exception("No match found");
}
}
public static void main(String[] args) {
final String GOAL = "hello".toLowerCase();
final int NUM_CORES = Runtime.getRuntime().availableProcessors();
final ArrayList<SearchTask> tasks = new ArrayList<>(NUM_CORES);
for (int i = 0; i < NUM_CORES; ++i) {
tasks.add(new SearchTask(GOAL, i, NUM_CORES));
}
final ExecutorService executor = Executors.newFixedThreadPool(NUM_CORES, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
final Thread result = new Thread(r);
result.setPriority(Thread.MIN_PRIORITY); // make sure we do not block more important tasks
result.setDaemon(false);
return result;
}
});
try {
final Long result = executor.invokeAny(tasks);
System.out.println("Seed for \"" + GOAL + "\" found: " + result);
} catch (Exception ex) {
System.err.println("Calculation failed: " + ex);
} finally {
executor.shutdownNow();
}
}
}
Create One Class With Name Startup this will help you..
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
I wanted to add to what @JohnMudd has written about Kivy. It has been years since the situation he described, and Kivy has evolved substantially.
The biggest selling point of Kivy, in my opinion, is its cross-platform compatibility. You can code and test everything using any desktop environment (Windows/*nix etc.), then package your app for a range of different platforms, including Android, iOS, MacOS and Windows (though apps often lack the native look and feel).
With Kivy's own KV language, you can code and build the GUI interface easily (it's just like Java XML, but rather than TextView etc., KV has its own ui.widgets
for a similar translation), which is in my opinion quite easy to adopt.
Currently Buildozer and python-for-android are the most recommended tools to build and package your apps. I have tried them both and can firmly say that they make building Android apps with Python a breeze. Their guides are well documented too.
iOS is another big selling point of Kivy. You can use the same code base with few changes required via kivy-ios Homebrew tools, although Xcode is required for the build, before running on their devices (AFAIK the iOS Simulator in Xcode currently doesn't work for the x86-architecture build). There are also some dependency issues which must be manually compiled and fiddled around with in Xcode to have a successful build, but they wouldn't be too difficult to resolve and people in Kivy Google Group are really helpful too.
With all that being said, users with good Python knowledge should have no problem picking up the basics quickly.
If you are using Kivy for more serious projects, you may find existing modules unsatisfactory. There are some workable solutions though. With the (work in progress) pyjnius for Android, and pyobjus, users can now access Java/Objective-C classes to control some of the native APIs.
std::vector<CustomClass *> whatever(20000);
or:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.
Replacing spaces is fine, but I might suggest going a little further to handle other URL-hostile characters like question marks, apostrophes, exclamation points, etc.
Also note that the general consensus among SEO experts is that dashes are preferred to underscores in URLs.
import re
def urlify(s):
# Remove all non-word characters (everything except numbers and letters)
s = re.sub(r"[^\w\s]", '', s)
# Replace all runs of whitespace with a single dash
s = re.sub(r"\s+", '-', s)
return s
# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))
When using instanceof
, you need to know the class of B
at compile time. When using isAssignableFrom()
it can be dynamic and change during runtime.
Undoing a merge with git is so easy you shouldn't even worry about the dry run:
$ git pull $REMOTE $BRANCH
# uh oh, that wasn't right
$ git reset --hard ORIG_HEAD
# all is right with the world
EDIT: As noted in the comments below, if you have changes in your working directory or staging area you'll probably want to stash them before doing the above (otherwise they will disappear following the git reset
above)
The way I often deal with the situation you describe is to use the .to_csv()
method and write to stdout:
import sys
df.to_csv(sys.stdout)
Update: it should now be possible to just use None
instead of sys.stdout
with similar effect!
This should dump the whole dataframe, including the entirety of any strings. You can use the to_csv parameters to configure column separators, whether the index is printed, etc. It will be less pretty than rendering it properly though.
I posted this originally in answer to the somewhat-related question at Output data from all columns in a dataframe in pandas
$route: This is used for deep-linking URLs to controllers and views (HTML partials) and watches $location.url() in order to map the path from an existing definition of route.
When we use ngRoute, the route is configured with $routeProvider and when we use ui-router, the route is configured with $stateProvider and $urlRouterProvider.
<div ng-view></div>
$routeProvider
.when('/contact/', {
templateUrl: 'app/views/core/contact/contact.html',
controller: 'ContactCtrl'
});
<div ui-view>
<div ui-view='abc'></div>
<div ui-view='abc'></div>
</div>
$stateProvider
.state("contact", {
url: "/contact/",
templateUrl: '/app/Aisel/Contact/views/contact.html',
controller: 'ContactCtrl'
});
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
For an advanced user text input is the best, if the user knows the date format, it is very fast. For a not so advanced user I suggest using a datepicker. Since usually you also have advanced and non-advanced users I suggest a combination of text input and datepicker.
If you have already git merge bugfix
on main
, you can squash your merge commit into one with:
git reset --soft HEAD^1
git commit
None of above answer solve my problem.
The fact is that my project did not have type script installed.
But locally I had run npm install -g typescript
. So I did not notice that typescript node dependency was not in my package json.
When I pushed it to server side, and run npm install
, then npx tsc
I get a tsc not found. In facts remote server did not have typescript installed. That was hidden because of my local global typescript install.
tl;dr What to do in modern (2018) times? Assume tel:
is supported, use it and forget about anything else.
The tel:
URI scheme RFC5431 (as well as sms:
but also feed:
, maps:
, youtube:
and others) is handled by protocol handlers (as mailto:
and http:
are).
They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto:
protocol handler with same meaning and behaviour of tel:
but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.
What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler()
and related functions) simplifying also the check for their support through isProtocolHandlerRegistered()
function.
There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).
In general what I suggest is:
tel:
is supported (yes, it's not true for very old devices but IMO you can ignore them).tel:
isn't supported then change links to use callto:
and repeat check desctibed in 3.tel:
and callto:
aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href
with javascript:void(0)
and (if number isn't repeated in text span) putting, telephone number in title
. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto:
and tel:
.Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:
tel:
is supported.tel:
with callto:
.tel:
or leave it as is (assuming there are good chances Skype is installed).This is a simple loop that keeps prompting unless the user selects 'y' or 'n'
$confirmation = Read-Host "Ready? [y/n]"
while($confirmation -ne "y")
{
if ($confirmation -eq 'n') {exit}
$confirmation = Read-Host "Ready? [y/n]"
}
<div (window:resize)="onResize($event)"
onResize(event) {
event.target.innerWidth;
}
or using the HostListener decorator:
@HostListener('window:resize', ['$event'])
onResize(event) {
event.target.innerWidth;
}
Supported global targets are window
, document
, and body
.
Until https://github.com/angular/angular/issues/13248 is implemented in Angular it is better for performance to subscribe to DOM events imperatively and use RXJS to reduce the amount of events as shown in some of the other answers.
I had to move domain, username, password from
client.ClientCredentials.UserName.UserName = domain + "\\" + username; client.ClientCredentials.UserName.Password = password
to
client.ClientCredentials.Windows.ClientCredential.UserName = username; client.ClientCredentials.Windows.ClientCredential.Password = password; client.ClientCredentials.Windows.ClientCredential.Domain = domain;
simply use this in your imagebutton layout
android:background="@null"
using
android:background="@android:color/transparent
or
btn.setBackgroundColor(Color.TRANSPARENT);
doesn't give perfect transparency
The best example is this one, No hiding, No jQuery, It's completely pure CSS
http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/
.custom-file-input::-webkit-file-upload-button {_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
.custom-file-input::before {_x000D_
content: 'Select some files';_x000D_
display: inline-block;_x000D_
background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);_x000D_
border: 1px solid #999;_x000D_
border-radius: 3px;_x000D_
padding: 5px 8px;_x000D_
outline: none;_x000D_
white-space: nowrap;_x000D_
-webkit-user-select: none;_x000D_
cursor: pointer;_x000D_
text-shadow: 1px 1px #fff;_x000D_
font-weight: 700;_x000D_
font-size: 10pt;_x000D_
}_x000D_
_x000D_
.custom-file-input:hover::before {_x000D_
border-color: black;_x000D_
}_x000D_
_x000D_
.custom-file-input:active::before {_x000D_
background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);_x000D_
}
_x000D_
<input type="file" class="custom-file-input">
_x000D_
"are there any issue we should expect from only storing and retreiving a money amount in a DOUBLE column ?"
It sounds like no rounding errors can be produced in your scenario and if there were, they would be truncated by the conversion to BigDecimal.
So I would say no.
However, there is no guarantee that some change in the future will not introduce a problem.
@ is a shortcut option for v-on. Use @ only when you want to execute some Vue methods. As you are not executing Vue methods, instead you are calling javascript function, you need to use onchange attribute to call javascript function
<select name="LeaveType" onchange="onChange(this.value)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
function onChange(value) {
console.log(value);
}
If you want to call Vue methods, do it like this-
<select name="LeaveType" @change="onChange($event)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
new Vue({
...
...
methods:{
onChange:function(event){
console.log(event.target.value);
}
}
})
You can use v-model data attribute on the select element to bind the value.
<select v-model="selectedValue" name="LeaveType" onchange="onChange(this.value)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
new Vue({
data:{
selectedValue : 1, // First option will be selected by default
},
...
...
methods:{
onChange:function(event){
console.log(this.selectedValue);
}
}
})
Hope this Helps :-)
Actually, there is another easy way to do it. It works for me but I'm not sure for you guys. The key thing here, is just adding the FADE in each (tab-pane) and it will works. Besides, you don't even need to script function or whatever version of jQuery. Here is my code...hope it will works for you all.
<div class="tab-pane fade" id="Customer">
<table class="table table-hover table-bordered">
<tr>
<th width="40%">Contact Person</th>
<td><?php echo $event['Event']['e_contact_person']; ?></td>
</tr>
</table>
</div>
<div class="tab-pane fade" id="Delivery">
<table class="table table-hover table-bordered">
<tr>
<th width="40%">Time Arrive Warehouse Start</th>
<td><?php echo $event['Event']['e_time_arrive_WH_start']; ?></td>
</tr>
</table>
</div>
d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)
print(sum1)
you can do it using the for loop
I have had a difficulty with the EF when the connection the server is stopped or paused, and I raised the same question. So for completeness to the above answers here is the code.
/// <summary>
/// Test that the server is connected
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <returns>true if the connection is opened</returns>
private static bool IsServerConnected(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
return true;
}
catch (SqlException)
{
return false;
}
}
}
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id', 'inner');
$this->db->join('table3', 'table1.id = table3.id', 'inner');
$this->db->where("table1", $id );
$query = $this->db->get();
Where you can specify which id should be viewed or select in specific table. You can also select which join portion either left, right, outer, inner, left outer, and right outer on the third parameter of join method.
use this one
//for getting length of object
int length = jsonObject.length();
or
//for getting length of array
int length = jsonArray.length();
You can both remove row names and convert them to a column by reference (without reallocating memory using ->
) using setDT
and its keep.rownames = TRUE
argument from the data.table
package
library(data.table)
setDT(df, keep.rownames = TRUE)[]
# rn VALUE ABS_CALL DETECTION P.VALUE
# 1: 1 1007_s_at 957.7292 P 0.004862793
# 2: 2 1053_at 320.6327 P 0.031335632
# 3: 3 117_at 429.8423 P 0.017000453
# 4: 4 121_at 2395.7364 P 0.011447358
# 5: 5 1255_g_at 116.4936 A 0.397993682
# 6: 6 1294_at 739.9271 A 0.066864977
As mentioned by @snoram, you can give the new column any name you want, e.g. setDT(df, keep.rownames = "newname")
would add "newname" as the rows column.
As for now there is no proper solution, as @spro says.
However, if you have an in-flight response and are using ReadableStream, you can close the stream to cancel the request.
fetch('http://example.com').then((res) => {
const reader = res.body.getReader();
/*
* Your code for reading streams goes here
*/
// To abort/cancel HTTP request...
reader.cancel();
});
Correct syntax looks like this. See MSDN.
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS
This worked for me:
location / {
try_files $uri $uri/ /base.html;
}
It sounds like you are talking about aggregation. Each instance of your player
class can contain zero or more instances of Airplane
, which, in turn, can contain zero or more instances of Flight
. You can implement this in Python using the built-in list
type to save you naming variables with numbers.
class Flight(object):
def __init__(self, duration):
self.duration = duration
class Airplane(object):
def __init__(self):
self.flights = []
def add_flight(self, duration):
self.flights.append(Flight(duration))
class Player(object):
def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
self.stock = stock
self.bank = bank
self.fuel = fuel
self.total_pax = total_pax
self.airplanes = []
def add_planes(self):
self.airplanes.append(Airplane())
if __name__ == '__main__':
player = Player()
player.add_planes()
player.airplanes[0].add_flight(5)
IMPORTANT Gotcha for using .contains() on a Collection of Objects, such as Domains. If the Domain declaration contains a EqualsAndHashCode, or some other equals() implementation to determine if those Ojbects are equal, and you've set it like this...
import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode(includes = "settingNameId, value")
then the .contains(myObjectToCompareTo) will evaluate the data in myObjectToCompareTo with the data for each Object instance in the Collection. So, if your equals method isn't up to snuff, as mine was not, you might see unexpected results.
The below code helps me to return a JSON object for JavaScript on the front end
My template code
template_file.json
{
"name": "{{name}}"
}
Python backed code
def download_json(request):
print("Downloading JSON")
# Response render a template as JSON object
return HttpResponse(render_to_response("template_file.json",dict(name="Alex Vera")),content_type="application/json")
File url.py
url(r'^download_as_json/$', views.download_json, name='download_json-url')
jQuery code for the front end
$.ajax({
url:'{% url 'download_json-url' %}'
}).done(function(data){
console.log('json ', data);
console.log('Name', data.name);
alert('hello ' + data.name);
});
Are you trying to drop the FK constraint or the column itself?
To drop the constraint:
alter table company drop constraint Company_CountryID_FK
You won't be able to drop the column until you drop the constraint.
Maybe I'm being dumb, but isn't table the obvious solution here?
<div class="parent">
<div class="fixed">
<div class="stretchToFit">
</div>
.parent{ display: table; width 100%; }
.fixed { display: table-cell; width: 150px; }
.stretchToFit{ display: table-cell; vertical-align: top}
Another way that I've figured out in chrome is even simpler, but man is it a hack!
.fixed{
float: left
}
.stretchToFit{
display: table-cell;
width: 1%;
}
This alone should fill the rest of the line horizontally, as table-cells do. However, you get some strange issues with it going over 100% of its parent, setting the width to a percent value fixes it though.
Set the set the Email Message IsBodyHtml = true
Take your object that contains your email contents Serialize the object and use xml/xslt to generate the html content.
If you want to do AlternateViews do the same thing that jmein only use a different xslt template to create the plain text content.
one of the major advantages to this is if you want to change your layout all you have to do update the xslt template.
Oracle 11G Express Edition is now available to install on 64-bit versions of Windows.
Use the following function:
DATEADD(type, value, date)
date is the date you want to manipulate
value is the integere value you want to add (or subtract if you provide a negative number)
type is one of:
SELECT DATEADD(dd, 1, GETDATE()) will return a current date + 1 day
The answer is correct, but you don't need to declare a variable. A string can contain your character:
"This string contains omega, that looks like this: \u03A9"
Unfortunately still those codes in ASCII are needed for displaying UTF-8, but I am still waiting (since too many years...) the day when UTF-8 will be same as ASCII was, and ASCII will be just a remembrance of the past.
You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:
function PersonListCtrl($scope, $http) {
$scope.loadData = function () {
$http.get('/persons').success(function(data) {
$scope.persons = data;
});
};
//initial load
$scope.loadData();
}
then in your markup
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="loadData()">Refresh</button>
</div>
As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:
for example (just puedo code) in your controller:
$scope.addPerson = function() {
$scope.persons.push({ name: 'Test Monkey' });
};
Then you could use that in your view or whatever you'd want to do.
You also may use an extension method, so it will be more readable (although everybody is already used to the regular Parse functions).
public static class StringExtensions
{
/// <summary>
/// Converts a string to int.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The converted integer.</returns>
public static int ParseToInt32(this string value)
{
return int.Parse(value);
}
/// <summary>
/// Checks whether the value is integer.
/// </summary>
/// <param name="value">The string to check.</param>
/// <param name="result">The out int parameter.</param>
/// <returns>true if the value is an integer; otherwise, false.</returns>
public static bool TryParseToInt32(this string value, out int result)
{
return int.TryParse(value, out result);
}
}
And then you can call it that way:
If you are sure that your string is an integer, like "50".
int num = TextBoxD1.Text.ParseToInt32();
If you are not sure and want to prevent crashes.
int num;
if (TextBoxD1.Text.TryParseToInt32(out num))
{
//The parse was successful, the num has the parsed value.
}
To make it more dynamic, so you can parse it also to double, float, etc., you can make a generic extension.
If you can use bootstrap3 then you can use css "navbar-fixed-top" also you need to add below css to push your page content down
body{
margin-top:100px;
}
If you purpose it to a html input, you can easily do this without the use of JavaScript! or any other JS libraries. It would be standard and very easy to use a CSS tag text-transform:
<input type="text" style="text-transform: uppercase" >
or you can use a bootstrap class named as "text-uppercase"
<input type="text" class="text-uppercase" >
In this manner, your code is much simpler!
You can now use Object.assign(target, ...sources)
. Following your example, you could use it like this:
class Foo {
name: string;
getName(): string { return this.name };
}
let fooJson: string = '{"name": "John Doe"}';
let foo: Foo = Object.assign(new Foo(), JSON.parse(fooJson));
console.log(foo.getName()); //returns John Doe
Object.assign
is part of ECMAScript 2015 and is currently available in most modern browsers.
To find ANY and ALL unicode error related... Using the following command:
grep -r -P '[^\x00-\x7f]' /etc/apache2 /etc/letsencrypt /etc/nginx
Found mine in
/etc/letsencrypt/options-ssl-nginx.conf: # The following CSP directives don't use default-src as
Using shed
, I found the offending sequence. It turned out to be an editor mistake.
00008099: C2 194 302 11000010
00008100: A0 160 240 10100000
00008101: d 64 100 144 01100100
00008102: e 65 101 145 01100101
00008103: f 66 102 146 01100110
00008104: a 61 097 141 01100001
00008105: u 75 117 165 01110101
00008106: l 6C 108 154 01101100
00008107: t 74 116 164 01110100
00008108: - 2D 045 055 00101101
00008109: s 73 115 163 01110011
00008110: r 72 114 162 01110010
00008111: c 63 099 143 01100011
00008112: C2 194 302 11000010
00008113: A0 160 240 10100000
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
I think I see your problem, you need to use the @
syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?
This is what I can suggest based on what I see so far:
.factory('MagComments', function ($resource) {
return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
loginID : organEntity,
password : organCommpassword,
id : '@magId'
});
})
The @magId
string will tell the resource to replace :id
with the property magId
on the object you pass it as parameters.
I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.
MoreLinq has a DistinctBy method that you can use:
It will allow you to do:
var results = table1.DistictBy(row => row.Text);
The implementation of the method (short of argument validation) is as follows:
private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
You can use this code too, to see the status of any link:
<?php
function get_url_status($url, $timeout = 10)
{
$ch = curl_init();
// set cURL options
$opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser
CURLOPT_URL => $url, // set URL
CURLOPT_NOBODY => true, // do a HEAD request only
CURLOPT_TIMEOUT => $timeout); // set timeout
curl_setopt_array($ch, $opts);
curl_exec($ch); // do it!
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE); // find HTTP status
curl_close($ch); // close handle
echo $status; //or return $status;
//example checking
if ($status == '302') { echo 'HEY, redirection';}
}
get_url_status('http://yourpage.comm');
?>
@using (Html.BeginForm()) {
<p>Do you like pizza?
@Html.DropDownListFor(x => x.likesPizza, new[] {
new SelectListItem() {Text = "Yes", Value = bool.TrueString},
new SelectListItem() {Text = "No", Value = bool.FalseString}
}, "Choose an option")
</p>
<input type = "submit" value = "Submit my answer" />
}
I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.
Some notes for beginners:
Hope this helps someone,
Quick and in some cases error-prone solution:
Find Regexp: (?sm)(.*?)([^\n]*\b(class|interface|enum)\b.*)
Replace: $1/**\n * \n * @author <a href="mailto:[email protected]">John Smith</a>\n */\n$2
This will add the header to the first encountered class/interface/enum in the file. Class should have no existing header yet.
Connect to an existing host but to a port that is blocked by the firewall that simply drops TCP SYN packets. For example, www.google.com:81.