upload_max_filesize = 8M;
post_max_size = 8M;
Imagine you already changed above values. But what happen when user try to upload large files greater than 8M ?
This is what happen, PHP shows this warning!
Warning: POST Content-Length of x bytes exceeds the limit of y bytes in Unknown on line 0
you can avoid it by adding
ob_get_contents();
ob_end_clean();
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
echo 'blah' . $_POST['fromPerson'];
}
Just restart your wamp server and then run php bin/magento cache:clean
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
If you absolutely have to add the property to the object, I believe you could cast it as an array, add your property (as a new array key), then cast it back as an object. The only time you run into stdClass
objects (I believe) is when you cast an array as an object or when you create a new stdClass
object from scratch (and of course when you json_decode()
something - silly me for forgetting!).
Instead of:
$foo = new StdClass();
$foo->bar = '1234';
You'd do:
$foo = array('bar' => '1234');
$foo = (object)$foo;
Or if you already had an existing stdClass object:
$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;
Also as a 1 liner:
$foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );
You can chain your where
s directly, without function(q)
. There's also a nice date handling package in laravel, called Carbon. So you could do something like:
$projects = Project::where('recur_at', '>', Carbon::now())
->where('recur_at', '<', Carbon::now()->addWeek())
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
Just make sure you require Carbon in composer and you're using Carbon namespace (use Carbon\Carbon;) and it should work.
EDIT: As Joel said, you could do:
$projects = Project::whereBetween('recur_at', array(Carbon::now(), Carbon::now()->addWeek()))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
You need this on all pages before you check for current sessions:
session_start();
Check if $_SESSION["loggedIn"
] (is not) true - If not, redirect them to the login page.
if($_SESSION["loggedIn"] != true){
echo 'not logged in';
header("Location: login.php");
exit;
}
For the lazy and the learning, to put it into your theme, Rfvgyhn's full code
<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>
I would strongly recommend using a library like PHPMailer to send emails.
It's easier and handles most of the issues automatically for you.
Regarding displaying embedded (inline) images, here's what's on their documentation:
Inline Attachments
There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with
<img src="cid:my-photo" alt="my-photo" />
.In detail, here is the function to add an inline attachment:
$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');
To give you a more complete example of how it would work:
<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->Port = 25; // set the SMTP port
$mail->SetFrom('[email protected]', 'First Last');
$mail->AddAddress('[email protected]', 'John Doe');
$mail->Subject = 'PHPMailer Test';
$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';
$mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
$mail->Send();
echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Regarding your comment, you asked how to send HTML email with embedded images, so I gave you an example of how to do that.
The library I told you about can send emails using a lot of methods other than SMTP.
Take a look at the PHPMailer Example page for other examples.
One way or the other, if you don't want to send the email in the ways supported by the library, you can (should) still use the library to build the message, then you send it the way you want.
For example:
You can replace the line that send the email:
$mail->Send();
With this:
$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want
Hope that helps. Let me know if you run into trouble using it.
Old question, but Guzzle adds the response within the exception object. So a simple try-catch on GuzzleHttp\Exception\ClientException
and then using getResponse
on that exception to see what 400-level error and continuing from there.
You can also just access $s1 like an array, if you only need to access it:
$s1 = "hello world";
echo $s1[0]; // -> h
It appears to only be availabe using the mysqlnd driver.
Try replacing it with the integer it represents; 1002, if I am not mistaken.
if the array looks like:
the $key will hold the type (fruit or vegetable) for each array value (orange, banana or carrot)
To avoid problems of character encoding in sending emails using the class PHPMailer we can configure it to send it with UTF-8 character encoding using the "CharSet" parameter, as we can see in the following Php code:
$mail = new PHPMailer();
$mail->From = '[email protected]';
$mail->FromName = 'Mi nombre';
$mail->AddAddress('[email protected]');
$mail->Subject = 'Prueba';
$mail->Body = '';
$mail->IsHTML(true);
// Active condition utf-8
$mail->CharSet = 'UTF-8';
// Send mail
$mail->Send();
you have to reason in terms of hased password:
store the password as md5('bob123');
when bob is register to your app
$query = "INSERT INTO users (username,password) VALUES('bob','".md5('bob123')."');
then, when bob is logging-in:
$query = "SELECT * FROM users WHERE username = 'bob' AND password = '".md5('bob123')."';
obvioulsy use variables for username and password, these queries are generated by php and then you can execute them on mysql
For those who are still getting blank response with $request->getContent()
, you can use:
$request->all()
e.g:
public function foo(Request $request){
$bodyContent = $request->all();
}
It worked fine with me,
$this->db->where("your_id !=",$your_id);
Or try this one,
$this->db->where("your_id <>",$your_id);
Or try this one,
$this->db->where("your_id IS NOT NULL");
all will work.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
this is just and slice of code, hope works for you
$ch = @curl_init();
@curl_setopt($ch, CURLOPT_URL, 'http://example.com');
@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
@curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = @curl_exec($ch);
$errno = @curl_errno($ch);
$error = @curl_error($ch);
$response = $response;
$info = @curl_getinfo($ch);
return $info['http_code'];
Had the same issue, because I forgot to go into my virtual machine. If I go to my local directory like this:
cd /www/homestead/my_project
php artisan migrate
that error will appear. But it works on my virtual machine
cd ~/homestead
vagrant ssh
cd /www/homestead/my_project
php artisan migrate
You dont have a function named assign()
, but a method with this name. PHP is not Java and in PHP you have to make clear, if you want to call a function
assign()
or a method
$object->assign()
In your case the call to the function resides inside another method. $this
always refers to the object, in which a method exists, itself.
$this->assign()
Dominc has the right idea, but put the calculation on the other side of the expression.
SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)
This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.
Because (amongst other reasons) it's much harder to ensure the input data is sanitized. If you use parametrized queries, as one does with PDO or mysqli you can entirely avoid the risk.
As an example, someone could use "enhzflep); drop table users"
as a username. The old functions will allow executing multiple statements per query, so something like that nasty bugger can delete a whole table.
If one were to use PDO of mysqli, the user-name would end-up being "enhzflep); drop table users"
.
See bobby-tables.com.
With explode function of php
$array=explode(" ",$str);
This is a quick example for you http://codepad.org/Pbg4n76i
This should work:
echo basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
But beware of any malicious parts in your URL.
Cache::flush(); https://laravel.com/docs/5.7/cache#events This work in the class Handler extends ExceptionHandler
You have to select and send the form data as well:
$("#post-btn").click(function(){
$.post("process.php", $("#reg-form").serialize(), function(data) {
alert(data);
});
});
Take a look at the documentation for the jQuery serialize
method, which encodes the data from the form fields into a data-string to be sent to the server.
In Web-"MVC" you can do whatever you please.
The original concept (1) described the model as the business logic. It should represent the application state and enforce some data consistency. That approach is often described as "fat model".
Most PHP frameworks follow a more shallow approach, where the model is just a database interface. But at the very least these models should still validate the incoming data and relations.
Either way, you're not very far off if you separate the SQL stuff or database calls into another layer. This way you only need to concern yourself with the real data/behaviour, not with the actual storage API. (It's however unreasonable to overdo it. You'll e.g. never be able to replace a database backend with a filestorage if that wasn't designed ahead.)
its just a warning use:
error_reporting(0);
it shows when we do not initialize array and direct assigning value to indexes.
somefunction{
$raja[0]="this";
$raja[1]="that";
}
instead :
somefunction{
$raja=array(0=>'this',1='that');
//or
$raja=array("this","that");
}
it just notification, do not generate any output error or any unexpected output.
You could try
<script type="text/javascript">
myvar = unescape('<?=rawurlencode($myvar)?>');
</script>
add this code in .htaccess (as an alternative of php.ini / ini_set function):
<IfModule mod_php5.c>
php_flag log_errors on
php_value error_log ./path_to_MY_PHP_ERRORS.log
# php_flag display_errors on
</IfModule>
* as commented: this is for Apache-type servers, and not for Nginx or others.
You can set 'url' => 'https://youDomain.com'
in config/app.php
or you could use a middleware class Laravel 5 - redirect to HTTPS.
Use subDays()
method:
$users = Users::where('status_id', 'active')
->where( 'created_at', '>', Carbon::now()->subDays(30))
->get();
Otro example, custom Data Pagination for JOIN
CODE in Controller CakePHP 2.6 is OK:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
'conditions'=>array(
'Clientes.requiere_senasa'=>1
),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
OR Example 2, NOT active conditions:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id',
'Clientes.requiere_senasa = 1'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
//'conditions'=>array(
// 'Clientes.requiere_senasa'=>1
//),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
Yes. You will need some things tho:
See khtmld(aemon) on *nx. See Url2Jpg for Windows but since it is dotNet app you should also chek Url2Bmp
Both are console tools that u can utilise from your web app to get the screenshot.
There are also web services that offer it. Check this out for example.
Edit:
This link is useful to.
All those special php expressions, in spirit of first day of ...
are great, though they go out of my head time and again.
So I decided to build a couple of basic datetime abstractions and tons of specific implementation which are auto-completed by any IDE. The point is to find what-kind of things. Like, today
, now
, the first day of a previous month
, etc. All of those things I've listed are datetimes. Hence, there is an interface or abstract class called ISO8601DateTime
, and specific datetimes which implement it.
The code in your particular case looks like that:
(new TheFirstDayOfThisMonth(new Now()))->value();
For more about this approach, take a look at this entry.
Please try this
error_reporting = E_ALL & ~E_NOTICE
in php.ini
You can read about jQuery Ajax from official jQuery Site: https://api.jquery.com/jQuery.ajax/
If you don't want to use any click event then you can set timer for periodically update.
Below code may be help you just example.
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
Above function will call after every 10 seconds and get content from response.php and update in #some_div
.
I think the only cookie you need is JSESSIONID=xxx..
Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.
There is already answer with Error Control Operator but it lacks of explanation. You can use @
operator with every expression and it hides errors (except of Fatal Errors).
@$test['test']; //PHP Notice: Undefined variable: test
@(14/0); // PHP Warning: Division by zero
//This is not working. You can't hide Fatal Errors this way.
@customFuntion(); // PHP Fatal error: Uncaught Error: Call to undefined function customFuntion()
For debugging it's fast and perfect method. But you should never ever use it on production nor permanent include in your local version. It will give you a lot of unnecessary irritation.
You should consider instead:
1. Error reporting settings as mentioned in accepted answer.
error_reporting(E_ERROR | E_PARSE);
or from PHP INI settings
ini_set('display_errors','Off');
2. Catching exceptions
try {
$var->method();
} catch (Error $e) {
// Handle error
echo $e->getMessage();
}
What about using something that is already implemented in Core?
//Clean non UTF-8 characters
Mage::getHelper('core/string')->cleanString($str)
Or one of the core url/ url rewrite methods..
Your curl gets timed out. Probably the url you are trying that requires more that 30 seconds.
If you are running the script through browser, then set the set_time_limit
to zero for infinite seconds.
set_time_limit(0);
Increase the curl's operation time limit using this option CURLOPT_TIMEOUT
curl_setopt($ch, CURLOPT_TIMEOUT,500); // 500 seconds
It can also happen for infinite redirection from the server. To halt this try to run the script with follow location disabled.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
This is the solution that I've came up with:
<form name = "form1" id = "form1" action = "#" method = "post">
<select name = "DropDownList1" id = "DropDownList1">
<?php
$arr = array('Yes', 'No', 'Fine' ); // create array so looping is easier
for( $i = 1; $i <= 3; $i++ ) // loop starts at first value and ends at last value
{
$selected = ''; // keep selected at nothing
if( isset( $_POST['go'] ) ) // check if form was submitted
{
if( $_POST['DropDownList1'] == $i ) // if the value of the dropdownlist is equal to the looped variable
{
$selected = 'selected = "selected"'; // if is equal, set selected = "selected"
}
}
// note: if value is not equal, selected stays defaulted to nothing as explained earlier
echo '<option value = "' . $i . '"' . $selected . '>' . $arr[$i] . '</option>'; // echo the option element to the page using the $selected variable
}
?>
</select> <!-- finish the form in html -->
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
</form>
The code I have works as long as the values are integers in some numeric order ( ascending or descending ). What it does is starts the dropdownlist in html, and adds each option element in php code. It will not work if you have random values though, i.e: 1, 4, 2, 7, 6. Each value must be unique.
Try this:
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/images/";
if (is_dir($upload_dir) && is_writable($upload_dir)) {
// do upload logic here
} else {
echo 'Upload directory is not writable, or does not exist.';
}
This will instantly flag any file permission errors.
Just simply add or die(mysqli_error($db));
at the end of your query, this will print the mysqli error.
mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));
As a side note I'd say you are at risk of mysql injection
, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
You can use html5 tag to download the image directly
<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."' download>donload</a> ";
?>
For more information, check this link http://www.w3schools.com/tags/att_a_download.asp
you can do that (work in mysql) probably other SQL too.. just try this:
select * from table where concat(' ',first_name,last_name)
like '%$search_term%';
i18n :
function getAge($birthdate, $pattern = 'eu')
{
$patterns = array(
'eu' => 'd/m/Y',
'mysql' => 'Y-m-d',
'us' => 'm/d/Y',
);
$now = new DateTime();
$in = DateTime::createFromFormat($patterns[$pattern], $birthdate);
$interval = $now->diff($in);
return $interval->y;
}
// Usage
echo getAge('05/29/1984', 'us');
// return 28
Try this. If I got any error on any file then I got error mail on my email id. Create two files index.php
and checkErrorEmail.php
and uploaded them to your server. Then load index.php
with your browser.
Index.php
<?php
include('checkErrorEmail.php');
include('dereporting.php');
$temp;
echo 'hi '.$temp;
?>
checkErrorEmail.php
<?php
// Destinations
define("ADMIN_EMAIL", "[email protected]");
//define("LOG_FILE", "/my/home/errors.log");
// Destination types
define("DEST_EMAIL", "1");
//define("DEST_LOGFILE", "3");
/* Examples */
// Send an e-mail to the administrator
//error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);
// Write the error to our log file
//error_log("Error", DEST_LOGFILE, LOG_FILE);
/**
* my_error_handler($errno, $errstr, $errfile, $errline)
*
* Author(s): thanosb, ddonahue
* Date: May 11, 2008
*
* custom error handler
*
* Parameters:
* $errno: Error level
* $errstr: Error message
* $errfile: File in which the error was raised
* $errline: Line at which the error occurred
*/
function my_error_handler($errno, $errstr, $errfile, $errline)
{
echo "<br><br><br><br>errno ".$errno.",<br>errstr ".$errstr.",<br>errfile ".$errfile.",<br>errline ".$errline;
if($errno)
{
error_log("Error: $errstr \n error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
}
/*switch ($errno) {
case E_USER_ERROR:
// Send an e-mail to the administrator
error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
// Write the error to our log file
//error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
break;
case E_USER_WARNING:
// Write the error to our log file
//error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
case E_USER_NOTICE:
// Write the error to our log file
// error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
default:
// Write the error to our log file
//error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
}*/
// Don't execute PHP's internal error handler
return TRUE;
}
// Use set_error_handler() to tell PHP to use our method
$old_error_handler = set_error_handler("my_error_handler");
?>
Surely using array_map
and if using a container implementing ArrayAccess
to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN()
clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait
cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr
you could always $arr = array_map
and be explicit.
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
This will work with either an array, an object or a variable and also escapes the special characters that may break your JS :
function debugToConsole($msg) {
echo "<script>console.log(".json_encode($msg).")</script>";
}
Edit : Added json_encode
to the echo
statement. This will prevent your script from breaking if there are quotes in your $msg
variable.
You should run:
composer dump-autoload
and if does not work you should:
re-install composer
I had the same error, but in my case the problem was that my application was using multiple first-level domains, while the cookie was using one. Removing cookie_domain: ".%domain%"
from framework.session
in the config.yml
caused cookies to default to whatever domain the form was on, and that fixed the problem.
It shows the problem it was the White spaces in App Name of .env file
You can use print_r
, var_dump
and var_export
funcations of php:
print_r
: Convert into human readble form
<?php
echo "<pre>";
print_r($results);
echo "</pre>";
?>
var_dump()
: will show you the type of the thing as well as what's in it.
var_dump($results);
foreach loop
: using for each loop you can iterate each and every value of an array.
foreach($results['data'] as $result) {
echo $result['type'].'<br>';
}
$givenday = date("w", mktime(0, 0, 0, MM, dd, yyyy));
This gives you the day of the week of the given date itself where 0
= Sunday and 6
= Saturday. From there you can simply calculate backwards to the day you want.
Be aware that HttpOnly doesn't stop cross-site scripting; instead, it neutralizes one possible attack, and currently does that only on IE (FireFox exposes HttpOnly cookies in XmlHttpRequest, and Safari doesn't honor it at all). By all means, turn HttpOnly on, but don't drop even an hour of output filtering and fuzz testing in trade for it.
You can send the array to this function:
function utf8_converter($array){
array_walk_recursive($array, function(&$item, $key){
if(!mb_detect_encoding($item, 'utf-8', true)){
$item = utf8_encode($item);
}
});
return $array;
}
It works for me.
For Issue C:\PHP\php-cgi.exe - The FastCGI process exited unexpectedly.
I resolved this by installing the Visual C++ Redistributable for Visual Studio 2015.(Microsoft Visual C++ 2015 Redistributable Update 3) and Visual C++ Redistributable for Visual Studio 2012 Update 4 in 32 and 64bit versions. and also make sure in php.info file cgi.fix_pathinfo=0 enabled.
Download library file Zebra_Image.php belo link
https://drive.google.com/file/d/0Bx-7K3oajNTRV1I2UzYySGZFd3M/view
resizeimage.php
<?php
require 'Zebra_Image.php';
// create a new instance of the class
$resize_image = new Zebra_Image();
// indicate a source image
$resize_image->source_path = $target_file1;
$ext = $photo;
// indicate a target image
$resize_image->target_path = 'images/thumbnil/' . $ext;
// resize
// and if there is an error, show the error message
if (!$resize_image->resize(200, 200, ZEBRA_IMAGE_NOT_BOXED, -1));
// from this moment on, work on the resized image
$resize_image->source_path = 'images/thumbnil/' . $ext;
?>
First you create a MySQL table to store images, like for example:
create table testblob (
image_id tinyint(3) not null default '0',
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_ctgy varchar(25) not null default '',
image_name varchar(50) not null default ''
);
Then you can write an image to the database like:
/***
* All of the below MySQL_ commands can be easily
* translated to MySQLi_ with the additions as commented
***/
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli
// $link = mysqli_connect("localhost", $username, $password,$dbname);
$sql = sprintf("INSERT INTO testblob
(image_type, image, image_size, image_name)
VALUES
('%s', '%s', '%d', '%s')",
/***
* For all mysqli_ functions below, the syntax is:
* mysqli_whartever($link, $functionContents);
***/
mysql_real_escape_string($size['mime']),
mysql_real_escape_string($imgData),
$size[3],
mysql_real_escape_string($_FILES['userfile']['name'])
);
mysql_query($sql);
You can display an image from the database in a web page with:
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);
One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.
To echo elements of array properly, you can use the function, implode(separator, array)
Example:
implode(' ', $var)
result:
first name[1], last name[1]
first name[2], last name[2]
More examples from W3C.
Another option would be file_get_contents()
:
// $xml_str = your xml
// $url = target url
$post_data = array('xml' => $xml_str);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
Thanks to this thread, and especially budidino because his code is what drove it home for me. Just wanted to contribute how to retrieve the JSON data from a request. Make changes to "//create request" request array part of the code to perform different requests. Ultimately, this will output the JSON onto the browser screen
<?php
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
function returnTweet(){
$oauth_access_token = "2602299919-lP6mgkqAMVwvHM1L0Cplw8idxJzvuZoQRzyMkOx";
$oauth_access_token_secret = "wGWny2kz67hGdnLe3Uuy63YZs4nIGs8wQtCU7KnOT5brS";
$consumer_key = "zAzJRrPOj5BvOsK5QhscKogVQ";
$consumer_secret = "Uag0ujVJomqPbfdoR2UAWbRYhjzgoU9jeo7qfZHCxR6a6ozcu1";
$twitter_timeline = "user_timeline"; // mentions_timeline / user_timeline / home_timeline / retweets_of_me
// create request
$request = array(
'screen_name' => 'burownrice',
'count' => '3'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
// merge request and oauth to one array
$oauth = array_merge($oauth, $request);
// do some magic
$base_info = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// make request
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
return $json;
}
$tweet = returnTweet();
echo $tweet;
?>
You can use the fgets()
function to read the file line by line:
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
}
fclose($handle);
} else {
// error opening the file.
}
Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.
They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.
you can use 'use' in function like bellow example
function page_properties($objPortal) use($objPage){
$objPage->set_page_title($myrow['title']);
}
You can always use the ( <condition> ? <value if true> : <value if false> )
syntax (it's called the ternary operator - thanks to Mark for remining me :) ).
If <condition>
is true, the statement would be evaluated as <value if true>
. If not, it would be evaluated as <value if false>
For instance:
$fourteen = 14;
$twelve = 12;
echo "Fourteen is ".($fourteen > $twelve ? "more than" : "not more than")." twelve";
This is the same as:
$fourteen = 14;
$twelve = 12;
if($fourteen > 12) {
echo "Fourteen is more than twelve";
}else{
echo "Fourteen is not more than twelve";
}
type on terminal:
nano ~/.bash_profile
then paste:
export PATH="/Users/yourusername/.composer/vendor/bin:$PATH"
then save (press ctrl+c, press Y, press enter)
now you are ready to use "laravel" on your terminal
Add
session_start();
at the beginning of your page before any HTML
You will have something like :
<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...
Don't forget to remove the space you have before
explode
has some very big problems in real life usage:
count(explode(',', null)); // 1 !!
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8
this is why i prefer preg_split
preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)
the entire boilerplate:
/** @brief wrapper for explode
* @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
* @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
* @param string $delimiter default ','
* @return array|mixed
*/
public static function explode($val, $as_is = false, $delimiter = ',')
{
// using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
return (is_string($val) || is_int($val)) ?
preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
:
($as_is ? $val : (is_array($val) ? $val : []));
}
<?
ob_start(); // ensures anything dumped out will be caught
// do stuff here
$url = 'http://example.com/thankyou.php'; // this can be set based on whatever
// clear out the output buffer
while (ob_get_status())
{
ob_end_clean();
}
// no redirect
header( "Location: $url" );
?>
jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.
You can access those values with the global $_GET variable
//www.example.com/index.php?id=7
print $_GET['id']; // prints "7"
You should check all "incoming" user data - so here, that "id" is an INT. Don't use it directly in your SQL (vulnerable to SQL injections).
As others already suggested, you can enable the "less secure" applications or you can simply switch from ssl
to tls
:
$mailer->Host = 'tls://smtp.gmail.com';
$mailer->SMTPAuth = true;
$mailer->Username = "[email protected]";
$mailer->Password = "***";
$mailer->SMTPSecure = 'tls';
$mailer->Port = 587;
When using tls
there's no need to grant access for less secure applications, just make sure, IMAP is enabled.
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
If anyone's still looking - Quercus has a war that allows to run PHP scripts in apache tomcat or glassfish. For a step by step guide look at this article
The other solutions here all have caveats (though they address the question at hand). If you are (1) looping over mixed-types or (2) want a generic solution that you can export as a function or include in your utilities, none of the other solutions here will work.
The simplest and most self-explanatory solution is:
// simplest, most-readable
if (is_bool($res) {
$res = $res ? 'true' : 'false';
}
// same as above but written more tersely
$res = is_bool($res) ? ($res ? 'true' : 'false') : $res;
// Terser still, but completely unnecessary function call and must be
// commented due to poor readability. What is var_export? What is its
// second arg? Why are we exporting stuff?
$res = is_bool($res) ? var_export($res, 1) : $res;
But most developers reading your code will require a trip to http://php.net/var_export to understand what the var_export
does and what the second param is.
var_export
Works for boolean
input but converts everything else to a string
as well.
// OK
var_export(false, 1); // 'false'
// OK
var_export(true, 1); // 'true'
// NOT OK
var_export('', 1); // '\'\''
// NOT OK
var_export(1, 1); // '1'
($res) ? 'true' : 'false';
Works for boolean input but converts everything else (ints, strings) to true/false.
// OK
true ? 'true' : 'false' // 'true'
// OK
false ? 'true' : 'false' // 'false'
// NOT OK
'' ? 'true' : 'false' // 'false'
// NOT OK
0 ? 'true' : 'false' // 'false'
json_encode()
Same issues as var_export
and probably worse since json_encode
cannot know if the string true
was intended a string or a boolean.
first of all,
be sure that there is a post
if(isset($_POST['username'])) {
// check if the username has been set
}
second, and most importantly, sanitize the data, meaning that
$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";
is deadly dangerous, instead use
$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";
and please research the subject sql injection
make sure you have correct path to extension folder
extension_dir = "ext"
by default it is commented with ; character
Default user for MySQL is "root", and server "localhost".
The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:
$data = [
"rs" => null
]
this above will work absolutely fine when used like:
$data["rs"] = 5;
But the below will throw a warning ::
$data = [
"rs" => [
"rs1" => null;
]
]
..
$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array
Install and run XAMPP: http://www.apachefriends.org/en/xampp.html
Just a sub answer:
Absolutely use translated urls with a language identifier in front of them: http://www.domain.com/nl/over-ons
Hybride solutions tend to get complicated, so I would just stick with it. Why? Cause the url is essential for SEO.
About the db translation: Is the number of languages more or less fixed? Or rather unpredictable and dynamic? If it is fixed, I would just add new columns, otherwise go with multiple tables.
But generally, why not use Drupal? I know everybody wants to build their own CMS cause it's faster, leaner, etc. etc. But that is just really a bad idea!
To read directory contents you can use readdir() and use a script, in my example download.php
, to download files
if ($handle = opendir('/path/to/your/dir/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
}
}
closedir($handle);
}
In download.php
you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php
$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;
if(!file_exists($file)){ // file does not exist
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($file);
}
You need to use the iconv package, specifically its iconv function.
You can use assertException extension to assert more than one exception during one test execution.
Insert method into your TestCase and use:
public function testSomething()
{
$test = function() {
// some code that has to throw an exception
};
$this->assertException( $test, 'InvalidArgumentException', 100, 'expected message' );
}
I also made a trait for lovers of nice code..
Yes, you need OpenSSL to work correctly. My backup testing site worked, my live server didn't. Difference? Live server didn't have OpenSSL within PHP configuration.
A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.
Try disabling all non-essential modules (in php.ini
), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.
If that doesn't help, you should report a php bug.
MAMP takes only two highest versions of the PHP in the following folder /Application/MAMP/bin/php
As you can see here highest versions are 7.0.10 and 5.6.25
Now 7.0.10 version is removed and as you can see highest two versions are 5.6.25 and 5.5.38 as shown in preferences
You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY
to your curl_setopt_array
method.
For example:
$proxy = '127.0.0.1:8888';
$opt = array (
CURLOPT_URL => "http://www.example.com",
CURLOPT_PROXY => $proxy,
CURLOPT_POST => true,
CURLOPT_VERBOSE => true,
);
$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);
As this is the first result on google for "php mysql transaction", I thought I'd add an answer that explicitly demonstrates how to do this with mysqli (as the original author wanted examples). Here's a simplified example of transactions with PHP/mysqli:
// let's pretend that a user wants to create a new "group". we will do so
// while at the same time creating a "membership" for the group which
// consists solely of the user themselves (at first). accordingly, the group
// and membership records should be created together, or not at all.
// this sounds like a job for: TRANSACTIONS! (*cue music*)
$group_name = "The Thursday Thumpers";
$member_name = "EleventyOne";
$conn = new mysqli($db_host,$db_user,$db_passwd,$db_name); // error-check this
// note: this is meant for InnoDB tables. won't work with MyISAM tables.
try {
$conn->autocommit(FALSE); // i.e., start transaction
// assume that the TABLE groups has an auto_increment id field
$query = "INSERT INTO groups (name) ";
$query .= "VALUES ('$group_name')";
$result = $conn->query($query);
if ( !$result ) {
$result->free();
throw new Exception($conn->error);
}
$group_id = $conn->insert_id; // last auto_inc id from *this* connection
$query = "INSERT INTO group_membership (group_id,name) ";
$query .= "VALUES ('$group_id','$member_name')";
$result = $conn->query($query);
if ( !$result ) {
$result->free();
throw new Exception($conn->error);
}
// our SQL queries have been successful. commit them
// and go back to non-transaction mode.
$conn->commit();
$conn->autocommit(TRUE); // i.e., end transaction
}
catch ( Exception $e ) {
// before rolling back the transaction, you'd want
// to make sure that the exception was db-related
$conn->rollback();
$conn->autocommit(TRUE); // i.e., end transaction
}
Also, keep in mind that PHP 5.5 has a new method mysqli::begin_transaction. However, this has not been documented yet by the PHP team, and I'm still stuck in PHP 5.3, so I can't comment on it.
I found a solution that works exactly how I want.
I changed
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');
To
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('userfile', 'Document', 'required');
}
print_r pretty print for PHP
function print_nice($elem,$max_level=10,$print_nice_stack=array()){
if(is_array($elem) || is_object($elem)){
if(in_array($elem,$print_nice_stack,true)){
echo "<font color=red>RECURSION</font>";
return;
}
$print_nice_stack[]=&$elem;
if($max_level<1){
echo "<font color=red>nivel maximo alcanzado</font>";
return;
}
$max_level--;
echo "<table border=1 cellspacing=0 cellpadding=3 width=100%>";
if(is_array($elem)){
echo '<tr><td colspan=2 style="background-color:#333333;"><strong><font color=white>ARRAY</font></strong></td></tr>';
}else{
echo '<tr><td colspan=2 style="background-color:#333333;"><strong>';
echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></td></tr>';
}
$color=0;
foreach($elem as $k => $v){
if($max_level%2){
$rgb=($color++%2)?"#888888":"#BBBBBB";
}else{
$rgb=($color++%2)?"#8888BB":"#BBBBFF";
}
echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">';
echo '<strong>'.$k."</strong></td><td>";
print_nice($v,$max_level,$print_nice_stack);
echo "</td></tr>";
}
echo "</table>";
return;
}
if($elem === null){
echo "<font color=green>NULL</font>";
}elseif($elem === 0){
echo "0";
}elseif($elem === true){
echo "<font color=green>TRUE</font>";
}elseif($elem === false){
echo "<font color=green>FALSE</font>";
}elseif($elem === ""){
echo "<font color=green>EMPTY STRING</font>";
}else{
echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem);
}
}
You can also make use of FilesystemIterator
. It requires even less code then DirectoryIterator
, and automatically removes .
and ..
.
// Let's traverse the images directory
$fileSystemIterator = new FilesystemIterator('images');
$entries = array();
foreach ($fileSystemIterator as $fileInfo){
$entries[] = $fileInfo->getFilename();
}
var_dump($entries);
//OUTPUT
object(FilesystemIterator)[1]
array (size=14)
0 => string 'aa[1].jpg' (length=9)
1 => string 'Chrysanthemum.jpg' (length=17)
2 => string 'Desert.jpg' (length=10)
3 => string 'giphy_billclinton_sad.gif' (length=25)
4 => string 'giphy_shut_your.gif' (length=19)
5 => string 'Hydrangeas.jpg' (length=14)
6 => string 'Jellyfish.jpg' (length=13)
7 => string 'Koala.jpg' (length=9)
8 => string 'Lighthouse.jpg' (length=14)
9 => string 'Penguins.jpg' (length=12)
10 => string 'pnggrad16rgb.png' (length=16)
11 => string 'pnggrad16rgba.png' (length=17)
12 => string 'pnggradHDrgba.png' (length=17)
13 => string 'Tulips.jpg' (length=10)
WordPress include tags, categories and taxonomies in search results
This code is taken from http://atiblog.com/custom-search-results/
Some functions here are taken from twentynineteen theme.Because it is made on this theme.
This code example will help you to include tags, categories or any custom taxonomy in your search. And show the posts contaning these tags or categories.
You need to modify your search.php of your theme to do so.
<?php
$search=get_search_query();
$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) );
$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );
//if you have any custom taxonomy
$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );
$mcat=array();
$mtag=array();
$mcustom_taxonomy=array();
foreach($all_categories as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}
foreach($all_tags as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}
foreach($all_custom_taxonomy as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcustom_taxonomy,$all->term_id);
}
}
$matched_posts=array();
$args1= array( 'post_status' => 'publish','posts_per_page' => -1,'tax_query' =>array('relation' => 'OR',array('taxonomy' => 'category','field' => 'term_id','terms' =>$mcat),array('taxonomy' => 'post_tag','field' => 'term_id','terms' =>$mtag),array('taxonomy' => 'custom_taxonomy','field' => 'term_id','terms' =>$mcustom_taxonomy)));
$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($matched_posts,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {
}
?>
<?php
// now we will do the normal wordpress search
$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
array_push($matched_posts,get_the_id());
}
wp_reset_postdata();
} else {
}
$matched_posts= array_unique($matched_posts);
$matched_posts=array_values(array_filter($matched_posts));
//print_r($matched_posts);
?>
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );
if ( $query3->have_posts() ) {
while ( $query3->have_posts() ) {
$query3->the_post();
get_template_part( 'template-parts/content/content', 'excerpt' );
}
twentynineteen_the_posts_navigation();
wp_reset_postdata();
} else {
}
?>
If d is a dictionary, then d.get(k, v)
means, give me the value of k in d, unless k isn't there, in which case give me v. It's being used here to get the current count of the character, which should start at 0 if the character hasn't been encountered before.
For Bash 3, there is a particular case that has a nice and simple solution:
If you don't want to handle a lot of variables, or keys are simply invalid variable identifiers, and your array is guaranteed to have less than 256 items, you can abuse function return values. This solution does not require any subshell as the value is readily available as a variable, nor any iteration so that performance screams. Also it's very readable, almost like the Bash 4 version.
Here's the most basic version:
hash_index() {
case $1 in
'foo') return 0;;
'bar') return 1;;
'baz') return 2;;
esac
}
hash_vals=("foo_val"
"bar_val"
"baz_val");
hash_index "foo"
echo ${hash_vals[$?]}
Remember, use single quotes in case
, else it's subject to globbing. Really useful for static/frozen hashes from the start, but one could write an index generator from a hash_keys=()
array.
Watch out, it defaults to the first one, so you may want to set aside zeroth element:
hash_index() {
case $1 in
'foo') return 1;;
'bar') return 2;;
'baz') return 3;;
esac
}
hash_vals=("", # sort of like returning null/nil for a non existent key
"foo_val"
"bar_val"
"baz_val");
hash_index "foo" || echo ${hash_vals[$?]} # It can't get more readable than this
Caveat: the length is now incorrect.
Alternatively, if you want to keep zero-based indexing, you can reserve another index value and guard against a non-existent key, but it's less readable:
hash_index() {
case $1 in
'foo') return 0;;
'bar') return 1;;
'baz') return 2;;
*) return 255;;
esac
}
hash_vals=("foo_val"
"bar_val"
"baz_val");
hash_index "foo"
[[ $? -ne 255 ]] && echo ${hash_vals[$?]}
Or, to keep the length correct, offset index by one:
hash_index() {
case $1 in
'foo') return 1;;
'bar') return 2;;
'baz') return 3;;
esac
}
hash_vals=("foo_val"
"bar_val"
"baz_val");
hash_index "foo" || echo ${hash_vals[$(($? - 1))]}
I found one way to access the shared folder without giving the username and password.
We need to change the share folder protect settings in the machine where the folder has been shared.
Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.
By doing the above settings we can access the shared folder without any username/password.
Just Remove the the Workstation Components from Add/Remove Programs - SQL Server 2005. Removing Workstation Components, SQL Server 2008 installation goes well.
It works for me.
git remote add origin https://github.com/repo.git
git push origin master
add the repository URL to the origin in the local working directory
I had a similar issue when working on Database restore operation on MS SQL Server 2012.
However, for my own scenario, I just needed to see the progress of the DATABASE RESTORE operation in the script window
All I had to do was add the STATS option to the script:
USE master;
GO
ALTER DATABASE mydb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
RESTORE DATABASE mydb
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_21-08-2020.bak'
WITH REPLACE,
STATS = 10,
RESTART,
MOVE 'my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\my_db.mdf',
MOVE 'my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\mydb_log.ldf'
GO
ALTER DATABASE mydb SET MULTI_USER;
GO
And then I switched to the Messages tab of the Script window to see the progress of the DATABASE RESTORE operation:
If you want to get more information after the DATABASE RESTORE operation you can use this command suggested by eythort:
SELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command = 'RESTORE DATABASE'
That's all.
I hope this helps
There would be two ways to define constants - const
and static final
, with the exact same semantics. Furthermore static final
describes the behaviour better than const
You don't really need to do it all in jQuery to do that smoothly. Do it like this:
$(".nextbutton").click(function() {
document.forms["form1"].submit();
});
It is possible to use only one variable:
var timer = -performance.now();
// Do something
timer += performance.now();
console.log("Time: " + (timer/1000).toFixed(5) + " sec.")
timer/1000
- to convert milliseconds to seconds
.toFixed(5)
- to trim extra digits
With Ubuntu I could not get the proxy option to work as advertised – so following command did not work:
sudo pip --proxy http://web-proxy.mydomain.com install somepackage
But exporting the https_proxy
environment variable (note its https_proxy
not http_proxy
) did the trick:
export https_proxy=http://web-proxy.mydomain.com
then
sudo -E pip install somepackage
Datatype 'bigint unsigned' may suit this requirement.
OpenSSL is quite difficult. It's easy to accidentally throw away all your security by not doing negotiation exactly right. (Heck, I've been personally bitten by a bug where curl wasn't reading the OpenSSL alerts exactly right, and couldn't talk to some sites.)
If you really want quick and simple, put stud in front of your program an call it a day. Having SSL in a different process won't slow you down: http://vincent.bernat.im/en/blog/2011-ssl-benchmark.html
Use the function Contains
from the strings package.
import (
"strings"
)
strings.Contains("something", "some") // true
Using code from there.
I would write:
myArray.enumerable().selectMany(function(x) { return x; }).array()
Quoting from the language specs:Iota
Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. It is reset to 0 whenever the reserved word const appears in the source and increments after each ConstSpec. It can be used to construct a set of related constants:
const ( // iota is reset to 0
c0 = iota // c0 == 0
c1 = iota // c1 == 1
c2 = iota // c2 == 2
)
const (
a = 1 << iota // a == 1 (iota has been reset)
b = 1 << iota // b == 2
c = 1 << iota // c == 4
)
const (
u = iota * 42 // u == 0 (untyped integer constant)
v float64 = iota * 42 // v == 42.0 (float64 constant)
w = iota * 42 // w == 84 (untyped integer constant)
)
const x = iota // x == 0 (iota has been reset)
const y = iota // y == 0 (iota has been reset)
Within an ExpressionList, the value of each iota is the same because it is only incremented after each ConstSpec:
const (
bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0
bit1, mask1 // bit1 == 2, mask1 == 1
_, _ // skips iota == 2
bit3, mask3 // bit3 == 8, mask3 == 7
)
This last example exploits the implicit repetition of the last non-empty expression list.
So your code might be like
const (
A = iota
C
T
G
)
or
type Base int
const (
A Base = iota
C
T
G
)
if you want bases to be a separate type from int.
For those who need save objects like {foo: 'bar'}, I share my edited version of @KevinBurke's answer. I've added JSON.stringify and JSON.parse, that's all.
cookie = {
set: function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else
var expires = "";
document.cookie = name + "=" + JSON.stringify(value) + expires + "; path=/";
},
get : function(name){
var nameEQ = name + "=",
ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return JSON.parse(c.substring(nameEQ.length,c.length));
}
return null;
}
}
So, now you can do things like this:
cookie.set('cookie_key', {foo: 'bar'}, 30);
cookie.get('cookie_key'); // {foo: 'bar'}
cookie.set('cookie_key', 'baz', 30);
cookie.get('cookie_key'); // 'baz'
Following code from here is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP).
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* This class provide various static methods that relax X509 certificate and
* hostname verification while using the SSL over the HTTP protocol.
*
* @author Jiramot.info
*/
public final class SSLUtilities {
/**
* Hostname verifier for the Sun's deprecated API.
*
* @deprecated see {@link #_hostnameVerifier}.
*/
private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
/**
* Thrust managers for the Sun's deprecated API.
*
* @deprecated see {@link #_trustManagers}.
*/
private static com.sun.net.ssl.TrustManager[] __trustManagers;
/**
* Hostname verifier.
*/
private static HostnameVerifier _hostnameVerifier;
/**
* Thrust managers.
*/
private static TrustManager[] _trustManagers;
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames. This method uses the old deprecated API from the
* com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHostnames()}.
*/
private static void __trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (__hostnameVerifier == null) {
__hostnameVerifier = new SSLUtilities._FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier
com.sun.net.ssl.HttpsURLConnection
.setDefaultHostnameVerifier(__hostnameVerifier);
} // __trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones. This method uses the
* old deprecated API from the com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHttpsCertificates()}.
*/
private static void __trustAllHttpsCertificates() {
com.sun.net.ssl.SSLContext context;
// Create a trust manager that does not validate certificate chains
if (__trustManagers == null) {
__trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager
try {
context = com.sun.net.ssl.SSLContext.getInstance("SSL");
context.init(null, __trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // __trustAllHttpsCertificates
/**
* Return true if the protocol handler property java. protocol.handler.pkgs
* is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated
* one, false otherwise.
*
* @return true if the protocol handler property is set to the Sun's
* deprecated one, false otherwise.
*/
private static boolean isDeprecatedSSLProtocol() {
return ("com.sun.net.ssl.internal.www.protocol".equals(System
.getProperty("java.protocol.handler.pkgs")));
} // isDeprecatedSSLProtocol
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
private static void _trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (_hostnameVerifier == null) {
_hostnameVerifier = new SSLUtilities.FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier:
HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
} // _trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
private static void _trustAllHttpsCertificates() {
SSLContext context;
// Create a trust manager that does not validate certificate chains
if (_trustManagers == null) {
_trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager:
try {
context = SSLContext.getInstance("SSL");
context.init(null, _trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // _trustAllHttpsCertificates
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
public static void trustAllHostnames() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHostnames();
} else {
_trustAllHostnames();
} // else
} // trustAllHostnames
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
public static void trustAllHttpsCertificates() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHttpsCertificates();
} else {
_trustAllHttpsCertificates();
} // else
} // trustAllHttpsCertificates
/**
* This class implements a fake hostname verificator, trusting any host
* name. This class uses the old deprecated API from the com.sun. ssl
* package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
*/
public static class _FakeHostnameVerifier implements
com.sun.net.ssl.HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, String session) {
return (true);
} // verify
} // _FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates. This
* class uses the old deprecated API from the com.sun.ssl package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
*/
public static class _FakeX509TrustManager implements
com.sun.net.ssl.X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always return true, trusting for client SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isClientTrusted(X509Certificate[] chain) {
return (true);
} // checkClientTrusted
/**
* Always return true, trusting for server SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isServerTrusted(X509Certificate[] chain) {
return (true);
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // _FakeX509TrustManager
/**
* This class implements a fake hostname verificator, trusting any host
* name.
*
* @author Jiramot.info
*/
public static class FakeHostnameVerifier implements HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
return (true);
} // verify
} // FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates.
*
* @author Jiramot.info
*/
public static class FakeX509TrustManager implements X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always trust for client SSL chain peer certificate chain with any
* authType authentication types.
*
* @param chain the peer certificate chain.
* @param authType the authentication type based on the client
* certificate.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType) {
} // checkClientTrusted
/**
* Always trust for server SSL chain peer certificate chain with any
* authType exchange algorithm types.
*
* @param chain the peer certificate chain.
* @param authType the key exchange algorithm used.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType) {
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // FakeX509TrustManager
} // SSLUtilities
Since I have encoding ISO-8859-1 operating system the date format "dd.MM.yyyy HH:mm:sss" was not recognised what did work was to use InvariantCulture string.
string url = "GetData?DagsPr=" + DagsProfs.ToString(CultureInfo.InvariantCulture)
Install virtual env with
virtualenv --system-site-packages
and use pip install -U to install matplotlib
The hide_code extension allows you to hide individual cells, and/or the prompts next to them. Install as
pip3 install hide_code
Visit https://github.com/kirbs-/hide_code/ for more info about this extension.
If you want to show error messages on form submission, you can use condition form.$submitted
to check if an attempt was made to submit the form. Check following example.
<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
<input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
<div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
<div ng-message="required">Please enter user name.</div>
</div>
<input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
<div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
<div ng-message="required">Please enter user address.</div>
<div ng-message="maxlength">Should be less than 30 chars</div>
</div>
<button type="submit">
Create user
</button>
</form>
In addition for the accepted answer you'll need the following permissions into your AndroidManifest to get it working:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
The syntax above doesn't work in Interbase 2007. Instead, I had to use something like:
DELETE FROM TableA a WHERE [filter condition on TableA]
AND (a.BId IN (SELECT a.BId FROM TableB b JOIN TableA a
ON a.BId = b.BId
WHERE [filter condition on TableB]))
(Note Interbase doesn't support the AS keyword for aliases)
cd to sessions directory and then:
1) View sessions older than 40 min:
find . -amin +40 -exec stat -c "%n %y" {} \;
2) Remove sessions older than 40 min:
find . -amin +40 -exec rm {} \;
Finally, i solved the problem by using following way, in which the position of the spinner can be get by its string
private int getPostiton(String locationid,Cursor cursor)
{
int i;
cursor.moveToFirst();
for(i=0;i< cursor.getCount()-1;i++)
{
String locationVal = cursor.getString(cursor.getColumnIndex(RoadMoveDataBase.LT_LOCATION));
if(locationVal.equals(locationid))
{
position = i+1;
break;
}
else
{
position = 0;
}
cursor.moveToNext();
}
Calling the method
Spinner location2 = (Spinner)findViewById(R.id.spinner1);
int location2id = getPostiton(cursor.getString(3),cursor);
location2.setSelection(location2id);
I hope it will help for some one..
One word: Don't.
OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?
You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).
I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)
It really depends on what algorithms you need to implement, there is no silver bullet (and that's shouldn't be a surprise... the general rule about programming is that there's no general rule ;-) ).
I often end up representing directed multigraphs using node/edge structures with pointers... more specifically:
struct Node
{
... payload ...
Link *first_in, *last_in, *first_out, *last_out;
};
struct Link
{
... payload ...
Node *from, *to;
Link *prev_same_from, *next_same_from,
*prev_same_to, *next_same_to;
};
In other words each node has a doubly-linked list of incoming links and a doubly-linked list of outgoing links. Each link knows from
and to
nodes and is at the same time in two different doubly-linked lists: the list of all links coming out from the same from
node and the list of all links arriving at the same to
node.
The pointers prev_same_from
and next_same_from
are used when following the chain of all the links coming out from the same node; the pointers prev_same_to
and next_same_to
are instead used when managing the chain of all the links pointing to the same node.
It's a lot of pointer twiddling (so unless you love pointers just forget about this) but query and update operations are efficient; for example adding a node or a link is O(1), removing a link is O(1) and removing a node x is O(deg(x)).
Of course depending on the problem, payload size, graph size, graph density this approach can be way overkilling or too much demanding for memory (in addition to payload you've 4 pointers per node and 6 pointers per link).
A similar structure full implementation can be found here.
If array item and list item are same
List<object> list=myArray.ToList();
to Print JSON parsed object just type
console.log( JSON.stringify(data, null, " ") );
and you will get output very clear
$ rails g model Item name:string description:text product:references
I too found the guides difficult to use. Easy to understand, but hard to find what I am looking for.
Also, I have temp projects that I run the rails generate
commands on. Then once I get them working I run it on my real project.
Reference for the above code: http://guides.rubyonrails.org/getting_started.html#associating-models
you can store the uri as string
intent.putExtra("imageUri", imageUri.toString());
and then just convert the string back to uri like this
Uri myUri = Uri.parse(extras.getString("imageUri"));
your data snippet need to be expanded a little, and it has to be this way to be proper json. notice I just include the array name attribute "item"
{"item":[
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}]}
your java script is simply
var objCount = json.item.length;
for ( var x=0; x < objCount ; xx++ ) {
var curitem = json.item[x];
}
In SL5 I found this to work:
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat=dd-MMMM-yy hh:mm}">
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat='Justification Date: \{0:dd-MMMM-yy hh:mm\}'}">
The simplest and also the most compact solution (for v2.3.3):
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValueAsString(obj)
Setting net.ipv6.conf.all.forwarding=1
will fix the issue.
This can be done on a live system using
sudo sysctl -w net.ipv6.conf.all.forwarding=1
As the error in code in conf file may vary (@Jacky Nguyen vs @H?NÐR? N???? answers),
the general solution answer would be to
a) correct the condition logic in conf file to make sense
(x)or b) install corrected/current phpmyadmin
As for a)
open the file with error code
For the terminal people: sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php
For the regular folks: sudo gedit /usr/share/phpmyadmin/libraries/sql.lib.php
find the condition - basically search for $analyzed_sql_results['select_expr']
now the logic should be to check whether this sub array is empty, or, whether it has just 1 element with a value "*
so basically the block
between && $analyzed_sql_results['select_from']
and && count($analyzed_sql_results['select_tables']) == 1
should look something like this
&& ( empty($analyzed_sql_results['select_expr']) //the sub array is empty, || //or, ( (count($analyzed_sql_results['select_expr']) == 1) //it has just 1 element && //and at the same time ($analyzed_sql_results['select_expr'][0] == '*') //the 1 element value is "*" ) )
one posibility: catch the exception and show an error message within the user frontend.
edit: add an listener to the field within the gui and check the user inputs there too, with this solution the exception case should be very rare...
The outfile should be in binary mode.
outFile = open('output.xml', 'wb')
This setting needs to be set:
SET SERVEROUTPUT ON
Pipe the result to wc
using the -l
(line count) switch:
grep -Rl "curl" ./ | wc -l
//program to form1 to form2
private void button1_Click(object sender, EventArgs e)
{
//MessageBox.Show("Welcome Admin");
Form2 frm = new Form2();
frm.Show();
this.Hide();
}
You can try this code:
function FormatNumber(number, numberOfDigits = 2) {
try {
return new Intl.NumberFormat('en-US').format(parseFloat(number).toFixed(2));
} catch (error) {
return 0;
}
}
var test1 = FormatNumber('1000000.4444');
alert(test1); // 1,000,000.44
var test2 = FormatNumber(100000000000.55555555, 4);
alert(test2); // 100,000,000,000.56
Try loading the website in another web browser such as Safari. Recently had this problem and for some reason, it worked after loading in a different browser.
Differences between PUT and PATCH The main difference between PUT and PATCH requests is witnessed in the way the server processes the enclosed entity to update the resource identified by the Request-URI. When making a PUT request, the enclosed entity is viewed as the modified version of the resource saved on the original server, and the client is requesting to replace it. However, with PATCH, the enclosed entity boasts a set of instructions that describe how a resource stored on the original server should be partially modified to create a new version.
The second difference is when it comes to idempotency. HTTP PUT is said to be idempotent since it always yields the same results every after making several requests. On the other hand, HTTP PATCH is basically said to be non-idempotent. However, it can be made to be idempotent based on where it is implemented.
Create a custom class, e.g. .custom-btn
. Note that to override jQM styles without using !important
, CSS hierarchy should be respected. .ui-btn.custom-class
or .ui-input-btn.custom-class
.
.ui-input-btn.custom-btn {
border:1px solid red;
text-decoration:none;
font-family:helvetica;
color:red;
background:url(img.png) repeat-x;
}
Add a data-wrapper-class
to input
. The custom class will be added to input
wrapping div.
<input type="button" data-wrapper-class="custom-btn">
Input
button is wrapped by a DIV with class ui-btn
. You need to select that div and the input[type="submit"]
. Using !important
is essential to override Jquery Mobile styles.
div.ui-btn, input[type="submit"] {
border:1px solid red !important;
text-decoration:none !important;
font-family:helvetica !important;
color:red !important;
background:url(../images/btn_hover.png) repeat-x !important;
}
var a=[];
a.push({
name_a:"abc",
b:[]
});
a.b.push({
name_b:"xyz"
});
Isn't this what default constructors are for?
class MyModel
{
public MyModel()
{
this.ReturnDate = DateTime.Now;
}
public date ReturnDate {get; set;};
}
for this small example:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print (data);
mysock.close()
adding the "b" before 'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n' solved my problem
i have same problem what i did i just downloaded 32-bit dll and added it to my bin folder this is solved my problem
You can use indexOf
But not working well in the last version of internet explorer.
Code:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
Execution:
isInArray(1, [1,2,3]); // true
I suggest you use the following code:
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle)
return true;
}
return false;
}
There is also a type - JTokenType.Undefined.
This check must be included in @Brian Rogers answer.
token.Type == JTokenType.Undefined
Clear is faster because it does not loop over elements to delete. This method can assume that ALL elements can be deleted.
Remove all
does not necessarily mean delete all elements in the list, only those provided as parameters SHOULD be delete. Hence, more effort is required to keep those which should not be deleted.
CLARIFICATION
By 'loop', I mean it does not have to check whether the element should be kept or not. It can set the reference to null
without searching through the provided lists of elements to delete.
Clear
IS faster than deleteall
.
IF "%1"=="" will fail, all versions of this will fail under certain poison character conditions. Only IF DEFINED or IF NOT DEFINED are safe
In Rails 3 you can use
request.original_url
http://apidock.com/rails/v3.2.8/ActionDispatch/Request/original_url
Instead Animals == "bird*"
Animals = "bird*"
should work.
Another approach in 3.4 (don't know if this is proper Ext): You can have a delete handler like this, assuming every row has a 'delete' button.
handler: function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
var id = rec.get('id');
// some DELETE/GET ajax callback here...
// pass in 'id' var or some key
// inside success
grid.getStore().removeAt(rowIndex);
}
Use java.utils.Arrays:
public int getTheNumber(int[] factors) {
int[] f = (int[])factors.clone();
Arrays.sort(f);
return f[0]*f[(f.length-1];
}
Or if you want to be efficient avoid all the object allocation just actually do the work:
public static int getTheNumber(int[] array) {
if (array.length == 0)
throw new IllegalArgumentException();
int min = array[0];
int max = array[0];
for (int i = 1; i< array.length;++i) {
int v = array[i];
if (v < min) {
min = v;
} else if (v > max) {
max = v;
}
}
return min * max;
}
You could query the sys.tables database view to get out the names of the tables, and then use this query to build yourself another query to do the update on the back of that. For instance:
select 'select * from '+name from sys.tables
will give you a script that will run a select * against all the tables in the system catalog, you could alter the string in the select clause to do your update, as long as you know the column name is the same on all the tables you wish to update, so your script would look something like:
select 'update '+name+' set comments = ''(*)''+comments where comments like ''%comment to be updated%'' ' from sys.tables
You could also then predicate on the tables query to only include tables that have a name in a certain format, or are in a subset you want to create the update script for.
You were almost there. Here is what you can try though.
$(function(){
$("#txtSearchProdAssign").keyup(function (e) {
if (e.which == 13) {
$('input[name="butAssignProd"]').trigger('click');
}
});
});
I have used trigger()
to execute click and bind it on the keyup
event insted of keydown
because click
event comprises of two events actually i.e. mousedown
then mouseup
. So to resemble things same as possible with keydown
and keyup
.
Here is a Demo
Default: 5672, the manual has the answer. It's defined in the RABBITMQ_NODE_PORT
variable.
https://www.rabbitmq.com/configure.html#define-environment-variables
The number might be differently if changed by someone in the rabbitmq configuration file:
vi /etc/rabbitmq/rabbitmq-env.conf
Ask the computer to tell you:
sudo nmap -p 1-65535 localhost
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:50 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00041s latency).
PORT STATE SERVICE
443/tcp open https
5672/tcp open amqp
15672/tcp open unknown
35102/tcp open unknown
59440/tcp open unknown
Oh look, 5672, and 15672
Use netstat:
netstat -lntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:15672 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:55672 0.0.0.0:* LISTEN
tcp 0 0 :::5672 :::* LISTEN
Oh look 5672.
use lsof:
eric@dev ~$ sudo lsof -i | grep beam
beam.smp 21216 rabbitmq 17u IPv4 33148214 0t0 TCP *:55672 (LISTEN)
beam.smp 21216 rabbitmq 18u IPv4 33148219 0t0 TCP *:15672 (LISTEN)
use nmap from a different machine, find out if 5672 is open:
sudo nmap -p 5672 10.0.1.71
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:19 EDT
Nmap scan report for 10.0.1.71
Host is up (0.00011s latency).
PORT STATE SERVICE
5672/tcp open amqp
MAC Address: 0A:40:0E:8C:75:6C (Unknown)
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds
Try to connect to a port manually with telnet, 5671 is CLOSED:
telnet localhost 5671
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
Try to connect to a port manually with telnet, 5672 is OPEN:
telnet localhost 5672
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Check your firewall:
sudo cat /etc/sysconfig/iptables
It should tell you what ports are made open:
-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT
Reapply your firewall:
sudo service iptables restart
iptables: Setting chains to policy ACCEPT: filter [ OK ]
iptables: Flushing firewall rules: [ OK ]
iptables: Unloading modules: [ OK ]
iptables: Applying firewall rules: [ OK ]
I know when you said "contents" you didn't mean this, but if you want to find all the values of all the attributes of a webelement this is a pretty nifty way to do that with javascript in python:
everything = b.execute_script(
'var element = arguments[0];'
'var attributes = {};'
'for (index = 0; index < element.attributes.length; ++index) {'
' attributes[element.attributes[index].name] = element.attributes[index].value };'
'var properties = [];'
'properties[0] = attributes;'
'var element_text = element.textContent;'
'properties[1] = element_text;'
'var styles = getComputedStyle(element);'
'var computed_styles = {};'
'for (index = 0; index < styles.length; ++index) {'
' var value_ = styles.getPropertyValue(styles[index]);'
' computed_styles[styles[index]] = value_ };'
'properties[2] = computed_styles;'
'return properties;', element)
you can also get some extra data with element.__dict__
.
I think this is about all the data you'd ever want to get from a webelement.
You can use CAST
function:
SELECT CAST(your_column_name AS varchar(10)) FROM your_table_name
bootstrap comes with clas btn-lg http://getbootstrap.com/components/#btn-dropdowns-sizing
<div class="btn btn-default btn-block">
Active
</div>
but if you want to have the button of the width of your column / container add btn-block
<div class="btn btn-default btn-lg">
Active
</div>
However this will expand to 100% so make surt ethat you will wrap your button in certain amount of columns e.g. then you know its always stays 3 columns until xs screen
<div class="col-sm-3">
<div class="btn btn-default btn-block">
Active
</div>
</div>
const fs = require('fs')
function readDemo1(file1) {
return new Promise(function (resolve, reject) {
fs.readFile(file1, 'utf8', function (err, dataDemo1) {
if (err)
reject(err);
else
resolve(dataDemo1);
});
});
}
async function copyFile() {
try {
let dataDemo1 = await readDemo1('url')
dataDemo1 += '\n' + await readDemo1('url')
await writeDemo2(dataDemo1)
console.log(dataDemo1)
} catch (error) {
console.error(error);
}
}
copyFile();
function writeDemo2(dataDemo1) {
return new Promise(function(resolve, reject) {
fs.writeFile('text.txt', dataDemo1, 'utf8', function(err) {
if (err)
reject(err);
else
resolve("Promise Success!");
});
});
}
Collation determines how your data is sorted and compared. It's very often important with regards to internazionalization, e.g. how do you sort japanese kanji?
If you google collation and sql server you'll find plenty of articles discussing it!
formatDate
is the function you can call it and pass the date you want to format to dd/mm/yyyy
var unformatedDate = new Date("2017-08-10 18:30:00");_x000D_
_x000D_
$("#hello").append(formatDate(unformatedDate));_x000D_
function formatDate(nowDate) {_x000D_
return nowDate.getDate() +"/"+ (nowDate.getMonth() + 1) + '/'+ nowDate.getFullYear();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="hello">_x000D_
_x000D_
_x000D_
</div>
_x000D_
Reading one line of text at a time, and appending said line to a string individually is time-consuming both in extracting each line and the overhead of so many method invocations.
I was able to get better performance by allocating a decent-sized byte array to hold the stream data, and which is iteratively replaced with a larger array when needed, and trying to read as much as the array could hold.
For some reason, Android repeatedly failed to download the entire file when the code used the InputStream returned by HTTPUrlConnection, so I had to resort to using both a BufferedReader and a hand-rolled timeout mechanism to ensure I would either get the whole file or cancel the transfer.
private static final int kBufferExpansionSize = 32 * 1024;
private static final int kBufferInitialSize = kBufferExpansionSize;
private static final int kMillisecondsFactor = 1000;
private static final int kNetworkActionPeriod = 12 * kMillisecondsFactor;
private String loadContentsOfReader(Reader aReader)
{
BufferedReader br = null;
char[] array = new char[kBufferInitialSize];
int bytesRead;
int totalLength = 0;
String resourceContent = "";
long stopTime;
long nowTime;
try
{
br = new BufferedReader(aReader);
nowTime = System.nanoTime();
stopTime = nowTime + ((long)kNetworkActionPeriod * kMillisecondsFactor * kMillisecondsFactor);
while(((bytesRead = br.read(array, totalLength, array.length - totalLength)) != -1)
&& (nowTime < stopTime))
{
totalLength += bytesRead;
if(totalLength == array.length)
array = Arrays.copyOf(array, array.length + kBufferExpansionSize);
nowTime = System.nanoTime();
}
if(bytesRead == -1)
resourceContent = new String(array, 0, totalLength);
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
if(br != null)
br.close();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT: It turns out that if you don't need to have the content re-encoded (ie, you want the content AS IS) you shouldn't use any of the Reader subclasses. Just use the appropriate Stream subclass.
Replace the beginning of the preceding method with the corresponding lines of the following to speed it up an extra 2 to 3 times.
String loadContentsFromStream(Stream aStream)
{
BufferedInputStream br = null;
byte[] array;
int bytesRead;
int totalLength = 0;
String resourceContent;
long stopTime;
long nowTime;
resourceContent = "";
try
{
br = new BufferedInputStream(aStream);
array = new byte[kBufferInitialSize];
Create a diagram for existing database schema or its subset as follows:
The ERD is displayed.
Export the diagram as follows:
The diagram is exported. To export in a vector format, use To PDF File, instead. This allows for simplified editing using Inkscape (or other vector image editor).
These instructions may work for SQL Developer 3.2.09.23 to 4.1.3.20.
For whose want create a Custom Cell :
CustomCell.h
#import <UIKit/UIKit.h>
@interface HeaderCollectionViewCell : UICollectionViewCell
@property (strong,nonatomic) UIImageView *image;
@end
CustomCell.m
#import "HeaderCollectionViewCell.h"
@implementation HeaderCollectionViewCell
#define IMAGEVIEW_BORDER_LENGTH 5
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
-(void)setup{
_image = [[UIImageView alloc] initWithFrame:(CGRectInset(self.bounds, IMAGEVIEW_BORDER_LENGTH, IMAGEVIEW_BORDER_LENGTH))];
[self addSubview:_image];
}
@end
UIViewController.h
#import <UIKit/UIKit.h>
@interface HomeViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (strong,nonatomic) UICollectionView *collectionView;
@end
UIViewController.m
#import "HomeViewController.h"
#import "HomeView.h"
#import "HeaderCollectionViewCell.h"
@interface HomeViewController ()
@property (nonatomic) NSString *cellID;
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.whiteColor;
_cellID = @"id";
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
_collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[_collectionView registerClass:[HeaderCollectionViewCell class] forCellWithReuseIdentifier:_cellID];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
_collectionView.backgroundColor = UIColor.redColor;
[self.view addSubview:_collectionView];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 4;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
HeaderCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:_cellID forIndexPath:indexPath];
cell.image.image = [UIImage imageNamed:@"premium-icon"];
return cell;
}
-(UITabBarItem*) tabBarItem{
return [[UITabBarItem alloc] initWithTitle:@"Início" image:[UIImage imageNamed:@"home-icon"] tag:0];
}
@end
If you use command line interface for inserting sql file to database.
Be sure your table charset utf8mb4
and column collation utf8mb4_unicode_ci
or utf8mb4_bin
mysql -u root -p123456 my_database < profiles.sql
ERROR 1366 (HY000) at line 1679: Incorrect string value: '\xF0\x9F\x98\x87\xF0\x9F...' for column 'note' at row 328
we can solve the problem with this parameter
--default-character-set=name
(Set the default character set)
mysql -u root -p123456 --default-character-set=utf8mb4 my_database < profiles.sql
One thing to keep in mind is that you can often use eval() to execute code in an otherwise restricted environment - social networking sites that block specific JavaScript functions can sometimes be fooled by breaking them up in an eval block -
eval('al' + 'er' + 't(\'' + 'hi there!' + '\')');
So if you're looking to run some JavaScript code where it might not otherwise be allowed (Myspace, I'm looking at you...) then eval() can be a useful trick.
However, for all the reasons mentioned above, you shouldn't use it for your own code, where you have complete control - it's just not necessary, and better-off relegated to the 'tricky JavaScript hacks' shelf.
Something like this (using the stat
module first to gather data about it and then filtering using a conditional) should work:
- stat: path=/etc/nologin
register: p
- name: create fake 'nologin' shell
file: path=/etc/nologin state=touch owner=root group=sys mode=0555
when: p.stat.exists is defined and not p.stat.exists
You might alternatively be able to leverage the changed_when
functionality.
This exception only happens if you are parsing an empty String/empty byte array.
below is a snippet on how to reproduce it:
String xml = ""; // <-- deliberately an empty string.
ByteArrayInputStream xmlStream = new java.io.ByteArrayInputStream(xml.getBytes());
Unmarshaller u = JAXBContext.newInstance(...)
u.setSchema(...);
u.unmarshal( xmlStream ); // <-- here it will fail
For many GitFlow users the most useful commands are:
git fetch origin master:master --update-head-ok
git fetch origin dev:dev --update-head-ok
The --update-head-ok
flag allows using the same command while on dev
or master
branches.
A handy alias in .gitconfig
:
[alias]
f=!git fetch origin master:master --update-head-ok && git fetch origin dev:dev --update-head-ok
In newer versions of PHP, "extension_dir" is not initially enabled.
Define the width as 960px, or whatever you prefer, and you're good to go!
#main {
margin: 0 auto !important;
float: none !important;
text-align: center;
width: 960px;
}
(I couldn't figure this out until I fixed the width, nothing else worked.)
Use whichever suits your need.
GridView.count(...)
GridView.count(
crossAxisCount: 2,
children: <Widget>[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
)
GridView.builder(...)
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (_, index) => FlutterLogo(),
itemCount: 4,
)
GridView(...)
GridView(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
children: <Widget>[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
)
GridView.custom(...)
GridView.custom(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
childrenDelegate: SliverChildListDelegate(
[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
),
)
GridView.extent(...)
GridView.extent(
maxCrossAxisExtent: 400,
children: <Widget>[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
)
Output (same for all):
When you want to fetch max value of a date column from dataframe, just the value without object type or Row object information, you can refer to below code.
table = "mytable"
max_date = df.select(max('date_col')).first()[0]
2020-06-26
instead of Row(max(reference_week)=datetime.date(2020, 6, 26))
Using VS 2010:
Let's say you have a Windows.Forms project. You add a UserControl (say MyControl) to the project, and design it all up. Now you want to add it to your toolbox.
As soon as the project is successfully built once, it will appear in your Framework Components. Right click the Toolbox to get the context menu, select "Choose Items...", and browse to the name of your control (MyControl) under the ".NET Framework Components" tab.
Advantage over using dlls: you can edit the controls in the same project as your form, and the form will build with the new controls. However, the control will only be avilable to this project.
Note: If the control has build errors, resolve them before moving on to the containing forms, or the designer has a heart attack.
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
'HTTP_USER_AGENT' Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.
So I assume you'll be able to get the browser name/id from the $_SERVER["HTTP_USER_AGENT"] variable.
You can also use:
File imgFile = new File(“filepath”);
if(imgFile.exists())
{
ImageView myImage = new ImageView(this);
myImage.setImageURI(Uri.fromFile(imgFile));
}
This does the bitmap decoding implicit for you.
Now we need to create a drawable resource file and name it ripple_effect as shown below
ripple_effect.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorRipple"> <!-- ripple color -->
<!-- for Button -->
<item>
<shape android:shape="rectangle">
<corners android:radius="3dp" />
<solid android:color="@color/colorPrimary"/>
</shape>
</item>
</ripple>
Source Full: https://code-android-example.blogspot.com/2020/11/ripple-effect-in-android-for-button.html
I am guessing you're confused with the parameterization of the types:
// This works, because there is one class/type definition in the parameterized <> field
ArrayList<String> myArrayList = new ArrayList<String>();
// This doesn't work, as you cannot use primitive types here
ArrayList<char> myArrayList = new ArrayList<char>();
Typically I create SessionProxy with strongly typed properties for items in the session. The code that accesses these properties checks for nullity and does the casting to the proper type. The nice thing about this is that all of my session related items are kept in one place. I don't have to worry about using different keys in different parts of the code (and wondering why it doesn't work). And with dependency injection and mocking I can fully test it with unit tests. If follows DRY principles and also lets me define reasonable defaults.
public class SessionProxy
{
private HttpSessionState session; // use dependency injection for testability
public SessionProxy( HttpSessionState session )
{
this.session = session; //might need to throw an exception here if session is null
}
public DateTime LastUpdate
{
get { return this.session["LastUpdate"] != null
? (DateTime)this.session["LastUpdate"]
: DateTime.MinValue; }
set { this.session["LastUpdate"] = value; }
}
public string UserLastName
{
get { return (string)this.session["UserLastName"]; }
set { this.session["UserLastName"] = value; }
}
}
Change the PATH variable to include the bin directory of your PostgreSQL installation.
then add new path their....[for example]
C:\Program Files\PostgreSQL\12\bin
After that click OK
Open CMD/Command Prompt. Type this to open psql
psql -U username database_name
For Example psql -U postgres test
Now, you will be prompted to give Password for the User. (It will be hidden as a security measure).
Then you are good to go.
If earlier working project crashing suddenly with mentioned error you can try following solution.
This worked for me.
Your regular expression [^a-zA-Z0-9]\s/g
says match any character that is not a number or letter followed by a space.
Remove the \s and you should get what you are after if you want a _ for every special character.
var newString = str.replace(/[^A-Z0-9]/ig, "_");
That will result in hello_world___hello_universe
If you want it to be single underscores use a + to match multiple
var newString = str.replace(/[^A-Z0-9]+/ig, "_");
That will result in hello_world_hello_universe
By far the simplest (works for python) is '123-(apple|banana)-?456'
.
In my case it was OneTab chrome extension.
when I am testing "typeof obj === undefined
", the alert(typeof obj)
returning object
, even though obj is undefined.
Since obj is type of Object
its returning Object
, not undefined
.
So after hours of testing I opted below technique.
if(document.getElementById(obj) !== null){
//do...
}else{
//do...
}
I am not sure why the first technique didn't work.But I get done my work using this.
Like many people, I was looking for something that was:
...But alas - nothing!
Well if a job's worth doing... I was able to get something up and running in about 30 mins. Disclaimer: there's quite a few known (and probably a few as yet unknown) problems with it, but it makes me wonder what on Earth the other 2920 lines of JS are there for in many offerings!
(window => {
let initCoords;
const coords_update = e => {
if (initCoords) {
const elem = initCoords.bar.closest('.scrollr');
const eSuffix = initCoords.axis.toUpperCase();
const sSuffix = initCoords.axis == 'x' ? 'Left' : 'Top';
const dSuffix = initCoords.axis == 'x' ? 'Width' : 'Height';
const max = elem['scroll' + dSuffix] - elem['client' + dSuffix];
const room = elem['client' + dSuffix] - initCoords.bar['client' + dSuffix];
const delta = e['page' + eSuffix] - initCoords.abs;
const abs = initCoords.p0 + delta;
elem['scroll' + sSuffix] = max * abs / room;
}
};
const scrollr_resize = elem => {
const xBar = elem.querySelector('.track.x .bar');
const yBar = elem.querySelector('.track.y .bar');
const xRel = elem.clientWidth / elem.scrollWidth;
const yRel = elem.clientHeight / elem.scrollHeight;
xBar.style.width = (100 * xRel).toFixed(2) + '%';
yBar.style.height = (100 * yRel).toFixed(2) + '%';
};
const scrollr_init = elem => {
const xTrack = document.createElement('span');
const yTrack = document.createElement('span');
const xBar = document.createElement('span');
const yBar = document.createElement('span');
xTrack.className = 'track x';
yTrack.className = 'track y';
xBar.className = 'bar';
yBar.className = 'bar';
xTrack.appendChild(xBar);
yTrack.appendChild(yBar);
elem.appendChild(xTrack);
elem.appendChild(yTrack);
elem.addEventListener('wheel', scrollr_OnWheel);
elem.addEventListener('scroll', scrollr_OnScroll);
xTrack.addEventListener('wheel', xTrack_OnWheel);
xTrack.addEventListener('click', xTrack_OnClick);
xTrack.addEventListener('mouseover', () => xTrack.classList.add('active'));
xTrack.addEventListener('mouseout', () => {
if (!initCoords) xTrack.classList.remove('active');
});
yTrack.addEventListener('click', yTrack_OnClick);
yTrack.addEventListener('mouseover', () => yTrack.classList.add('active'));
yTrack.addEventListener('mouseout', () => {
if (!initCoords) yTrack.classList.remove('active');
});
xBar.addEventListener('click', bar_OnClick);
xBar.addEventListener('mousedown', xBar_OnMouseDown);
yBar.addEventListener('click', bar_OnClick);
yBar.addEventListener('mousedown', yBar_OnMouseDown);
scrollr_resize(elem);
};
window.addEventListener('load', e => {
const scrollrz = Array.from(document.querySelectorAll('.scrollr'));
scrollrz.forEach(scrollr_init);
});
window.addEventListener('resize', e => {
const scrollrz = Array.from(document.querySelectorAll('.scrollr'));
scrollrz.forEach(scrollr_resize);
});
window.addEventListener('mousemove', coords_update);
window.addEventListener('mouseup', e => {
initCoords = null;
Array.from(document.querySelectorAll('.track.active'))
.forEach(elem => elem.classList.remove('active'));
});
function xBar_OnMouseDown(e) {
const p0 = this.offsetLeft;
initCoords = {
axis: 'x',
abs: e.pageX,
bar: this,
p0
};
}
function yBar_OnMouseDown(e) {
const p0 = this.offsetTop;
initCoords = {
axis: 'y',
abs: e.pageY,
bar: this,
p0
};
}
function bar_OnClick(e) {
e.stopPropagation();
}
function xTrack_OnClick(e) {
const elem = this.closest('.scrollr');
const xBar = this.querySelector('.bar');
let unit = elem.clientWidth - 30;
if (e.offsetX <= xBar.offsetLeft) unit *= -1;
elem.scrollLeft += unit;
}
function yTrack_OnClick(e) {
const elem = this.closest('.scrollr');
const yBar = this.querySelector('.bar');
let unit = elem.clientHeight - 30;
if (e.offsetY <= yBar.offsetTop) unit *= -1;
elem.scrollTop += unit;
}
function xTrack_OnWheel(e) {
e.stopPropagation();
const elem = this.closest('.scrollr');
const left0 = elem.scrollLeft;
const delta = e.deltaY !== 0 ? e.deltaY : e.deltaX;
elem.scrollLeft += delta;
const moved = left0 !== elem.scrollLeft;
if (moved) e.preventDefault();
}
function scrollr_OnWheel(e) {
const left0 = this.scrollLeft;
const top0 = this.scrollTop;
this.scrollLeft += e.deltaX;
this.scrollTop += e.deltaY;
const moved = left0 !== this.scrollLeft || top0 !== this.scrollTop;
if (moved) e.preventDefault();
}
function scrollr_OnScroll(e) {
const xTrack = this.querySelector('.track.x');
const yTrack = this.querySelector('.track.y');
const xBar = xTrack.querySelector('.bar');
const yBar = yTrack.querySelector('.bar');
const xMax = this.scrollWidth - this.clientWidth;
const yMax = this.scrollHeight - this.clientHeight;
const xFrac = this.scrollLeft / xMax;
const yFrac = this.scrollTop / yMax;
const xAbs = xFrac * (this.clientWidth - xBar.clientWidth);
const yAbs = yFrac * (this.clientHeight - yBar.clientHeight);
xTrack.style.left = this.scrollLeft + 'px';
xTrack.style.bottom = -this.scrollTop + 'px';
xBar.style.left = xAbs + 'px';
yTrack.style.top = this.scrollTop + 'px';
yTrack.style.right = -this.scrollLeft + 'px';
yBar.style.top = yAbs + 'px';
};
})(window);
_x000D_
.scrollr {
overflow: hidden;
position: relative;
}
.track {
position: absolute;
cursor: pointer;
transition: background-color .3s;
user-select: none;
}
.track.x {
left: 0;
bottom: 0;
width: 100%;
height: 10px;
}
.track.y {
top: 0;
right: 0;
height: 100%;
width: 10px;
}
.bar {
position: absolute;
background-color: yellow;
transition: background-color .3s, opacity .3s, width .3s, height .3s, margin .3s;
display: block;
width: 100%;
height: 100%;
opacity: .7;
}
.track.x .bar {
min-width: 25px;
height: 3px;
margin: 5px 0 2px 0;
}
.track.y .bar {
min-height: 25px;
width: 3px;
margin: 0 2px 0 5px;
}
.track.active {
background-color: #ccc;
}
.track.active .bar {
background-color: #999;
margin: 0;
opacity: 1;
}
.track.x.active .bar {
height: 10px;
}
.track.y.active .bar {
width: 10px;
}
/* Custom client stuff */
.content {
background: red;
}
.content p {
width: 450px;
margin: 0;
}
.scrollr {
max-width: 350px;
max-height: 150px;
}
_x000D_
<div class="scrollr content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
</div>
_x000D_
A way that will fail if your input string isn't valid pairs of hex characters...:
>>> import binascii
>>> ' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))
'0xde 0xad 0xbe 0xef'
The solution is:
NameVirtualHost *:80
Listen 80
(...)
<VirtualHost *:80>
ServerName host1
DocumentRoot /someDir
</VirtualHost>
<VirtualHost *:80>
ServerName host2
DocumentRoot /someOtherDir
</VirtualHost>
<VirtualHost *:80>
ServerName aaaa.com
DocumentRoot /defaultDir
</VirtualHost>
In my case, to work, I created a VirtualHost
(n.e. VirtualHost
per CNAME
) called aaaa.com
since I have different files for different VirtualHost
s and knowing that Apache reads them in alphabetical order.
I had to remove the first option from a select, with no ID, only a class, so I used this code successfully:
$('select.validation').find('option:first').remove();
SELECT table_name as Table_Name, row_cnt as Row_Count, SUM(mb) as Size_MB
FROM
(SELECT in_tbl.table_name, to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from ' ||ut.table_name)),'/ROWSET/ROW/C')) AS row_cnt , mb
FROM
(SELECT CASE WHEN lob_tables IS NULL THEN table_name WHEN lob_tables IS NOT NULL THEN lob_tables END AS table_name , mb
FROM (SELECT ul.table_name AS lob_tables, us.segment_name AS table_name , us.bytes/1024/1024 MB FROM user_segments us
LEFT JOIN user_lobs ul ON us.segment_name = ul.segment_name ) ) in_tbl INNER JOIN user_tables ut ON in_tbl.table_name = ut.table_name ) GROUP BY table_name, row_cnt ORDER BY 3 DESC;``
Above query will give, Table_name, Row_count, Size_in_MB(includes lob column size) of specific user.
Best thing to use is HTMLAgilityPack. You can also look into using Fizzler or CSQuery depending on your needs for selecting the elements from the retrieved page. Using LINQ or Regukar Expressions is just to error prone, especially when the HTML can be malformed, missing closing tags, have nested child elements etc.
You need to stream the page into an HtmlDocument object and then select your required element.
// Call the page and get the generated HTML
var doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlNode.ElementsFlags["br"] = HtmlAgilityPack.HtmlElementFlag.Empty;
doc.OptionWriteEmptyNodes = true;
try
{
var webRequest = HttpWebRequest.Create(pageUrl);
Stream stream = webRequest.GetResponse().GetResponseStream();
doc.Load(stream);
stream.Close();
}
catch (System.UriFormatException uex)
{
Log.Fatal("There was an error in the format of the url: " + itemUrl, uex);
throw;
}
catch (System.Net.WebException wex)
{
Log.Fatal("There was an error connecting to the url: " + itemUrl, wex);
throw;
}
//get the div by id and then get the inner text
string testDivSelector = "//div[@id='test']";
var divString = doc.DocumentNode.SelectSingleNode(testDivSelector).InnerHtml.ToString();
[EDIT] Actually, scrap that. The simplest method is to use FizzlerEx, an updated jQuery/CSS3-selectors implementation of the original Fizzler project.
Code sample directly from their site:
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
//get the page
var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html");
var page = document.DocumentNode;
//loop through all div tags with item css class
foreach(var item in page.QuerySelectorAll("div.item"))
{
var title = item.QuerySelector("h3:not(.share)").InnerText;
var date = DateTime.Parse(item.QuerySelector("span:eq(2)").InnerText);
var description = item.QuerySelector("span:has(b)").InnerHtml;
}
I don't think it can get any simpler than that.
Look at Java sources: valueOf
is using parseInt
:
/**
* Parses the specified string as a signed decimal integer value.
*
* @param string
* the string representation of an integer value.
* @return an {@code Integer} instance containing the integer value
* represented by {@code string}.
* @throws NumberFormatException
* if {@code string} cannot be parsed as an integer value.
* @see #parseInt(String)
*/
public static Integer valueOf(String string) throws NumberFormatException {
return valueOf(parseInt(string));
}
parseInt
returns int
/**
* Parses the specified string as a signed decimal integer value. The ASCII
* character \u002d ('-') is recognized as the minus sign.
*
* @param string
* the string representation of an integer value.
* @return the primitive integer value represented by {@code string}.
* @throws NumberFormatException
* if {@code string} cannot be parsed as an integer value.
*/
public static int parseInt(String string) throws NumberFormatException {
return parseInt(string, 10);
}
If you need minimal value for particular column
min(data[,2])
Note: R considers NA
both the minimum and maximum value so if you have NA's in your column, they return: NA
. To remedy, use:
min(data[,2], na.rm=T)
Instead, you could git CtrlZ and retry the commit but this time add " -m " with a message in quotes after it, then it will commit without prompting you with that page.
First of all Assert()
method is available for Trace
and Debug
classes.
Debug.Assert()
is executing only in Debug mode.
Trace.Assert()
is executing in Debug and Release mode.
Here is an example:
int i = 1 + 3;
// Debug.Assert method in Debug mode fails, since i == 4
Debug.Assert(i == 3);
Debug.WriteLine(i == 3, "i is equal to 3");
// Trace.Assert method in Release mode is not failing.
Trace.Assert(i == 4);
Trace.WriteLine(i == 4, "i is equla to 4");
Console.WriteLine("Press a key to continue...");
Console.ReadLine();
Run this code in Debug mode and then in Release mode.
You will notice that during Debug mode your code Debug.Assert
statement fails, you get a message box showing the current stack trace of the application. This is not happening in Release mode since Trace.Assert()
condition is true (i == 4)
.
WriteLine()
method simply gives you an option of logging the information to Visual Studio output.
file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
any_string = "Hello\nWorld"
file.write(any_string)
file.close()
I was having a similar problem, but additionally I was getting a Java Heap Space error anytime I modified/saved JSP pages with Tomcat server running, therefore the context were not fully recharged.
My versions were Apache Tomcat 6.0.29 and JDK 6u12.
Upgrading JDK to 6u21 as suggested in References section of URL http://wiki.apache.org/tomcat/MemoryLeakProtection solved the Java Heap Space problem (context now reloads OK) although JDBC Driver error still appears.
I had a similar problem accessing a LDAP-Server from a docker container. I set a fixed IP for the container and added a firewall rule.
docker-compose.yml:
version: '2'
services:
containerName:
image: dockerImageName:latest
extra_hosts:
- "dockerhost:192.168.50.1"
networks:
my_net:
ipv4_address: 192.168.50.2
networks:
my_net:
ipam:
config:
- subnet: 192.168.50.0/24
iptables rule:
iptables -A INPUT -j ACCEPT -p tcp -s 192.168.50.2 -d $192.168.50.1 --dport portnumberOnHost
Inside the container access dockerhost:portnumberOnHost
Simple way to display pdf files from database and we can download it.
$resume is pdf file name which comes from database.
../resume/filename is path of folder where your file is stored.
<a href="../resumes/<?php echo $resume; ?>"/><?php echo $resume; ?></a>
One of the options you should consider is Notable PDF
It has a free plan unless you are planning on doing real-time online collaboration on pdfs
Embed the following iframe
to any html and enjoy the results:
<iframe width='1000' height='800' src='http://bit.ly/1JxrtjR' frameborder='0' allowfullscreen></iframe>
To finally answer the title question: It is (a client side setting) in (project, profile or settings)
[plugin]?[r|R]epository/[releases|snapshots]/updatePolicy
... tag.
The (currently, maven: 3.6.0, but I suppose "far backwards" compatible) possible values are :
/** * Never update locally cached data. */ public static final String UPDATE_POLICY_NEVER = "never"; /** * Always update locally cached data. */ public static final String UPDATE_POLICY_ALWAYS = "always"; /** * Update locally cached data once a day. */ public static final String UPDATE_POLICY_DAILY = "daily"; /** * Update locally cached data **every X minutes** as given by "interval:X". */ public static final String UPDATE_POLICY_INTERVAL = "interval";
The current (maven 3.6.0) evaluation of this tag is implemented as follows:
public boolean isUpdatedRequired( RepositorySystemSession session, long lastModified, String policy ) { boolean checkForUpdates; if ( policy == null ) { policy = ""; } if ( RepositoryPolicy.UPDATE_POLICY_ALWAYS.equals( policy ) ) { checkForUpdates = true; } else if ( RepositoryPolicy.UPDATE_POLICY_DAILY.equals( policy ) ) { Calendar cal = Calendar.getInstance(); cal.set( Calendar.HOUR_OF_DAY, 0 ); cal.set( Calendar.MINUTE, 0 ); cal.set( Calendar.SECOND, 0 ); cal.set( Calendar.MILLISECOND, 0 ); checkForUpdates = cal.getTimeInMillis() > lastModified; } else if ( policy.startsWith( RepositoryPolicy.UPDATE_POLICY_INTERVAL ) ) { int minutes = getMinutes( policy ); Calendar cal = Calendar.getInstance(); cal.add( Calendar.MINUTE, -minutes ); checkForUpdates = cal.getTimeInMillis() > lastModified; } else { // assume "never" checkForUpdates = false; if ( !RepositoryPolicy.UPDATE_POLICY_NEVER.equals( policy ) ) { LOGGER.warn( "Unknown repository update policy '{}', assuming '{}'", policy, RepositoryPolicy.UPDATE_POLICY_NEVER ); } } return checkForUpdates; }
..with:
private int getMinutes( String policy ) { int minutes; try { String s = policy.substring( RepositoryPolicy.UPDATE_POLICY_INTERVAL.length() + 1 ); minutes = Integer.valueOf( s ); } catch ( RuntimeException e ) { minutes = 24 * 60; LOGGER.warn( "Non-parseable repository update policy '{}', assuming '{}:1440'", policy, RepositoryPolicy.UPDATE_POLICY_INTERVAL ); } return minutes; }
...where lastModified
is the (local file) "modified timestamp" of an/each underlying artifact.
In particular for the interval:x
setting:
:
is not that strict - any "non-empty" character could do it (=
,
, ...).x < 0
should yield to "never".interval:0
I would assume a "minutely" (0-59 secs. or above...) interval.24 * 60
minutes (~"daily")...see: DefaultUpdatePolicyAnalyzer, DefaultMetadataResolver#resolveMetadata() and RepositoryPolicy
Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.
If a header file contains a function, and is included by multiple .c
files, each .c
file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.
It is technically possible to create static
functions in a header file for inclusion in multiple .c
files. Though this is generally not done because it breaks from the convention that code is found in .c
files and declarations are found in .h
files.
See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.
just run the following command in the node project
npm install
its worked for me
You need to edit the Tomcat/conf/server.xml
and change the connector port. The connector setting should look something like this:
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" />
Just change the connector port from default 8080 to another valid port number.
you can .remove()
each child:
const div = document.querySelector('div.my-div')
while(div.firstChild) div.firstChild.remove()
This allows you to just get the image data and set to the img src, which is cool.
var oReq = new XMLHttpRequest();
oReq.open("post", '/somelocation/getmypic', true );
oReq.responseType = "blob";
oReq.onload = function ( oEvent )
{
var blob = oReq.response;
var imgSrc = URL.createObjectURL( blob );
var $img = $( '<img/>', {
"alt": "test image",
"src": imgSrc
} ).appendTo( $( '#bb_theImageContainer' ) );
window.URL.revokeObjectURL( imgSrc );
};
oReq.send( null );
The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.
Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):
{{ var1 + '-' + var2 + '-' + var3 }}
If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:
e.g. To concatenate our 3 vars, and get a sha512 hash:
{{ (var1 + var2 + var3) | hash('sha512') }}
Note: this works on Ansible 2.3. I haven't tested it on earlier versions.
Or something like:
df.loc[df['a'].isnull(),'a']=0
df.loc[df['b'].isnull(),'b']=0
and if there is more:
for i in your_list:
df.loc[df[i].isnull(),i]=0
I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.
#!/bin/bash
PROPERTY_FILE=filename.properties
function getProperty {
PROP_KEY=$1
PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
echo $PROP_VALUE
}
echo "# Reading property from $PROPERTY_FILE"
DB_USER=$(getProperty "db.username")
DB_PASS=$(getProperty "db.password")
ROOT_LOC=$(getProperty "root.location")
echo $DB_USER
echo $DB_PASS
echo $ROOT_LOC
echo "Writing on DB ... "
mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL
update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
EOFMYSQL
echo "Writing root location($ROOT_LOC) is done ... "
counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;
if [ "$counter" = "1" ]
then
echo "ROOT location updated"
fi
If you have a fixed navbar, you'll need something like this.
Taking from the best of the above answers and comments...
$(".bs-js-navbar-scrollspy li a[href^='#']").on('click', function(event) {
var target = this.hash;
event.preventDefault();
var navOffset = $('#navbar').height();
return $('html, body').animate({
scrollTop: $(this.hash).offset().top - navOffset
}, 300, function() {
return window.history.pushState(null, null, target);
});
});
First, in order to prevent the "undefined" error, store the hash to a variable, target
, before calling preventDefault()
, and later reference that stored value instead, as mentioned by pupadupa.
Next. You cannot use window.location.hash = target
because it sets the url and the location simultaneously rather than separately. You will end up having the location at the beginning of the element whose id matches the href... but covered by your fixed top navbar.
In order to get around this, you set your scrollTop value to the vertical scroll location value of the target minus the height of your fixed navbar. Directly targeting that value maintains smooth scrolling, instead of adding an adjustment afterwards, and getting unprofessional-looking jitters.
You will notice the url doesn't change. To set this, use return window.history.pushState(null, null, target);
instead, to manually add the url to the history stack.
Done!
Other notes:
1) using the .on
method is the latest (as of Jan 2015) jquery method that is better than .bind
or .live
, or even .click
for reasons I'll leave to you to find out.
2) the navOffset value can be within the function or outside, but you will probably want it outside, as you may very well reference that vertical space for other functions / DOM manipulations. But I left it inside to make it neatly into one function.
In [42]: a = [4, 6, 12]
In [43]: [sum(a[:i+1]) for i in xrange(len(a))]
Out[43]: [4, 10, 22]
This is slighlty faster than the generator method above by @Ashwini for small lists
In [48]: %timeit list(accumu([4,6,12]))
100000 loops, best of 3: 2.63 us per loop
In [49]: %timeit [sum(a[:i+1]) for i in xrange(len(a))]
100000 loops, best of 3: 2.46 us per loop
For larger lists, the generator is the way to go for sure. . .
In [50]: a = range(1000)
In [51]: %timeit [sum(a[:i+1]) for i in xrange(len(a))]
100 loops, best of 3: 6.04 ms per loop
In [52]: %timeit list(accumu(a))
10000 loops, best of 3: 162 us per loop
Have a look at GitHub - gspread.
I found it to be very easy to use and since you can retrieve a whole column by
first_col = worksheet.col_values(1)
and a whole row by
second_row = worksheet.row_values(2)
you can more or less build some basic select ...
where ... = ...
easily.
Short list of some of the major differences:
bool
, true
and false
, Objective-C uses BOOL
, YES
and NO
.void*
and nullptr
, Objective-C prefers id
and nil
.SEL
) as an approximate equivalent to function pointers.nil
, unlike C++ which will crash if you try to call a member function of nullptr
self
, and allows class initialisers (similar to constructors) to return a completely different class if desired. Contrast to C++, where if you create a new instance of a class (either implicitly on the stack, or explicitly through new
) it is guaranteed to be of the type you originally specified.int foo (void)
and int foo (int)
define an implicit overload of the method foo
, but to achieve the same in Objective-C requires the explicit overloads - (int) foo
and - (int) foo:(int) intParam
. This is due to Objective-C's named parameters being functionally equivalent to C++'s name mangling.alloc
message, or implicitly in an appropriate factory method).In my opinion, probably the biggest difference is the syntax. You can achieve essentially the same things in either language, but in my opinion the C++ syntax is simpler while some of Objective-C's features make certain tasks (such as GUI design) easier thanks to dynamic dispatch.
Probably plenty of other things too that I've missed, I'll update with any other things I think of. Other than that, can highly recommend the guide LiraNuna pointed you to. Incidentally, another site of interest might be this.
I should also point out that I'm just starting learning Objective-C myself, and as such a lot of the above may not quite be correct or complete - I apologise if that's the case, and welcome suggestions for improvement.
EDIT: updated to address the points raised in the following comments, added a few more items to the list.
<ScrollViewer MaxHeight="50"
Width="Auto"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto">
<TextBlock Text="{Binding Path=}"
Style="{StaticResource TextStyle_Data}"
TextWrapping="Wrap" />
</ScrollViewer>
I am doing this in another way by putting MaxHeight in ScrollViewer.
Just Adjust the MaxHeight to show more or fewer lines of text. Easy.
"At run time, the authorization module iterates through the allow and deny elements, starting at the most local configuration file, until the authorization module finds the first access rule that fits a particular user account. Then, the authorization module grants or denies access to a URL resource depending on whether the first access rule found is an allow or a deny rule. The default authorization rule is . Thus, by default, access is allowed unless configured otherwise."
Article at MSDN
deny = * means deny everyone
deny = ? means deny unauthenticated users
In your 1st example deny * will not affect dan, matthew since they were already allowed by the preceding rule.
According to the docs, here is no difference in your 2 rule sets.
Here, you could use cv2.bitwise_and
function if you already have the mask image.
For check the below code:
img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)
The output will be as follows for a lena image, and for rectangular mask.
It's not Twitter bootstrap specific, it is a normal HTML5 component and you can specify the range with the min
and max
attributes (in your case only the first attribute). For example:
<div> _x000D_
<input type="number" id="replyNumber" min="0" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
I'm not sure if only integers are allowed by default in the control or not, but else you can specify the step
attribute:
<div> _x000D_
<input type="number" id="replyNumber" min="0" step="1" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
Now only numbers higher (and equal to) zero can be used and there is a step of 1, which means the values are 0, 1, 2, 3, 4, ... .
BE AWARE: Not all browsers support the HTML5 features, so it's recommended to have some kind of JavaScript fallback (and in your back-end too) if you really want to use the constraints.
For a list of browsers that support it, you can look at caniuse.com.
The problem is that the first argument passed to class methods in python is always a copy of the class instance on which the method is called, typically labelled self
. If the class is declared thus:
class foo(object):
def foodo(self, thing=None, thong='not underwear'):
print thing if thing else "nothing"
print 'a thong is',thong
it behaves as expected.
Explanation:
Without self
as the first parameter, when myfoo.foodo(thing="something")
is executed, the foodo
method is called with arguments (myfoo, thing="something")
. The instance myfoo
is then assigned to thing
(since thing
is the first declared parameter), but python also attempts to assign "something"
to thing
, hence the Exception.
To demonstrate, try running this with the original code:
myfoo.foodo("something")
print
print myfoo
You'll output like:
<__main__.foo object at 0x321c290>
a thong is something
<__main__.foo object at 0x321c290>
You can see that 'thing' has been assigned a reference to the instance 'myfoo' of the class 'foo'. This section of the docs explains how function arguments work a bit more.
If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:
def plot(xx, yy, good):
"""Plot data
Good parts are plotted as black, bad parts as red.
Parameters
----------
xx, yy : 1D arrays
Data to plot.
good : `numpy.ndarray`, boolean
Boolean array indicating if point is good.
"""
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
from matplotlib.colors import from_levels_and_colors
from matplotlib.collections import LineCollection
cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
points = np.array([xx, yy]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lines = LineCollection(segments, cmap=cmap, norm=norm)
lines.set_array(good.astype(int))
ax.add_collection(lines)
plt.show()
You can use the onchange event:
<form name="myform" id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" onchange="this.form.submit()"/>
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="DoSubmit()" />
</form>
In my case it was because I had another folder that contained xampp and all it's files (htdocs, php e.t.c). Like I installed Xampp twice in different directories and for some reason the configurations of the other one was affecting my current xampp directory and so I had to change the memory size in the php.ini file of the other directory too.
You can do this:
create type number_tab is table of number;
select * from table (number_tab(1,2,3,4,5,6));
The column is given the name COLUMN_VALUE by Oracle, so this works too:
select column_value from table (number_tab(1,2,3,4,5,6));
Suppose your timestring has a format that looks like this :
'2016-03-10 16:00:00.0'
In that case, you could do a simple regex to convert it to ISO 8601
:
'2016-03-10 16:00:00.0'.replace(/ /g,'T')
This would procude the following output :
'2016-03-10T16:00:00.0'
This is the standard datetime format, and thus supported by all browsers :
document.body.innerHTML = new Date('2016-03-10T16:00:00.0') // THIS IS SAFE TO USE
_x000D_
Suppose your timestring has a format that looks like this :
'02-24-2015 09:22:21 PM'
Here, you can do the following regex :
'02-24-2015 09:22:21 PM'.replace(/-/g,'/');
This, too, produces a format supported by all browsers :
document.body.innerHTML = new Date('02/24/2015 09:22:21 PM') // THIS IS SAFE TO USE
_x000D_
Suppose you have a time string that isn't easy to adjust to one of the well-supported standards.
In that case, it's best to just split your time string into different pieces and use them as individual parameters for Date
:
document.body.innerHTML = new Date(2016, 2, 26, 3, 24, 0); // THIS IS SAFE TO USE
_x000D_
If you want to access both the key and value, use the following:
Python 2:
for key, value in my_dict.iteritems():
print(key, value)
Python 3:
for key, value in my_dict.items():
print(key, value)
To come full circle and include all versions of Visual Studio, @Myster originally stated that;
Pre Visual Studio 2015 the paths to applicationhost.config were:
%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config
Visual Studio 2015/2017 path can be found at: (credit: @Talon)
$(solutionDir)\.vs\config\applicationhost.config
Visual Studio 2019 path can be found at: (credit: @Talon)
$(solutionDir)\.vs\config\$(ProjectName)\applicationhost.config
But the part that might get some people is that the project settings in the .sln file can repopulate the applicationhost.config for Visual Studio 2015+. (credit: @Lex Li)
So, if you make a change in the applicationhost.config you also have to make sure your changes match here:
$(solutionDir)\ProjectName.sln
The two important settings should look like:
Project("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") = "ProjectName", "ProjectPath\", "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
and
VWDPort = "Port#"
What is important here is that the two settings in the .sln must match the name and bindingInformation respectively in the applicationhost.config file if you plan on making changes. There may be more places that link these two files and I will update as I find more links either by comments or more experience.
Where do you want to see the output?
Messages being output via Debug.Print
will be displayed in the immediate window which you can open by pressing Ctrl+G.
You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar
Clone the repository as normal:
git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle
Then checkout the tag you want like so:
git checkout tags/1.1.4
This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".
To retain any changes made, move them to a new branch:
git checkout -b 1.1.4-jspooner
You can get back to the master branch by using:
git checkout master
Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:
git checkout 1.1.4
But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:
warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'
The shorthand can be safely used if the repository does not share names between branches and tags.
In your widget's Info.plist file, don't forget to set your AllowNetworkAccess
key to true.
I am new to maven and did not understand how I could work with local maven project added through Viktor Nordling's answer and still have a proper dependency in pom.xml file. The answer is simple: intellij first looks at your locally added module and if it doesn't find one it goes to get the project remotely. You can check this by looking at "external libraries" under your project browser when you add or remove maven module.
Hope this helps anyone.
I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.
In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.
For example:
INSERT INTO MyTable
( Column1, Column2, Column3 )
VALUES
('John', 123, 'Lloyds Office'),
('Jane', 124, 'Lloyds Office'),
('Billy', 125, 'London Office'),
('Miranda', 126, 'Bristol Office');
Fiddle with 3 working solutions in action.
Given an external JSON:
myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'
Solution 1: $.ajax() + jsonp:
$.ajax({
dataType: "jsonp",
url: myurl ,
}).done(function ( data ) {
// do my stuff
});
Solution 2: $.ajax()+json+&calback=?:
$.ajax({
dataType: "json",
url: myurl + '&callback=?',
}).done(function ( data ) {
// do my stuff
});
Solution 3: $.getJSON()+calback=?:
$.getJSON( myurl + '&callback=?', function(data) {
// do my stuff
});
Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/
To remove duplicates from a single column
Sub removeDuplicate()
'removeDuplicate Macro
Columns("A:A").Select
ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _
Header:=xlNo
Range("A1").Select
End Sub
if you have header then use Header:=xlYes
Increase your range as per your requirement.
you can make it to 1000 like this :
ActiveSheet.Range("$A$1:$A$1000")
More info here here
This is the shell function I use to get my SSH key finger print for creating DigitalOcean droplets:
fingerprint() {
pubkeypath="$1"
ssh-keygen -E md5 -lf "$pubkeypath" | awk '{ print $2 }' | cut -c 5-
}
Put it in your ~/.bashrc
, source it, and then you can get the finger print as so:
$ fingerprint ~/.ssh/id_rsa.pub
d2:47:0a:87:30:a0:c0:df:6b:42:19:55:b4:f3:09:b9
Short answer:
ALTER SCHEMA new_schema TRANSFER old_schema.table_name
I can confirm that the data in the table remains intact, which is probably quite important :)
Long answer as per MSDN docs,
ALTER SCHEMA schema_name
TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]
If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.
The [new-ish at the time of writing in 2017] Fetch API is intended to make GET requests easy, but it is able to POST as well.
let data = {element: "barium"};
fetch("/post/data/here", {
method: "POST",
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
If you are as lazy as me (or just prefer a shortcut/helper):
window.post = function(url, data) {
return fetch(url, {method: "POST", body: JSON.stringify(data)});
}
// ...
post("post/data/here", {element: "osmium"});
You can try this simple piece of code below.
For HEX to RGB
list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;
This will return 123,222,132
For RGB to HEX
$rgb = (123,222,132),
$rgbarr = explode(",",$rgb,3);
echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]);
This will return #7bde84
if you do not expect that your list
will be recreated then you can use the same approach as you've used for Asp.Net (instead of DataSource
this property in WPF is usually named ItemsSource
):
this.dataGrid1.ItemsSource = list;
But if you would like to replace your list
with new collection instance then you should consider using databinding
.
I found an easy way to do this -
Just enter a command like this -
>mvn -Dtest=TestClassName#methodname -Dmaven.surefire.debug test
It will start listening to 5005 port. Now just create a remote debugging in Eclipse through Debug Configurations for localhost(any host) and port 5005.
Source - https://doc.nuxeo.com/display/CORG/How+to+Debug+a+Test+Run+with+Maven
Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.
Use Bat To Exe Converter and compile the Bat file as an executable.
Steps:
You should use heredoc
or nowdoc
.
$var = "some text";
$text = <<<EOT
Place your text between the EOT. It's
the delimiter that ends the text
of your multiline string.
$var
EOT;
The difference between heredoc
and nowdoc
is that PHP code embedded in a heredoc
gets executed, while PHP code in nowdoc
will be printed out as is.
$var = "foo";
$text = <<<'EOT'
My $var
EOT;
In this case $text
will have the value "My $var"
, not "My foo"
.
Notes:
EOT;
there should be no spaces or tabs. otherwise you will get an error.EOT
) that enclose the text is arbitrary, that is, one can use other strings, e.g. <<<FOO
and FOO;
You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.
You are trying to do a logarithm of something that is not positive.
Logarithms figure out the base after being given a number and the power it was raised to. log(0)
means that something raised to the power of 2
is 0
. An exponent can never result in 0
*, which means that log(0)
has no answer, thus throwing the math domain error
*Note: 0^0
can result in 0
, but can also result in 1
at the same time. This problem is heavily argued over.
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
Java does not (yet) support closures. But there are other languages like Scala and Groovy which run in the JVM and do support closures.
I have a Samsung Galaxy and I had the same issue as you. Here's how to fix it:
In device manager on your Windows PC, even though it might say the USB drivers are installed correctly, there may exist corruption.
I went into device manager and uninstalled SAMSUNG Android USB Composite Device and made sure to check the box 'delete driver software'. Now the device will have an exclamation mark etc. I right clicked and installed the driver again (refresh copy). This finally made adb acknowledge my phone as an emulator.
As others noted, for Nexus 4, you can also try this fix.
For compare hashed password with the plain text password string you can use the PHP password_verify
if(password_verify('1234567', $crypt_password_string)) {
// in case if "$crypt_password_string" actually hides "1234567"
}
Yes the second syntax is fine.
Have you tried using the SPF wizard? https://www.spfwizard.net/
It can quickly generate basic and complex SPF records.
Suppose you want to load RegistrationComponent on load and then ConfirmationComponent on some event click on RegistrationComponent.
So in appModule.ts
, you can write like this.
RouterModule.forRoot([
{
path: '',
redirectTo: 'registration',
pathMatch: 'full'
},
{
path: 'registration',
component: RegistrationComponent
},
{
path : 'confirmation',
component: ConfirmationComponent
}
])
OR
RouterModule.forRoot([
{
path: '',
component: RegistrationComponent
},
{
path : 'confirmation',
component: ConfirmationComponent
}
])
is also fine. Choose whatever you like.
We found that older iPhones and iPads, running iOS versions 9 & 10, occasionally return bogus blank AJAX results, perhaps due to Apple's turning down CPU speed. When returning the blank result, iOS does not call the server, as if returning a result from cache. Frequency varies widely, from roughly 10% to 30% of AJAX calls return blank.
The solution is hard to believe. Just wait 1s and call again. In our testing, only one repeat was all that was ever needed, but we wrote the code to call up to 4 times. We're not sure if the 1s wait is required, but we didn't want to risk burdening our server with bursts of repeated calls.
We found the problem happened with two different AJAX calls, calling on different API files with different data. But I'm concerned it could happen on any AJAX call. We just don't know because we don't inspect every AJAX result and we don't test every call multiple times on old devices.
Both problem AJAX calls were using: POST, Asynchronously = true, setRequestHeader = ('Content-Type', 'application/x-www-form-urlencoded')
When the problem happens, there's usually only one AJAX call going on. So it's not due to overlapping AJAX calls. Sometimes the problem happens when the device is busy, but sometimes not, and without DevTools we don't really know what's happening at the time.
iOS 13 doesn't do this, nor Chrome or Firefox. We don't have any test devices running iOS 11 or 12. Perhaps someone else could test those?
I'm noting this here because this question is the top Google result when searching for this problem.
You want the Pillow library, here is how to install it on Python 3:
pip3 install Pillow
If that does not work for you (it should), try normal pip
:
pip install Pillow
I like to use:
make --debug=j
https://linux.die.net/man/1/make
--debug[=FLAGS]
Print debugging information in addition to normal processing. If the FLAGS are omitted, then the behavior is the same as if -d
was specified. FLAGS may be a for all debugging output (same as using -d
), b
for basic debugging, v
for more verbose basic debugging, i
for showing implicit rules, j
for details on invocation of commands, and m
for debugging while remaking makefiles.
Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.
If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.
Syntax of waitpid()
:
pid_t waitpid(pid_t pid, int *status, int options);
The value of pid
can be:
pid
.pid
.The value of options is an OR of zero or more of the following constants:
WNOHANG
: Return immediately if no child has exited.WUNTRACED
: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.WCONTINUED
: Also return if a stopped child has been resumed by delivery of SIGCONT
.For more help, use man waitpid
.
Merging using an EqualityComparer
that maps items for comparison to a different value/type. Here we will map from KeyValuePair
(item type when enumerating a dictionary) to Key
.
public class MappedEqualityComparer<T,U> : EqualityComparer<T>
{
Func<T,U> _map;
public MappedEqualityComparer(Func<T,U> map)
{
_map = map;
}
public override bool Equals(T x, T y)
{
return EqualityComparer<U>.Default.Equals(_map(x), _map(y));
}
public override int GetHashCode(T obj)
{
return _map(obj).GetHashCode();
}
}
Usage:
// if dictA and dictB are of type Dictionary<int,string>
var dict = dictA.Concat(dictB)
.Distinct(new MappedEqualityComparer<KeyValuePair<int,string>,int>(item => item.Key))
.ToDictionary(item => item.Key, item=> item.Value);
If you look at the exception stack trace it says that, it failed to convert from ABDeadlineType
to DeadlineType
. Because your repository is going to return you the objects of ABDeadlineType
. How the spring-data-jpa
will convert into the other one(DeadlineType
). You should return the same type from repository and then have some intermediate util class to convert it into your model class.
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
List<ABDeadlineType> findAllSummarizedBy();
}
You have to click and hold until the other icon shows up, then slide the mouse down to the icon.
This works with font awesome:
<button class="btn btn-outline-success">
<i class="fa fa-print" aria-hidden="true"></i>
Print
</button>
Add a -v flag with your git command . e.g.
git pull -v
v stands for verify .
Since strptime
returns a datetime object which has tzinfo
attribute, We can simply replace it with desired timezone.
>>> import datetime
>>> date_time_str = '2018-06-29 08:15:27.243860'
>>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc)
>>> date_time_obj.tzname()
'UTC'
The default is height: auto
in browser, but height: X%
Defines the height in percentage of the containing block.
To get a full list of colors to use in plots:
import matplotlib.colors as colors
colors_list = list(colors._colors_full_map.values())
So, you can use in that way quickly:
scatter(X,Y, color=colors_list[0])
scatter(X,Y, color=colors_list[1])
scatter(X,Y, color=colors_list[2])
...
scatter(X,Y, color=colors_list[-1])
I used this in my code:
<div class="sticky-top h-100">
<nav id="sidebar" class="vh-100">
....
this cause your sidebar height become 100% and fixed at top.
The very main difference between PCDATA and CDATA is
PCDATA - Basically used for ELEMENTS while
CDATA - Used for Attributes of XML i.e ATTLIST
When the FragmentPagerAdapter
adds a fragment to the FragmentManager, it uses a special tag based on the particular position that the fragment will be placed. FragmentPagerAdapter.getItem(int position)
is only called when a fragment for that position does not exist. After rotating, Android will notice that it already created/saved a fragment for this particular position and so it simply tries to reconnect with it with FragmentManager.findFragmentByTag()
, instead of creating a new one. All of this comes free when using the FragmentPagerAdapter
and is why it is usual to have your fragment initialisation code inside the getItem(int)
method.
Even if we were not using a FragmentPagerAdapter
, it is not a good idea to create a new fragment every single time in Activity.onCreate(Bundle)
. As you have noticed, when a fragment is added to the FragmentManager, it will be recreated for you after rotating and there is no need to add it again. Doing so is a common cause of errors when working with fragments.
A usual approach when working with fragments is this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
CustomFragment fragment;
if (savedInstanceState != null) {
fragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag("customtag");
} else {
fragment = new CustomFragment();
getSupportFragmentManager().beginTransaction().add(R.id.container, fragment, "customtag").commit();
}
...
}
When using a FragmentPagerAdapter
, we relinquish fragment management to the adapter, and do not have to perform the above steps. By default, it will only preload one Fragment in front and behind the current position (although it does not destroy them unless you are using FragmentStatePagerAdapter
). This is controlled by ViewPager.setOffscreenPageLimit(int). Because of this, directly calling methods on the fragments outside of the adapter is not guaranteed to be valid, because they may not even be alive.
To cut a long story short, your solution to use putFragment
to be able to get a reference afterwards is not so crazy, and not so unlike the normal way to use fragments anyway (above). It is difficult to obtain a reference otherwise because the fragment is added by the adapter, and not you personally. Just make sure that the offscreenPageLimit
is high enough to load your desired fragments at all times, since you rely on it being present. This bypasses lazy loading capabilities of the ViewPager, but seems to be what you desire for your application.
Another approach is to override FragmentPageAdapter.instantiateItem(View, int)
and save a reference to the fragment returned from the super call before returning it (it has the logic to find the fragment, if already present).
For a fuller picture, have a look at some of the source of FragmentPagerAdapter (short) and ViewPager (long).
You'll need to open the workbook to refer to it.
Sub Setwbk()
Dim wbk As Workbook
Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
Master Benchmark Data Sheet.xlsx")
End Sub
* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:
Why do I have to "set" it?
Set
is how VBA assigns object variables. Since a Range
and a Workbook
/Worksheet
are objects, you must use Set
with these.
In as few words as possible:
String query = "INSERT INTO ....";
PreparedStatement preparedStatement = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setXXX(1, VALUE);
preparedStatement.setXXX(2, VALUE);
....
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
int key = rs.next() ? rs.getInt(1) : 0;
if(key!=0){
System.out.println("Generated key="+key);
}
Many answers here claims to use git reset ... <file>
or git checkout ... <file>
but by doing so, you will loose every modifications on <file>
committed after the commit you want to revert.
If you want to revert changes from one commit on a single file only, just as git revert
would do but only for one file (or say a subset of the commit files), I suggest to use both git diff
and git apply
like that (with <sha>
= the hash of the commit you want to revert) :
git diff <sha>^ <sha> path/to/file.ext | git apply -R
Basically, it will first generate a patch corresponding to the changes you want to revert, and then reverse-apply the patch to drop those changes.
Of course, it shall not work if reverted lines had been modified by any commit between <sha1>
and HEAD
(conflict).
For the love of $DEITY please do not make a busy-wait sleep function. setTimeout
and setInterval
do everything you need.
var showHide = document.getElementById('showHide');_x000D_
setInterval(() => {_x000D_
showHide.style.visibility = "initial";_x000D_
setTimeout(() => {_x000D_
showHide.style.visibility = "hidden"_x000D_
}, 1000);_x000D_
;_x000D_
}, 2000);
_x000D_
<div id="showHide">Hello! Goodbye!</div>
_x000D_
Every two second interval hide text for one second. This shows how to use setInterval and setTimeout to show and hide text each second.
I like darkporter's idea because it will be easy for a dev team new to AngularJS to understand and worked straight away.
I created this adaptation which uses 2 divs, one for loader bar and another for actual content displayed after data is loaded. Error handling would be done elsewhere.
Add a 'ready' flag to $scope:
$http({method: 'GET', url: '...'}).
success(function(data, status, headers, config) {
$scope.dataForView = data;
$scope.ready = true; // <-- set true after loaded
})
});
In html view:
<div ng-show="!ready">
<!-- Show loading graphic, e.g. Twitter Boostrap progress bar -->
<div class="progress progress-striped active">
<div class="bar" style="width: 100%;"></div>
</div>
</div>
<div ng-show="ready">
<!-- Real content goes here and will appear after loading -->
</div>
See also: Boostrap progress bar docs
function showPanel(fieldName) {
var fieldNameElement = document.getElementById("field_name");
while(fieldNameElement.childNodes.length >= 1) {
fieldNameElement.removeChild(fieldNameElement.firstChild);
}
fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName));
}
The advantages of doing it this way:
If I were going to use a javascript library, I'd use jQuery, and do this:
$("div#field_name").text(fieldName);
Note that @AnthonyWJones' comment is correct: "field_name" isn't a particularly descriptive id or variable name.
Try to use it
LayoutInflater inflater = (LayoutInflater).getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflate.from(YourActivity.this).inflate(R.layout.yourLayout, null);
Try this:
in.nextLine();
This advances the Scanner to the next line.
Unicode and encodings are completely different, unrelated things.
Assigns a numeric ID to each character:
So, Unicode assigns the number 0x41 to A, 0xE1 to á, and 0x414 to ?.
Even the little arrow ? I used has its Unicode number, it's 0x2192. And even emojis have their Unicode numbers, is 0x1F602.
You can look up the Unicode numbers of all characters in this table. In particular, you can find the first three characters above here, the arrow here, and the emoji here.
These numbers assigned to all characters by Unicode are called code points.
The purpose of all this is to provide a means to unambiguously refer to a each character. For example, if I'm talking about , instead of saying "you know, this laughing emoji with tears", I can just say, Unicode code point 0x1F602. Easier, right?
Note that Unicode code points are usually formatted with a leading U+
, then the hexadecimal numeric value padded to at least 4 digits. So, the above examples would be U+0041, U+00E1, U+0414, U+2192, U+1F602.
Unicode code points range from U+0000 to U+10FFFF. That is 1,114,112 numbers. 2048 of these numbers are used for surrogates, thus, there remain 1,112,064. This means, Unicode can assign a unique ID (code point) to 1,112,064 distinct characters. Not all of these code points are assigned to a character yet, and Unicode is extended continuously (for example, when new emojis are introduced).
The important thing to remember is that all Unicode does is to assign a numerical ID, called code point, to each character for easy and unambiguous reference.
Map characters to bit patterns.
These bit patterns are used to represent the characters in computer memory or on disk.
There are many different encodings that cover different subsets of characters. In the English-speaking world, the most common encodings are the following:
Maps 128 characters (code points U+0000 to U+007F) to bit patterns of length 7.
Example:
You can see all the mappings in this table.
Maps 191 characters (code points U+0020 to U+007E and U+00A0 to U+00FF) to bit patterns of length 8.
Example:
You can see all the mappings in this table.
Maps 1,112,064 characters (all existing Unicode code points) to bit patterns of either length 8, 16, 24, or 32 bits (that is, 1, 2, 3, or 4 bytes).
Example:
The way UTF-8 encodes characters to bit strings is very well described here.
Looking at the above examples, it becomes clear how Unicode is useful.
For example, if I'm Latin-1 and I want to explain my encoding of á, I don't need to say:
"I encode that a with an aigu (or however you call that rising bar) as 11100001"
But I can just say:
"I encode U+00E1 as 11100001"
And if I'm UTF-8, I can say:
"Me, in turn, I encode U+00E1 as 11000011 10100001"
And it's unambiguously clear to everybody which character we mean.
It's true that sometimes the bit pattern of an encoding, if you interpret it as a binary number, is the same as the Unicode code point of this character.
For example:
Of course, this has been arranged like this on purpose for convenience. But you should look at it as a pure coincidence. The bit pattern used to represent a character in memory is not tied in any way to the Unicode code point of this character.
Nobody even says that you have to interpret a bit string like 11100001 as a binary number. Just look at it as the sequence of bits that Latin-1 uses to encode the character á.
The encoding used by your Python interpreter is UTF-8.
Here's what's going on in your examples:
The following encodes the character á in UTF-8. This results in the bit string 11000011 10100001, which is saved in the variable a
.
>>> a = 'á'
When you look at the value of a
, its content 11000011 10100001 is formatted as the hex number 0xC3 0xA1 and output as '\xc3\xa1'
:
>>> a
'\xc3\xa1'
The following saves the Unicode code point of á, which is U+00E1, in the variable ua
(we don't know which data format Python uses internally to represent the code point U+00E1 in memory, and it's unimportant to us):
>>> ua = u'á'
When you look at the value of ua
, Python tells you that it contains the code point U+00E1:
>>> ua
u'\xe1'
The following encodes Unicode code point U+00E1 (representing character á) with UTF-8, which results in the bit pattern 11000011 10100001. Again, for output this bit pattern is represented as the hex number 0xC3 0xA1:
>>> ua.encode('utf-8')
'\xc3\xa1'
The following encodes Unicode code point U+00E1 (representing character á) with Latin-1, which results in the bit pattern 11100001. For output, this bit pattern is represented as the hex number 0xE1, which by coincidence is the same as the initial code point U+00E1:
>>> ua.encode('latin1')
'\xe1'
There's no relation between the Unicode object ua
and the Latin-1 encoding. That the code point of á is U+00E1 and the Latin-1 encoding of á is 0xE1 (if you interpret the bit pattern of the encoding as a binary number) is a pure coincidence.
Use this as your WHERE condition
WHERE CHARINDEX('Apples', column) = 0
Using Bash Parameter Expansion:
orig="AxxBCyyyDEFzzLMN"
mod=${orig//[xyz]/_}
The .NET documentation says: State Property: A bitwise combination of the ConnectionState values
So I think you should check
!myConnection.State.HasFlag(ConnectionState.Open)
instead of
myConnection.State != ConnectionState.Open
because State can have multiple flags.
When you use recv
in connection with select
if the socket is ready to be read from but there is no data to read that means the client has closed the connection.
Here is some code that handles this, also note the exception that is thrown when recv
is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :
def listenToSockets(self):
while True:
changed_sockets = self.currentSockets
ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)
for s in ready_to_read:
if s == self.serverSocket:
self.acceptNewConnection(s)
else:
self.readDataFromSocket(s)
And the function that receives the data :
def readDataFromSocket(self, socket):
data = ''
buffer = ''
try:
while True:
data = socket.recv(4096)
if not data:
break
buffer += data
except error, (errorCode,message):
# error 10035 is no data available, it is non-fatal
if errorCode != 10035:
print 'socket.error - ('+str(errorCode)+') ' + message
if data:
print 'received '+ buffer
else:
print 'disconnected'
In PowerShell pwd
is an alias to Get-Location
so you can simply run pwd
in it like in bash
It can also be called from cmd like this powershell -Command pwd
although cd
or echo %cd%
in cmd would work just fine
Use Perl's URI::Escape
module and uri_escape
function in the second line of your bash script:
...
value="$(perl -MURI::Escape -e 'print uri_escape($ARGV[0]);' "$2")"
...
Edit: Fix quoting problems, as suggested by Chris Johnsen in the comments. Thanks!
Simple Answer: NO
Well, at least a naming convention as such encouraged by Oracle or community, no, however, basically you have to be aware of following the rules and limits for identifiers, such as indicated in MySQL documentation: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
About the naming convention you follow, I think it is ok, just the number 5 is a little bit unnecesary, I think most visual tools for managing databases offer a option for sorting column names (I use DBeaver, and it have it), so if the purpouse is having a nice visual presentation of your table you can use this option I mention.
By personal experience, I would recommed this:
lower_case_table_names
is not correctly configured and your server start throwing errors just by simply unrecognizing your camelCase or PascalCase standard (case sensitivity problem).And what about the "Plural vs Singular" naming? Well, this is most a situation of personal preferences. In my case I try to use plural names for tables because I think a table as a collection of elements or a package containig elements, so a plural name make sense for me; and singular names for columns because I see columns as attributes that describe singularly to those table elements.
I wrote a library that can help with type convertions https://github.com/KromDaniel/jonson
js := jonson.New([]interface{}{55.6, 70.8, 10.4, 1, "48", "-90"})
js.SliceMap(func(jsn *jonson.JSON, index int) *jonson.JSON {
jsn.MutateToInt()
return jsn
}).SliceMap(func(jsn *jonson.JSON, index int) *jonson.JSON {
if jsn.GetUnsafeInt() > 50{
jsn.MutateToString()
}
return jsn
}) // ["55","70",10,1,48,-90]
With the find
method, your callback is going to be passed the value of each element, like:
{
description: 'object1', id: 1
}
Thus, you want code like:
_.find(savedViews, function(o) {
return o.description === view;
})
I just spent several hours on this fershlugginer issue, which cropped up after renewing my development license. To reiterate, everything was working without a hitch, then (thank you Apple!) it all got screwed up and stayed screwed up. None of the Apple official troubleshooting steps (linked to above) or possible resolution steps mentioned here resolved the issue for me.
What finally did it for me was to delete both my development and distribution certificates, revoke them in the provisioning portal, and then let Xcode AUTOMATICALLY refresh/issue them. Nothing else, in any order, was able to get both required certificates into my keychain with the private key correctly attached.
SELECT definition + char(13) + 'GO' FROM MyDatabase.sys.sql_modules s INNER JOIN MyDatabase.sys.procedures p ON [s].[object_id] = [p].[object_id] WHERE p.name LIKE 'Something%'" queryout "c:\SP_scripts.sql -S MyInstance -T -t -w
get the sp and execute it
This will work if the department, salary and employee name are in the same table.
select ed.emp_name, ed.salary, ed.dept from
(select max(salary) maxSal, dept from emp_dept group by dept) maxsaldept
inner join emp_dept ed
on ed.dept = maxsaldept.dept and ed.salary = maxsaldept.maxSal
Is there any better solution than this?
following sequence of commands works (I lose the first line of the data -no header=None present-, but at least it loads):
df = pd.read_csv(filename,
usecols=range(0, 42))
df.columns = ['YR', 'MO', 'DAY', 'HR', 'MIN', 'SEC', 'HUND',
'ERROR', 'RECTYPE', 'LANE', 'SPEED', 'CLASS',
'LENGTH', 'GVW', 'ESAL', 'W1', 'S1', 'W2', 'S2',
'W3', 'S3', 'W4', 'S4', 'W5', 'S5', 'W6', 'S6',
'W7', 'S7', 'W8', 'S8', 'W9', 'S9', 'W10', 'S10',
'W11', 'S11', 'W12', 'S12', 'W13', 'S13', 'W14']
Following does NOT work:
df = pd.read_csv(filename,
names=['YR', 'MO', 'DAY', 'HR', 'MIN', 'SEC', 'HUND',
'ERROR', 'RECTYPE', 'LANE', 'SPEED', 'CLASS',
'LENGTH', 'GVW', 'ESAL', 'W1', 'S1', 'W2', 'S2',
'W3', 'S3', 'W4', 'S4', 'W5', 'S5', 'W6', 'S6',
'W7', 'S7', 'W8', 'S8', 'W9', 'S9', 'W10', 'S10',
'W11', 'S11', 'W12', 'S12', 'W13', 'S13', 'W14'],
usecols=range(0, 42))
CParserError: Error tokenizing data. C error: Expected 53 fields in line 1605634, saw 54 Following does NOT work:
df = pd.read_csv(filename,
header=None)
CParserError: Error tokenizing data. C error: Expected 53 fields in line 1605634, saw 54
Hence, in your problem you have to pass usecols=range(0, 2)
A classic "or" would be |
. For example, ab|de
would match either side of the expression.
However, for something like your case you might want to use the ?
quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:
\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+
This pattern will match:
\d+
: One or more numbers.\s+
: One or more whitespaces.[A-Z\s]+
: One or more uppercase characters or space characters\s+
: One or more whitespaces.[A-Z][A-Za-z\s]+
: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.If you'd like a more static check, e.g. indeed only match ABC
and A ABC
, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):
\d (?:ABC|A ABC) Street
Or another alternative using a quantifier:
\d (?:A )?ABC Street
Regardless of how do you index the pushbacks your vector contains 10 elements indexed from 0
(0
, 1
, ..., 9
). So in your second loop v[j]
is invalid, when j
is 10
.
This will fix the error:
for(int j = 9;j >= 0;--j)
{
cout << v[j];
}
In general it's better to think about indexes as 0
based, so I suggest you change also your first loop to this:
for(int i = 0;i < 10;++i)
{
v.push_back(i);
}
Also, to access the elements of a container, the idiomatic approach is to use iterators (in this case: a reverse iterator):
for (vector<int>::reverse_iterator i = v.rbegin(); i != v.rend(); ++i)
{
std::cout << *i << std::endl;
}