Sometimes, you have to send message from another Thread
to UI thread. This type of scenario occurs when you can't execute Network/IO operations on UI thread.
Below example handles that scenario.
Runnable
on UI thread. So post your Runnable
to handler on HandlerThread
Runnable
and send it back to UI thread and show a Toast
message.Solution:
HandlerThread
:requestHandler
responseHandler
and override handleMessage
methodpost
a Runnable
task on requestHandler
Runnable
task, call sendMessage
on responseHandler
sendMessage
result invocation of handleMessage
in responseHandler
.Message
and process it, update UISample code:
/* Handler thread */
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
Handler requestHandler = new Handler(handlerThread.getLooper());
final Handler responseHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
//txtView.setText((String) msg.obj);
Toast.makeText(MainActivity.this,
"Runnable on HandlerThread is completed and got result:"+(String)msg.obj,
Toast.LENGTH_LONG)
.show();
}
};
for ( int i=0; i<5; i++) {
Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
/* Add your business logic here and construct the
Messgae which should be handled in UI thread. For
example sake, just sending a simple Text here*/
String text = "" + (++rId);
Message msg = new Message();
msg.obj = text.toString();
responseHandler.sendMessage(msg);
System.out.println(text.toString());
} catch (Exception err) {
err.printStackTrace();
}
}
};
requestHandler.post(myRunnable);
}
Useful articles:
handlerthreads-and-why-you-should-be-using-them-in-your-android-apps
If all else fails (including not having the timeout
command) the concept in this shell script will work:
#!/bin/bash
set -u
ssh $1 "sleep 10 ; uptime" > /tmp/outputfile 2>&1 & PIDssh=$!
Count=0
while test $Count -lt 5 && ps -p $PIDssh > /dev/null
do
echo -n .
sleep 1
Count=$((Count+1))
done
echo ""
if ps -p $PIDssh > /dev/null
then
echo "ssh still running, killing it"
kill -HUP $PIDssh
else
echo "Exited"
fi
This only inserts if the item to be inserted is not already present.
Works the same as:
if not exists (...) insert ...
in T-SQL
insert into destination (DESTINATIONABBREV)
select 'xyz' from dual
left outer join destination d on d.destinationabbrev = 'xyz'
where d.destinationid is null;
may not be pretty, but it's handy :)
if val % 1 == 0:
val = int(val)
else:
val = float(val)
This worked for me.
How it works: if the remainder of the quotient of val and 1 is 0, val has to be an integer and can, therefore, be declared to be int without having to worry about losing decimal numbers.
Compare these two situations:
A:
val = 12.00
if val % 1 == 0:
val = int(val)
else:
val = float(val)
print(val)
In this scenario, the output is 12, because 12.00 divided by 1 has the remainder of 0. With this information we know, that val doesn't have any decimals and we can declare val to be int.
B:
val = 13.58
if val % 1 == 0:
val = int(val)
else:
val = float(val)
print(val)
This time the output is 13.58, because when val is divided by 1 there is a remainder (0.58) and therefore val is declared to be a float.
By just declaring the number to be an int (without testing the remainder) decimal numbers will be cut off.
This way there are no zeros in the end and no other than the zeros will be ignored.
If building a project through a build system (Maven, Gradle etc..) works but IntelliJ show Invalid target release
error, then do the following,
Close IntelliJ
Go to the directory of the project
Delete the .idea/ directory
Start IntelliJ with the project's directory
This will re-create the .idea/ directory and will no longer show the error.
NOTE: Any repository specific IntelliJ settings that you have added would be deleted when the .idea/ directory is deleted and they will be re-created with the defaults.
open
is a new access level in Swift 3, introduced with the implementation
of
It is available with the Swift 3 snapshot from August 7, 2016, and with Xcode 8 beta 6.
In short:
open
class is accessible and subclassable outside of the
defining module. An open
class member is accessible and
overridable outside of the defining module.public
class is accessible but not subclassable outside of the
defining module. A public
class member is accessible but
not overridable outside of the defining module.So open
is what public
used to be in previous
Swift releases and the access of public
has been restricted.
Or, as Chris Lattner puts it in
SE-0177: Allow distinguishing between public access and public overridability:
“open” is now simply “more public than public”, providing a very simple and clean model.
In your example, open var hashValue
is a property which is accessible and can be overridden in NSObject
subclasses.
For more examples and details, have a look at SE-0117.
Most simple way is to use boost::lexical_cast:
double value;
try
{
value = boost::lexical_cast<double>(my_string);
}
catch (boost::bad_lexical_cast const&)
{
value = 0;
}
I hope 10 years isn't too late, I used this in Windows Scheduler;
"C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE"
-S BLRREPSRVR\SQLEXPRESS -d Reporting_DB -o "C:\Reports\CHP_Gen.csv" -Q "EXEC dbo.CHP_Generation_Report" -W -w 999 -s ","
It opens sql command .exe and runs a script designed for sql command. The sql command script is very easy to use with a few google searches and trial and error. You can see that it picks a database, defines output location and executes a procedure. The procedure is just a query selecting which rows and columns to display from a table in the database.
Add display: block;
. That's the difference between a <div>
tag and an <a>
tag
.btn {
display: block;
height: 300px;
width: 300px;
border-radius: 50%;
border: 1px solid red;
}
As @filoxo said, you can use document.querySelectorAll
.
If you know that there is only one element with the class you are looking for, or you are interested only in the first one, you can use:
document.querySelector('.class1.class2');
BTW, while .class1.class2
indicates an element with both classes, .class1 .class2
(notice the whitespace) indicates an hierarchy - and element with class class2
which is inside en element with class class1
:
<div class='class1'>
<div>
<div class='class2'>
:
:
And if you want to force retrieving a direct child, use >
sign (.class1 > .class2
):
<div class='class1'>
<div class='class2'>
:
:
For entire information about selectors:
https://www.w3schools.com/jquery/jquery_ref_selectors.asp
One way is to use DispatchQueue.main.asyncAfter
as a lot of people have answered.
Another way is to use perform(_:with:afterDelay:)
. More details here
perform(#selector(delayedFunc), with: nil, afterDelay: 3)
@IBAction func delayedFunc() {
// implement code
}
if you are using centOS or Red Hat, you should first update SElinux. Execute the following statement
ausearch -c 'sshd' --raw | audit2allow -M my-sshd
then you need to execute
semodule -i my-sshd.pp
good luck
For those who use docker-compose
, it’s really easy to set a password without any config file like redis.conf
. Here’s how you would normally use the official Redis image:
redis:
image: 'redis:4-alpine'
ports:
- '6379:6379'
And here’s all you need to change to set a custom password:
redis:
image: 'redis:4-alpine'
command: redis-server --requirepass yourpassword
ports:
- '6379:6379'
Everything will start up as normal and your Redis server will be protected by a password.
For details, this blog post seems to support the idea.
That won't work on Windows for a start. Longs and ints are both 32 bits whether you're compiling for 32 bit or 64 bit windows. I would think checking if the size of a pointer is 8 bytes is probably a more reliable route.
I also have faced the same issue. Initially tried modifying System PATH which does not worked out. Later resolved by installing Micro Visual Studio express.
This error is coming because some process is already running on 8081 port. Stop that process and then run your command, it will run your code. For this first list all the process which are using this port by typing
lsof -i :8081
This command will list the process id (PID) of the process and then kill the node process by using
kill -9 <PID>
Here PID is the process id of the node process.
Second David's answer below: I needed to mount a network drive automatically when users logged in. Dokan SSHFS is a nice tool, but wasn't reliable enough in this case. The copy of Netdrive I found didn't support SSHFS or sftp - not sure if a more recent one does.
The solution I'm trialling now involves adding a virtual network adapter (with file sharing disabled), using plink to open a tunnel via the new adapter to the remote machine running SAMBA, and mounting the network drive against the new adapter. There's another useful tutorial here http://www.blisstonia.com/eolson/notes/smboverssh.php.
The tunnel and network drive can be set up with a login script, so a few seconds after login users can use the mapped drive without needing to take any action.
You may also try appending a space at the start and end of keyword: /\s+123456\s+/i
.
Normaly you can GET and POST parameters in a servlet the same way:
request.getParameter("cmd");
But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.
If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:
BufferedReader reader = request.getReader();
Json post processing example (uses org.json package )
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
try {
JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
// Work with the data using methods like...
// int someInt = jsonObject.getInt("intParamName");
// String someString = jsonObject.getString("stringParamName");
// JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
// JSONArray arr = jsonObject.getJSONArray("arrayParamName");
// etc...
}
For anyone else with this issue that arrives here via Google, please check that the host element of the *ngFor
directive is accurate. By this, I mean that I encountered this error and spent a long time researching fixes before realizing that I had put the *ngFor
on an ng-template
element instead of on my component I wanted to repeat.
Incorrect
<ng-template *ngFor=let group of groups$ | async" ...>
<my-component [prop1]="group.key" ... </my-component>
<\ng-template>
Correct
<my-component *ngFor=let group of groups$ | async" [prop1]="group.key" ... </my-component>
I know this is an obvious mistake in hindsight, but I hope an answer here will save someone the headache I now have.
If you using webpack in your application, you can simply set it there, using DefinePlugin
...
So in your plugin
section, set the NODE_ENV to production
:
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"',
})
]
I think you can assume, that name is unique and all radio in group has the same name. Then you can use jQuery support like that:
$("[name=gender]").val(["Male"]);
Note: Passing array is important.
Conditioned version:
if (!$("[name=gender]:checked").length) {
$("[name=gender]").val(["Male"]);
}
This is for those who want to a portable way to count cpu cores on *bsd, *nix or solaris (haven't tested on aix and hp-ux but should work). It has always worked for me.
dmesg | \
egrep 'cpu[. ]?[0-9]+' | \
sed 's/^.*\(cpu[. ]*[0-9]*\).*$/\1/g' | \
sort -u | \
wc -l | \
tr -d ' '
solaris grep
& egrep
don't have -o
option so sed
is used instead.
check if you are using more than one internet connection to your pc like one is LAN second one is Modem , so disable all lan or modem .
I would use a single Context class inheriting from IdentityDbContext. This way you can have the context be aware of any relations between your classes and the IdentityUser and Roles of the IdentityDbContext. There is very little overhead in the IdentityDbContext, it is basically a regular DbContext with two DbSets. One for the users and one for the roles.
Try the file
command with -i
option.
-i
option Causes the file command to output mime type strings rather than the more traditional human readable ones. Thus it may say text/plain; charset=us-ascii
rather than ASCII text
.
Post both multiple text inputs plus multiple files via Ajax in one Ajax request
HTML
<form class="form-horizontal" id="myform" enctype="multipart/form-data">
<input type="text" name="name" class="form-control">
<input type="text" name="email" class="form-control">
<input type="file" name="image" class="form-control">
<input type="file" name="anotherFile" class="form-control">
Jquery Code
$(document).on('click','#btnSendData',function (event) {
event.preventDefault();
var form = $('#myform')[0];
var formData = new FormData(form);
// Set header if need any otherwise remove setup part
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
}
});
$.ajax({
url: "{{route('sendFormWithImage')}}",// your request url
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
console.log(data);
},
error: function () {
}
});
});
foreach ($array as $key => $val) {
echo $val;
}
To get rid of the if/else awkwardness you could use a using block:
@{
var count = 0;
foreach (var item in Model)
{
using(Html.TableRow(new { @class = (count++ % 2 == 0) ? "alt-row" : "" }))
{
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.Truncate(item.Details, 75)
</td>
<td>
<img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()"
alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
@Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
</td>
}
}
}
Reusable element that make it easier to add attributes:
//Block is take from http://www.codeducky.org/razor-trick-using-block/
public class TableRow : Block
{
private object _htmlAttributes;
private TagBuilder _tr;
public TableRow(HtmlHelper htmlHelper, object htmlAttributes) : base(htmlHelper)
{
_htmlAttributes = htmlAttributes;
}
public override void BeginBlock()
{
_tr = new TagBuilder("tr");
_tr.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(_htmlAttributes));
this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.StartTag));
}
protected override void EndBlock()
{
this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.EndTag));
}
}
Helper method to make razor syntax clearer:
public static TableRow TableRow(this HtmlHelper self, object htmlAttributes)
{
var tableRow = new TableRow(self, htmlAttributes);
tableRow.BeginBlock();
return tableRow;
}
No matching client found for package name 'com.tf' I am pretty sure that the "package_name" in google-services.json is not matching with your "applicationId" in app gradle.
app gradle:
defaultConfig {
applicationId "com.tf" //replace with the package_name in google-services.json =
minSdkVersion 23
targetSdkVersion 26
versionCode 7
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
google-services.json
"client_info": {
"mobilesdk_app_id": "1:23978655351:android:2b2fece6b961cc70",
"android_client_info": {
"package_name": "in.ac.geu.debug"
}
},
Solution: Just make sure the package_name
and applicationId
must be same.
I found new Solution without any required certification to call curl only add two line code.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
This is size improvement of R. Yaghoobi answer
<input type="number" oninput="this.value|=0"/>
_x000D_
We use here standard shorthand for "OR" operator e.g 9 | 2 = 11
in binary: 0b1001 | 0b1010 = 0b1011
. This operator first cast numbers to integers in implicit way and then do OR. But because OR with zero don't change anything so number is cast to integer. OR with non-number string gives 0.
For a project of mine, I needed to create intervals for time-series modeling, and to make the procedure more efficient I created tsmoothie: A python library for time-series smoothing and outlier detection in a vectorized way.
It provides different smoothing algorithms together with the possibility to computes intervals.
Here I use a ConvolutionSmoother
but you can also test it others.
import numpy as np
import matplotlib.pyplot as plt
from tsmoothie.smoother import *
x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.2
# operate smoothing
smoother = ConvolutionSmoother(window_len=5, window_type='ones')
smoother.smooth(y)
# generate intervals
low, up = smoother.get_intervals('sigma_interval', n_sigma=2)
# plot the smoothed timeseries with intervals
plt.figure(figsize=(11,6))
plt.plot(smoother.smooth_data[0], linewidth=3, color='blue')
plt.plot(smoother.data[0], '.k')
plt.fill_between(range(len(smoother.data[0])), low[0], up[0], alpha=0.3)
I point out also that tsmoothie can carry out the smoothing of multiple timeseries in a vectorized way
This is my implementation of the solution suggested by @mhm, where I discarded the use of jQuery.
The variable formId contains the id of the form and msg is an object with messages of my application.
This implementation tries to notify the user with the native HTML 5 error messages, if not possible then alert a generic form error message.
If there are no errors I submit the form.
let applyForm = document.getElementById(formId);
if (!applyForm.checkValidity()) {
if (applyForm.reportValidity) {
applyForm.reportValidity();
} else {
alert(msg.ieErrorForm);
}
} else {
applyForm.submit();
}
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
Or simply Use union, for simple array.
_.union([1,2,3,3], [3,5])
// [1,2,3,5]
distanceTo will give you the distance in meters between the two given location ej target.distanceTo(destination).
distanceBetween give you the distance also but it will store the distance in a array of float( results[0]). the doc says If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]
hope that this helps
i've used distanceTo to get the distance from point A to B i think that is the way to go.
you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3
S3 Static Website Hosting Route All Paths to Index.html
adopted to your needs would be something like
location /service/ {
rewrite ^\/service\/(.*) /$1 break;
proxy_pass http://apache;
}
if you want to end up in http://127.0.0.1:8080/query/params/
if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like
location /service/ {
rewrite ^\/(.*) /$1 break;
proxy_pass http://apache;
}
Super easy way to do this.
let text = "This string is having multiple font"
let attributedText =
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), subString:
"This")
attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), onRange:
NSMakeRange(5, 6))
For more detail click here: https://github.com/iOSTechHub/AttributedString
This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines.
As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.
So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.
I resolved it by giving permission to the user on each of the directories that you're using, like so:
sudo chown user /home/user/git
and so on.
The value for your onClick
attribute should be a function, not a function call.
<button type="submit" onClick={function(){removeTaskFunction(todo)}}>Submit</button>
You don't need jQuery, and there are a bunch of ways to do it, for example:
var parts = myString.split('/');
var answer = parts[parts.length - 1];
Where myString contains your string.
Try this Using the substring(int start, int end); method
String myLongString = "abcdefghij";
if (myLongString .length() >= 10)
String shortStr = myLongString.substring(0, 5)+ "...";
this will return abcde.
If you have a C99 compliant compiler, you can use
mystruct = (struct x){0};
otherwise you should do what David Heffernan wrote, i.e. declare:
struct x empty = {0};
And in the loop:
mystruct = empty;
On Gradle 5.x I use:
wrapper {
gradleVersion = '5.5.1'
}
You could use the xpath :
//div[@class="measure-tab" and .//span[contains(., "someText")]]
Input :
<root>
<div class="measure-tab">
<td> someText</td>
</div>
<div class="measure-tab">
<div>
<div2>
<span>someText2</span>
</div2>
</div>
</div>
</root>
Output :
Element='<div class="measure-tab">
<div>
<div2>
<span>someText2</span>
</div2>
</div>
</div>'
Be aware that when you do press your <leader>
key you have only 1000ms (by default) to enter the command following it.
This is exacerbated because there is no visual feedback (by default) that you have pressed your <leader>
key and vim is awaiting the command; and so there is also no visual way to know when this time out has happened.
If you add set showcmd
to your vimrc
then you will see your <leader>
key appear in the bottom right hand corner of vim (to the left of the cursor location) and perhaps more importantly you will see it disappear when the time out happens.
The length of the timeout can also be set in your vimrc
, see :help timeoutlen
for more information.
I am running Ubuntu 19.04 and followed all the instructions above and then some. Finally, what worked for me was to run
sudo apt autoremove rvm
and now when I try and reinstall RVM it's actually gone. RVM is invasive, to say the least.
Use the PHP DOMDocument
parser.
$doc = new DOMDocument();
// load the HTML string we want to strip
$doc->loadHTML($html);
// get all the script tags
$script_tags = $doc->getElementsByTagName('script');
$length = $script_tags->length;
// for each tag, remove it from the DOM
for ($i = 0; $i < $length; $i++) {
$script_tags->item($i)->parentNode->removeChild($script_tags->item($i));
}
// get the HTML string back
$no_script_html_string = $doc->saveHTML();
This worked me me using the following HTML document:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>
hey
</title>
<script>
alert("hello");
</script>
</head>
<body>
hey
</body>
</html>
Just bear in mind that the DOMDocument
parser requires PHP 5 or greater.
From the command line, enter this:
php -f filename.php
Make sure that filename.php both includes and executes the function you want to test. Anything you echo out will appear in the console, including errors.
Be wary that often the php.ini for Apache PHP is different from CLI PHP (command line interface).
Reference: https://secure.php.net/manual/en/features.commandline.usage.php
-O3 option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels ‘-O2’ and ‘-O1’. The ‘-O3’ optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.
{% load static %}
Please add this template tag on top of the HTML or base HTML file
If you are running MYSQL through XAMPP:
Open XAMPP mysql configuration file (on OSX):
/Applications/XAMPP/etc/my.cnf
Copy the socket path:
socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
Open rails project's database configuration file: myproject/config/database.yml
Add the socket config to the development database config:
-->
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: difiuri_falcioni
pool: 5
username: root
password:
host: localhost
socket: /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
Enjoy :)
The accepted answer doesn't seem to work if you unplug the network cable. Or the server crashes. Or your router crashes. Or if you forget to pay your internet bill. Set the TCP keep-alive options for better reliability.
public static class SocketExtensions
{
public static void SetSocketKeepAliveValues(this Socket instance, int KeepAliveTime, int KeepAliveInterval)
{
//KeepAliveTime: default value is 2hr
//KeepAliveInterval: default value is 1s and Detect 5 times
//the native structure
//struct tcp_keepalive {
//ULONG onoff;
//ULONG keepalivetime;
//ULONG keepaliveinterval;
//};
int size = Marshal.SizeOf(new uint());
byte[] inOptionValues = new byte[size * 3]; // 4 * 3 = 12
bool OnOff = true;
BitConverter.GetBytes((uint)(OnOff ? 1 : 0)).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)KeepAliveTime).CopyTo(inOptionValues, size);
BitConverter.GetBytes((uint)KeepAliveInterval).CopyTo(inOptionValues, size * 2);
instance.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
}
}
// ...
Socket sock;
sock.SetSocketKeepAliveValues(2000, 1000);
The time value sets the timeout since data was last sent. Then it attempts to send and receive a keep-alive packet. If it fails it retries 10 times (number hardcoded since Vista AFAIK) in the interval specified before deciding the connection is dead.
So the above values would result in 2+10*1 = 12 second detection. After that any read / wrtie / poll operations should fail on the socket.
It seems that you didn't update the counter
is the script, use counter++
$this->session->unset_userdata('session_value');
Swift Version of Simon Lee's answer .
// MARK: - Variables
var isCcBccSelected = false // To toggle Bcc.
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// Hide the Bcc Text Field , until CC gets focused in didSelectRowAtIndexPath()
if self.cellTypes[indexPath.row] == CellType.Bcc {
if (isCcBccSelected) {
return 44
} else {
return 0
}
}
return 44.0
}
Then in didSelectRowAtIndexPath()
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
// To Get the Focus of CC, so that we can expand Bcc
if self.cellTypes[indexPath.row] == CellType.Cc {
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? RecipientTableViewCell {
if cell.tag == 1 {
cell.recipientTypeLabel.text = "Cc:"
cell.recipientTextField.userInteractionEnabled = true
cell.recipientTextField.becomeFirstResponder()
isCcBccSelected = true
tableView.beginUpdates()
tableView.endUpdates()
}
}
}
}
This should work:
window.onload = function() {
document.getElementById('about').className = 'expand';
};
Or if you're using jQuery:
$(function() {
$('#about').addClass('expand');
});
I tried using MP4Box for this task, but it couldn't handle the M4V I was dealing with. I had success embedding the SRT as soft subtitles with ffmpeg with the following command line:
ffmpeg -i input.m4v -i input.srt -vcodec copy -acodec copy -scodec copy -map 0:0 -map 0:1 -map 1:0 -y output.mkv
Like you I had to use an MKV output file - I wasn't able to create an M4V file.
Jonathon gave you an approach using dict comprehensions in his answer. Here is an approach that deals with your do something part.
If you want to do something with the values of the dictionary, you don't need a dictionary comprehension at all:
I'm using iteritems(
) since you tagged your question with python-2.7
results = map(some_function, [(k,v) for k,v in a_dict.iteritems() if 'foo' in k])
Now the result will be in a list with some_function
applied to each key/value pair of the dictionary, that has foo
in its key.
If you just want to deal with the values and ignore the keys, just change the list comprehension:
results = map(some_function, [v for k,v in a_dict.iteritems() if 'foo' in k])
some_function
can be any callable, so a lambda would work as well:
results = map(lambda x: x*2, [v for k,v in a_dict.iteritems() if 'foo' in k])
The inner list is actually not required, as you can pass a generator expression to map as well:
>>> map(lambda a: a[0]*a[1], ((k,v) for k,v in {2:2, 3:2}.iteritems() if k == 2))
[4]
If you don't want it to add it to a link, you can just enclose it within a span and that would work.
<span id='clickableAwesomeFont'><i class="fa fa-behance-square fa-4x"></span>
in your css, then you can:
#clickableAwesomeFont {
cursor: pointer
}
Then in java script, you can just add a click handler.
In cases where it's actually not a link, I think this is much cleaner and using a link would be changing its semantics and abusing its meaning.
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
For any ubuntu users visiting this page, I was facing the same error and the issue was XAMPP (LAMPP in ubuntu) was not able to connect to mysql because another mysql service was working so my solution to this issue was
stop mysql service
sudo service mysql stop
restart lampp
sudo /opt/lampp/lampp restart
I had everything set up, but still couldn't see proper error pages for status code 500 on our staging server, despite the fact everything worked fine on local development servers.
I found this blog post from Rick Strahl that helped me.
I needed to add Response.TrySkipIisCustomErrors = true;
to my custom error handling code.
I've tried out many answers on this page, none really worked:
So instead of writing readable code, I decided to use the simple and workable approach mentioned in the question instead.
Hopefully another solution will come up.
I prefer to use map to delete the property and then return the new array item.
array.map(function(item) {
delete item.bad;
return item;
});
_id = "123321"; _user = await likes.find({liker_id: _id},{liked_id:"$liked_id"}); ;
let suppose you have liker_id and liked_id field in the document so by putting "$liked_id" it will return _id and liked_id only.
Have encountered the same issue in my asp.net project, in the end i found the issue is with the target function not static, the issue fixed after I put the keyword static.
[WebMethod]
public static List<string> getRawData()
If you can't use the delay
method as Robert Harvey suggested, you can use setTimeout
.
Eg.
setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one
<span style="color:#ffffff; font-size:18px; line-height:35px; font-family: Calibri;">Our Activities </span>
This works for me well:) As it has been already mentioned above "The font tag has been deprecated, at least in XHTML. It always safe to use span tag. font may not give you desire results, at least in my case it didn't.
Client use convert File to ToBase64String
, after use Xml to promulgate
to Server call, this server use File.WriteAllBytes(path,Convert.FromBase64String(dataFile_Client_sent))
.
Good lucky!
Most of the answers are working fine. We can also check the request header
request()->header('Accept')=='application/json'
to check the request type
There is a tutorial for creating an HTML5 progress bar here. If you don't want to use HTML5 methods or you are looking for an all-browser solution, try this code:
<div style="width: 150px; height: 25px; background-color: #dbdbdb;">
<div style="height: 25px; width:87%; background-color: gold"> </div>
</div>
_x000D_
You can change the color GOLD to any progress bar color and #dbdbdb to the background-color of your progress bar.
You could do a WHILE
loop based on the count on your script length divided by 8000.
EG:
DECLARE @Counter INT
SET @Counter = 0
DECLARE @TotalPrints INT
SET @TotalPrints = (LEN(@script) / 8000) + 1
WHILE @Counter < @TotalPrints
BEGIN
-- Do your printing...
SET @Counter = @Counter + 1
END
You could simply have: var result = (str == "true")
.
I see users in comments wondering how to disable cell editing while allowing row deletion : I managed to do this by setting all columns individually to read only, instead of the DataGrid itself.
<DataGrid IsReadOnly="False">
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True"/>
<DataGridTextColumn IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
dividend % divisor
Dividend is the numeric expression to divide. Dividend must be any expression of integer data type in sql server.
Divisor is the numeric expression to divide the dividend. Divisor must be expression of integer data type except in sql server.
SELECT 15 % 2
Output
1
Dividend = 15
Divisor = 2
Let's say you wanted to query
Query a list of CITY names from STATION with even ID numbers only.
Schema structure for STATION:
ID Number
CITY varchar
STATE varchar
select CITY from STATION as st where st.id % 2 = 0
Will fetch the even set of records
In order to fetch the odd records with Id as odd number.
select CITY from STATION as st where st.id % 2 <> 0
% function reduces the value to either 0 or 1
Update your pom.xml
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.1</version>
</dependency>
Efran Cobisi's suggestion of using an Auto Mapper is a good one. I have used Auto Mapper for a while and it worked well, until I found the much faster alternative, Mapster.
Given a large list or IEnumerable, Mapster outperforms Auto Mapper. I found a benchmark somewhere that showed Mapster being 6 times as fast, but I could not find it again. You could look it up and then, if it is suits you, use Mapster.
One of my favourites are Filtered indexes. Now I can create lightning fast covering indexes for my most critical queries with only minor impact on DML statements.
/Håkan Winther
The code yo have provided runs fine. Remember that if you have your code in the header, you need to wait for the dom to be loaded first. In jQuery it would just be as simple as putting your code inside $(function(e){...});
In normal javascript use window.onLoad(..) or the like... or have the script after the table defnition (yuck!). The snippet you provided runs fine when I have it that way for the following:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<table id='ddReferences'>
<tr>
<td>dfsdf</td>
<td>sdfs</td>
<td>frtyr</td>
<td>hjhj</td>
</tr>
</table>
<script>
var refTab = document.getElementById("ddReferences")
var ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
row = refTab.rows[i];
for ( var j = 0; col = row.cells[j]; j++ ) {
alert(col.firstChild.nodeValue);
}
}
</script>
</body>
</html>
This is not a code issue. It is your default IE settings
To change the "always open" setting:
EDIT: If you ask me , instead of making any changes in the code i would add the following text "Internet Explorer users: To download file, "Rightclick" the link and hit "Save target as" to download the file."
EDIT 2: THIS solution will work perfectly for you. Its a solution i just copied from the other answer. Im not trying to pass it off as my own
Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"
However you must make sure that you specify the type of file(s) you allow. You have mentioned in your post that you want this for any type of file. This will be an issue.
For ex. If your site has images and if the end user clicks these images then they will be downloaded on his computer instead of opening in a new page. Got the point. So you need to specify the file extensions.
what led me to this page is that I set within a page then the inside of an included page I did the increment
and here is the problem
so to solve such a problem, simply use scope="request"
when you declare the variable or the increment
//when you set the variale add scope="request"
<c:set var="nFilters" value="${0}" scope="request"/>
//the increment, it can be happened inside an included page
<c:set var="nFilters" value="${nFilters + 1}" scope="request" />
hope this saves your time
I'm Using Xampp and Laravel 5.8 in Windows 10, and i've been like this before. When i got this problem, My XAMPP is no have Password
Then I tried to delete some codes in
config>database.php
'password' => env('DB_PASSWORD', ''),
And in .env
DB_PASSWORD=SECRET
the Problem is solved
This one worked with me
pip install -- pywin32==227
Warning: this is not safe if executed from multiple sessions at the same time (see caveats below).
Another clever way to do an "UPSERT" in postgresql is to do two sequential UPDATE/INSERT statements that are each designed to succeed or have no effect.
UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
SELECT 3, 'C', 'Z'
WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
The UPDATE will succeed if a row with "id=3" already exists, otherwise it has no effect.
The INSERT will succeed only if row with "id=3" does not already exist.
You can combine these two into a single string and run them both with a single SQL statement execute from your application. Running them together in a single transaction is highly recommended.
This works very well when run in isolation or on a locked table, but is subject to race conditions that mean it might still fail with duplicate key error if a row is inserted concurrently, or might terminate with no row inserted when a row is deleted concurrently. A SERIALIZABLE
transaction on PostgreSQL 9.1 or higher will handle it reliably at the cost of a very high serialization failure rate, meaning you'll have to retry a lot. See why is upsert so complicated, which discusses this case in more detail.
This approach is also subject to lost updates in read committed
isolation unless the application checks the affected row counts and verifies that either the insert
or the update
affected a row.
In addition mysql passwords when not using the IDENTIFIED BY
clause, may be blank values, if non-blank, they may be encrypted. But yes USAGE
is used to modify an account by granting simple resource limiters such as MAX_QUERIES_PER_HOUR
, again this can be specified by also
using the WITH clause, in conjuction with GRANT USAGE
(no privileges added) or GRANT ALL
, you can also specify GRANT USAGE
at the global level, database level, table level,etc....
function createCSSClass(selector, style, hoverstyle)
{
if (!document.styleSheets)
{
return;
}
if (document.getElementsByTagName("head").length == 0)
{
return;
}
var stylesheet;
var mediaType;
if (document.styleSheets.length > 0)
{
for (i = 0; i < document.styleSheets.length; i++)
{
if (document.styleSheets[i].disabled)
{
continue;
}
var media = document.styleSheets[i].media;
mediaType = typeof media;
if (mediaType == "string")
{
if (media == "" || (media.indexOf("screen") != -1))
{
styleSheet = document.styleSheets[i];
}
}
else if (mediaType == "object")
{
if (media.mediaText == "" || (media.mediaText.indexOf("screen") != -1))
{
styleSheet = document.styleSheets[i];
}
}
if (typeof styleSheet != "undefined")
{
break;
}
}
}
if (typeof styleSheet == "undefined") {
var styleSheetElement = document.createElement("style");
styleSheetElement.type = "text/css";
document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
for (i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].disabled) {
continue;
}
styleSheet = document.styleSheets[i];
}
var media = styleSheet.media;
mediaType = typeof media;
}
if (mediaType == "string") {
for (i = 0; i < styleSheet.rules.length; i++)
{
if (styleSheet.rules[i].selectorText.toLowerCase() == selector.toLowerCase())
{
styleSheet.rules[i].style.cssText = style;
return;
}
}
styleSheet.addRule(selector, style);
}
else if (mediaType == "object")
{
for (i = 0; i < styleSheet.cssRules.length; i++)
{
if (styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase())
{
styleSheet.cssRules[i].style.cssText = style;
return;
}
}
if (hoverstyle != null)
{
styleSheet.insertRule(selector + "{" + style + "}", 0);
styleSheet.insertRule(selector + ":hover{" + hoverstyle + "}", 1);
}
else
{
styleSheet.insertRule(selector + "{" + style + "}", 0);
}
}
}
createCSSClass(".modalPopup .header",
" background-color: " + lightest + ";" +
"height: 10%;" +
"color: White;" +
"line-height: 30px;" +
"text-align: center;" +
" width: 100%;" +
"font-weight: bold; ", null);
Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW
, FIRST_COL
, and LAST_COL
, and that _xlSheet
is the name of the ExcelSheet
(using Microsoft.Interop.Excel
)
First, define the range:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
Then, set the background color of that range:
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
Finally, set the font color:
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
And here's the code combined:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
There are two approaches which are not mentioned above, but both of which solve the problem in a way which complies with PEP 8 and allow you to make better use of your space. They are:
msg = (
'This message is so long, that it requires '
'more than {x} lines.{sep}'
'and you may want to add more.').format(
x=x, sep=2*'\n')
print(msg)
Notice how the parentheses are used to allow us not to add plus signs between pure strings, and spread the result over multiple lines without the need for explicit line continuation '\' (ugly and cluttered).
The advantages are same with what is described below, the difference is that you can do it anywhere.
Compared to the previous alternative, it is visually better when inspecting code, because it outlines the start and end of msg
clearly (compare with msg +=
one every line, which needs one additional thinking step to deduce that those lines add to the same string - and what if you make a typo, forgetting a +
on one random line ?).
Regarding this approach, many times we have to build a string using iterations and checks within the iteration body, so adding its pieces within the function call, as shown later, is not an option.
A close alternative is:
msg = 'This message is so long, that it requires '
msg += 'many lines to write, one reason for that\n'
msg += 'is that it contains numbers, like this '
msg += 'one: ' + str(x) +', which take up more space\n'
msg += 'to insert. Note how newlines are also included '
msg += 'and can be better presented in the code itself.'
print(msg)
Though the first is preferable.
The other approach is like the previous ones, though it starts the message on the line below the print
.
The reason for this is to gain space on the left, otherwise the print(
itself "pushes" you to the right. This consumption of indentation is the inherited by the rest of the lines comprising the message, because according to PEP 8 they must align with the opening parenthesis of print
above them. So if your message was already long, this way it's forced to be spread over even more lines.
Contrast:
raise TypeError('aaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaa')
with this (suggested here):
raise TypeError(
'aaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaa')
The line spread was reduced. Of course this last approach does no apply so much to print
, because it is a short call. But it does apply to exceptions.
A variation you can have is:
raise TypeError((
'aaaaaaaaaaaaaaaaaaaaaaaa'
'aaaaaaaaaaaaaaaaaaaaaaaa'
'aaaaa {x} aaaaa').format(x=x))
Notice how you don't need to have plus signs between pure strings. Also, the indentation guides the reader's eyes, no stray parentheses hanging below to the left. The replacements are very readable. In particular, such an approach makes writing code that generates code or mathematical formulas a very pleasant task.
It is OK to throw from your constructor, but you should make sure that your object is constructed after main has started and before it finishes:
class A
{
public:
A () {
throw int ();
}
};
A a; // Implementation defined behaviour if exception is thrown (15.3/13)
int main ()
{
try
{
// Exception for 'a' not caught here.
}
catch (int)
{
}
}
One thing to note when using uuid1
, if you use the default call (without giving clock_seq
parameter) you have a chance of running into collisions: you have only 14 bit of randomness (generating 18 entries within 100ns gives you roughly 1% chance of a collision see birthday paradox/attack). The problem will never occur in most use cases, but on a virtual machine with poor clock resolution it will bite you.
The correct way to create a user in Django is to use the create_user function. This will handle the hashing of the password, etc..
from django.contrib.auth.models import User
user = User.objects.create_user(username='john',
email='[email protected]',
password='glass onion')
d = {1:2, 3:4, 5:6, 7:8}
l = (1,5)
{key: d[key] for key in l}
Here is the way I look at COALESCE...and hopefully it makes sense...
In a simplistic form….
Coalesce(FieldName, 'Empty')
So this translates to…If "FieldName" is NULL, populate the field value with the word "EMPTY".
Now for mutliple values...
Coalesce(FieldName1, FieldName2, Value2, Value3)
If the value in Fieldname1 is null, fill it with the value in Fieldname2, if FieldName2 is NULL, fill it with Value2, etc.
This piece of test code for the AdventureWorks2012 sample database works perfectly & gives a good visual explanation of how COALESCE works:
SELECT Name, Class, Color, ProductNumber,
COALESCE(Class, Color, ProductNumber) AS FirstNotNull
FROM Production.Product
You might want to look at "JavaScript HTML DOM Events" for a general overview of events:
http://www.w3schools.com/jsref/dom_obj_event.asp
PrimeFaces is built on jQuery, so here's jQuery's "Events" documentation:
http://api.jquery.com/category/events/
http://api.jquery.com/category/events/form-events/
http://api.jquery.com/category/events/keyboard-events/
http://api.jquery.com/category/events/mouse-events/
http://api.jquery.com/category/events/browser-events/
Below, I've listed some of the more common events, with comments about where they can be used (taken from jQuery documentation).
Mouse Events
(Any HTML element can receive these events.)
click
dblclick
mousedown
mousemove
mouseover
mouseout
mouseup
Keyboard Events
(These events can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for these event types.)
keydown
keypress
keyup
Form Events
blur
(In recent browsers, the domain of the event has been extended to include all element types.)
change
(This event is limited to <input>
elements, <textarea>
boxes and <select>
elements.)
focus
(This event is implicitly applicable to a limited set of elements, such as form elements (<input>
, <select>
, etc.) and links (<a href>
). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.)
select
(This event is limited to <input type="text">
fields and <textarea>
boxes.)
submit
(It can only be attached to <form>
elements.)
const returnedTarget = Object.assign(target, source);
and pass empty array to target
in case complex objects this way works for me
$.extend(true, [], originalArray)
in case of array
$.extend(true, {}, originalObject)
in case of object
I find that the best way to do this is to use SUMPRODUCT
instead:
=SUMPRODUCT((A1:A10<>"")*1)
It's also pretty great if you want to throw in more criteria:
=SUMPRODUCT((A1:A10<>"")*(A1:A10>$B$1)*(A1:A10<=$B$2))
Using the width function:
$('div#somediv').width('70%');
will turn:
<div id="somediv" />
into:
<div id="somediv" style="width: 70%;"/>
Most common way:
console.log(object);
However I must mention JSON.stringify
which is useful to dump variables in non-browser scripts:
console.log( JSON.stringify(object) );
The JSON.stringify
function also supports built-in prettification as pointed out by Simon Zyx.
Example:
var obj = {x: 1, y: 2, z: 3};
console.log( JSON.stringify(obj, null, 2) ); // spacing level = 2
The above snippet will print:
{
"x": 1,
"y": 2,
"z": 3
}
On caniuse.com you can view the browsers that support natively the JSON.stringify
function: http://caniuse.com/json
You can also use the Douglas Crockford library to add JSON.stringify
support on old browsers: https://github.com/douglascrockford/JSON-js
Docs for JSON.stringify
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I hope this helps :-)
How do I rename a specific column in pandas?
From v0.24+, to rename one (or more) columns at a time,
DataFrame.rename()
with axis=1
or axis='columns'
(the axis
argument was introduced in v0.21
.
Index.str.replace()
for string/regex based replacement.
If you need to rename ALL columns at once,
DataFrame.set_axis()
method with axis=1
. Pass a list-like sequence. Options are available for in-place modification as well.rename
with axis=1
df = pd.DataFrame('x', columns=['y', 'gdp', 'cap'], index=range(5))
df
y gdp cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
With 0.21+, you can now specify an axis
parameter with rename
:
df.rename({'gdp':'log(gdp)'}, axis=1)
# df.rename({'gdp':'log(gdp)'}, axis='columns')
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
(Note that rename
is not in-place by default, so you will need to assign the result back.)
This addition has been made to improve consistency with the rest of the API. The new axis
argument is analogous to the columns
parameter—they do the same thing.
df.rename(columns={'gdp': 'log(gdp)'})
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
rename
also accepts a callback that is called once for each column.
df.rename(lambda x: x[0], axis=1)
# df.rename(lambda x: x[0], axis='columns')
y g c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
For this specific scenario, you would want to use
df.rename(lambda x: 'log(gdp)' if x == 'gdp' else x, axis=1)
Index.str.replace
Similar to replace
method of strings in python, pandas Index and Series (object dtype only) define a ("vectorized") str.replace
method for string and regex-based replacement.
df.columns = df.columns.str.replace('gdp', 'log(gdp)')
df
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
The advantage of this over the other methods is that str.replace
supports regex (enabled by default). See the docs for more information.
set_axis
with axis=1
Call set_axis
with a list of header(s). The list must be equal in length to the columns/index size. set_axis
mutates the original DataFrame by default, but you can specify inplace=False
to return a modified copy.
df.set_axis(['cap', 'log(gdp)', 'y'], axis=1, inplace=False)
# df.set_axis(['cap', 'log(gdp)', 'y'], axis='columns', inplace=False)
cap log(gdp) y
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
Note: In future releases, inplace
will default to True
.
Method Chaining
Why choose set_axis
when we already have an efficient way of assigning columns with df.columns = ...
? As shown by Ted Petrou in this answer set_axis
is useful when trying to chain methods.
Compare
# new for pandas 0.21+
df.some_method1()
.some_method2()
.set_axis()
.some_method3()
Versus
# old way
df1 = df.some_method1()
.some_method2()
df1.columns = columns
df1.some_method3()
The former is more natural and free flowing syntax.
Well this is not a right answer but can be consider as a quick workaround. Right answer is turn off Strict SSL.
I am having the same error
PhantomJS not found on PATH
Downloading https://github.com/Medium/phantomjs/releases/download/v2.1.1/phantomjs-2.1.1-windows.zip
Saving to C:\Users\Sam\AppData\Local\Temp\phantomjs\phantomjs-2.1.1-windows.zip
Receiving...
Error making request.
Error: unable to get local issuer certificate
at TLSSocket. (_tls_wrap.js:1105:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket._finishInit (_tls_wrap.js:639:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:469:38)
So the after reading the error.
Just downloaded the file manually and placed it on the required path. i.e
C:\Users\Sam\AppData\Local\Temp\phantomjs\
This solved my problem.
PhantomJS not found on PATH
Download already available at C:\Users\sam\AppData\Local\Temp\phantomjs\phantomjs-2.1.1-windows.zip
Verified checksum of previously downloaded file
Extracting zip contents
You can use flexbox to center your text. By the way no need for extra containers because text is considered as anonymous flex item.
From flexbox specs:
Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item. However, an anonymous flex item that contains only white space (i.e. characters that can be affected by the
white-space
property) is not rendered (just as if it weredisplay:none
).
So just make grid items as flex containers (display: flex
), and add align-items: center
and justify-content: center
to center both vertically and horizontally.
Also performed optimization of HTML and CSS:
html,_x000D_
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-template-rows: 100vh;_x000D_
_x000D_
font-family: Raleway;_x000D_
font-size: large;_x000D_
}_x000D_
_x000D_
.left_bg,_x000D_
.right_bg {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.left_bg {_x000D_
background-color: #3498db;_x000D_
}_x000D_
_x000D_
.right_bg {_x000D_
background-color: #ecf0f1;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left_bg">Review my stuff</div>_x000D_
<div class="right_bg">Hire me!</div>_x000D_
</div>
_x000D_
I have tried all of the above solutions (which all bring valid points), but nothing was working for me.
Until I found that my MySQL table field mappings in C# was using an incorrect type: MySqlDbType.Blob . I changed it to MySqlDbType.Text and now I can write all the UTF8 symbols I want!
p.s. My MySQL table field is of the "LongText" type. However, when I autogenerated the field mappings using MyGeneration software, it automatically set the field type as MySqlDbType.Blob in C#.
Interestingly, I have been using the MySqlDbType.Blob type with UTF8 characters for many months with no trouble, until one day I tried writing a string with some specific characters in it.
Hope this helps someone who is struggling to find a reason for the error.
you can change firstItem to id and it will work
you can change the routing on global.asax (i do not recommed that)
and, can't believe no one mentioned this, you can call :
http://localhost:2316/Inventory/ViewStockNext?firstItem=11
In a @Url.Action would be :
@Url.Action("ViewStockNext", "Inventory", new {firstItem=11});
depending on the type of what you are doing, the last will be more suitable. Also you should consider not doing ViewStockNext action and instead a ViewStock action with index. (my 2cents)
Use Tkinter:
https://stackoverflow.com/a/4203897/2804197
try:
from Tkinter import Tk
except ImportError:
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()
(Original author: https://stackoverflow.com/users/449571/atomizer)
If the requested resource of the server is using Flask. Install Flask-CORS.
Use this regular expression to match square brackets or single quotes:
/[\[\]']+/g
Replace with the empty string.
console.log("['abc','xyz']".replace(/[\[\]']+/g,''));
_x000D_
After trying the top answer, I found that you must also restart the computer. The error may be part of a git issue as well where restarting your computer will reset.
var map:Map[String, String] = Map()
var map1 = map + ("red" -> "#FF0000")
println(map1)
This should be a simple check.
Example 1
var myObj = {"a": "test1"}
if(myObj.a == "test1") {
alert("test1 exists!");
}
Change it to:
<div style="background-color:black; overflow:hidden;" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>
Basically the outer div only contains floats. Floats are removed from the normal flow. As such the outer div really contains nothing and thus has no height. It really is black but you just can't see it.
The overflow:hidden property basically makes the outer div enclose the floats. The other way to do this is:
<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
<div style="clear:both></div>
</div>
Oh and just for completeness, you should really prefer classes to direct CSS styles.
Load testing = putting a specified amount of load on the server for certain amount of time. 100 simultaneous users for 10 minutes. Ensure stability of software. Stress testing = increasing the amount of load steadily until the software crashes. 10 simultaneous users increasing every 2 minutes until the server crashes.
To make a comparison to weight lifting: You "max" your weight to see what you can do for 1 rep (stress testing) and then on regular workouts you do 85% of your max value for 3 sets of 10 reps (load testing)
Just because this is what I got when I Googled this error, my problem was that I had
if (value < other.value)
return -1;
else if (value >= other.value)
return 1;
else
return 0;
the value >= other.value
should (obviously) actually be value > other.value
so that you can actually return 0 with equal objects.
If you use gcc, there's gprof available.
I wanted to the know how programmer find memory leak
Some uses tools, some does what you do, could also through peer code review
Is there any standard or procedure one should follow to ensure there is no memory leak in the program
For me: whenever I create dynamically allocated objects, I always put the freeing code after, then fill the code between. This would be OK if you're sure there won't be exceptions in the code between. Otherwise, I make use of try-finally (I don't use C++ frequently).
$_
is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ...
so $_
represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:
write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH
You can actualy fake the transparency of option
DOMElements with the following CSS:
option {
/* Whatever color you want */
background-color: #82caff;
}
The option
tag does not support rgba
colors yet.
echo -e $lines | while read line
...
done
The while
loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.
Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines
will run in a subshell:
while read line
do
if [[ "$line" == "second line" ]]
then
foo=2
echo "Variable \$foo updated to $foo inside if inside while loop"
fi
echo "Value of \$foo in while loop body: $foo"
done <<< "$(echo -e "$lines")"
You can get rid of the rather ugly echo
in the here-string above by expanding the backslash sequences immediately when assigning lines
. The $'...'
form of quoting can be used there:
lines=$'first line\nsecond line\nthird line'
while read line; do
...
done <<< "$lines"
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check if spinner2 has a selected item and show the value in edittext
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// sometimes you need nothing here
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check if spinner1 has a selected item and show the value in edittext
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// sometimes you need nothing here
}
});
I always use 010 Editor to open huge files. It can handle 2 GB easily. I was manipulating files with 50 GB with 010 Editor :-)
It's commercial now, but it has a trial version.
MySQLdb is the straightforward way. You get to execute SQL queries over a connection. Period.
My preferred way, which is also pythonic, is to use the mighty SQLAlchemy instead. Here is a query related tutorial, and here is a tutorial on ORM capabilities of SQLALchemy.
Generally a parameter is what appears in the definition of the method. An argument is the instance passed to the method during runtime.
You can see a description here: http://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments
you can use
date -d "30 days ago" +"%d/%m/%Y"
to get the date from 30 days ago, similarly you can replace 30 with x amount of days
A really easy way is to simply call post()
on your layout. This will run your code the next step, after your view has already been created.
YOUR_LAYOUT.post( new Runnable() {
@Override
public void run() {
int width = YOUR_LAYOUT.getMeasuredWidth();
int height = YOUR_LAYOUT.getMeasuredHeight();
}
});
Pseudo code, something like:
CASE
When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'
This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.
add the -s
(silent) option to remove the progress meter, then redirect stderr to stdout to get verbose output on the same fd as the response body
curl -vs google.com 2>&1 | less
user double quote to get the exact value. like this:
echo "${var}"
and it will read your value correctly.
Padding is the space inside the border, between the border and the actual view's content. Note that padding goes completely around the content: there is padding on the top, bottom, right and left sides (which can be independent).
Margins are the spaces outside the border, between the border and the other elements next to this view. In the image, the margin is the grey area outside the entire object. Note that, like the padding, the margin goes completely around the content: there are margins on the top, bottom, right, and left sides.
An image says more than 1000 words (extracted from Margin Vs Padding - CSS Properties):
I'll have a go at this complicated subject.
The origin itself is the name of a host (scheme, hostname, and port) i.g. https://www.google.com
or could be a locally opened file file://
etc.. It is where something (i.g. a web page) originated from. When you open your web browser and go to https://www.google.com
, the origin of the web page that is displayed to you is https://www.google.com
. You can see this in Chrome Dev Tools under Security
:
The same applies for if you open a local HTML file via your file explorer (which is not served via a server):
When you open your browser and go to https://website.com
, that website will have the origin of https://website.com
. This website will most likely only fetch images, icons, js files and do API calls towards https://website.com
, basically it is calling the same server as it was served from. It is doing calls to the same origin.
If you open your web browser and open a local HTML file and in that html file there is javascript which wants to do a request to google for example, you get the following error:
The same-origin policy tells the browser to block cross-origin requests. In this instance origin null
is trying to do a request to https://www.google.com
(a cross-origin request). The browser will not allow this because of the CORS Policy which is set and that policy is that cross-origin requests is not allowed.
Same applies for if my page was served from a server on localhost:
If we host our own localhost API server running on localhost:3000 with the following code:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/hello', function (req, res) {
// res.header("Access-Control-Allow-Origin", "*");
res.send('Hello World');
})
app.listen(3000, () => {
console.log('alive');
})
And open a HTML file (that does a request to the localhost:3000 server) directory from the file explorer the following error will happen:
Since the web page was not served from the localhost server on localhost:3000 and via the file explorer the origin is not the same as the server API origin, hence a cross-origin request is being attempted. The browser is stopping this attempt due to CORS Policy.
But if we uncomment the commented line:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/hello', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.send('Hello World');
})
app.listen(3000, () => {
console.log('alive');
})
And now try again:
It works, because the server which sends the HTTP response included now a header stating that it is ok for cross-origin requests to happen to the server, this means the browser will let it happen, hence no error.
Following is taken from: https://web.dev/cross-origin-resource-sharing/#how-does-cors-work
Remember, the same-origin policy tells the browser to block cross-origin requests. When you want to get a public resource from a different origin, the resource-providing server needs to tell the browser "This origin where the request is coming from can access my resource". The browser remembers that and allows cross-origin resource sharing.
Step 1: client (browser) request When the browser is making a cross-origin request, the browser adds an Origin header with the current origin (scheme, host, and port).
Step 2: server response On the server side, when a server sees this header, and wants to allow access, it needs to add an Access-Control-Allow-Origin header to the response specifying the requesting origin (or * to allow any origin.)
Step 3: browser receives response When the browser sees this response with an appropriate Access-Control-Allow-Origin header, the browser allows the response data to be shared with the client site.
Here is another good answer, more detailed as to what is happening: https://stackoverflow.com/a/10636765/1137669
You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:
div.parent{
position: relative;
left: 0px; /* stick it wherever it was positioned by default */
top: 0px;
}
div.child{
position: absolute;
left: 10px;
top: 10px;
}
getTime()
retrieves the milliseconds since Jan 1, 1970 GMT passed to the constructor. It should not be too hard to get the Unix time (same, but in seconds) from that.
It's not bullet-proof but for UNIX environments simple test like
if run("which python3").find("venv") == -1:
# something when not executed from venv
works great for me. It's simpler then testing existing of some attribute and, anyway, you should name your venv directory venv
.
Sometimes this works;
sudo apt-get install mongodb-org --fix-missing --fix-broken
sudo apt-get autoremove mongodb-org --fix-missing --fix-broken
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
It is technically possible to put a caption on an ImageButton
if you really want to do it. Just put a TextView
over the ImageButton
using FrameLayout
. Just remember to not make the Textview
clickable.
Example:
<FrameLayout>
<ImageButton
android:id="@+id/button_x"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@null"
android:scaleType="fitXY"
android:src="@drawable/button_graphic" >
</ImageButton>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:text="TEST TEST" >
</TextView>
</FrameLayout>
I was trying to go from godaddy to app engine. What did the trick was using this line:
openssl req -new -newkey rsa:2048 -nodes -keyout name.unencrypted.priv.key -out name.csr
Exactly as is, but replacing name with my domain name (not that it really even mattered)
And I answered all the questions pertaining to common name / organization as www.name.com
Then I opened the csr, copied it, pasted it in go daddy, then downloaded it, unzipped it, navigated to the unzipped folder with the terminal and entered:
cat otherfilegodaddygivesyou.crt gd_bundle-g2-g1.crt > name.crt
Then I used these instructions from Trouble with Google Apps Custom Domain SSL, which were:
openssl rsa -in privateKey.key -text > private.pem
openssl x509 -inform PEM -in www_mydomain_com.crt > public.pem
exactly as is, except instead of privateKey.key I used name.unencrypted.priv.key, and instead of www_mydomain_com.crt, I used name.crt
Then I uploaded the public.pem to the admin console for the "PEM encoded X.509 certificate", and uploaded the private.pem for the "Unencrypted PEM encoded RSA private key"..
.. And that finally worked.
You can use the str.format
method. Examples:
>>> print('{0:.16f}'.format(1.6))
1.6000000000000001
>>> print('{0:.15f}'.format(1.6))
1.600000000000000
Note the 1
at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.
You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):
>>> print '%.16f' % 1.6
1.6000000000000001
>>> print '%.15f' % 1.6
1.600000000000000
i find best for do it fast and simple
find ur item in list
var d = Details.Where(x => x.ProductID == selectedProduct.ID).SingleOrDefault();
make clone from current
OrderDetail dd = d;
Update ur clone
dd.Quantity++;
find index in list
int idx = Details.IndexOf(d);
remove founded item in (1)
Details.Remove(d);
insert
if (idx > -1)
Details.Insert(idx, dd);
else
Details.Insert(Details.Count, dd);
As already answered, you can simply use the trace command:
console.trace("I am here");
However, if you came to this question searching about how to log the stack trace of an exception, you can simply log the Exception object.
try {
// if something unexpected
throw new Error("Something unexpected has occurred.");
} catch (e) {
console.error(e);
}
It will log:
Error: Something unexpected has occurred.
at main (c:\Users\Me\Documents\MyApp\app.js:9:15)
at Object. (c:\Users\Me\Documents\MyApp\app.js:17:1)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
If your Node.js version is < than 6.0.0, logging the Exception object will not be enough. In this case, it will print only:
[Error: Something unexpected has occurred.]
For Node version < 6, use console.error(e.stack)
instead of console.error(e)
to print the error message plus the full stack, like the current Node version does.
Note: if the exception is created as a string like throw "myException"
, it's not possible to retrieve the stack trace and logging e.stack
yields undefined.
To be safe, you can use
console.error(e.stack || e);
and it will work for old and new Node.js versions.
from PyPDF2 import PdfFileMerger
import webbrowser
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
def list_files(directory, extension):
return (f for f in os.listdir(directory) if f.endswith('.' + extension))
pdfs = list_files(dir_path, "pdf")
merger = PdfFileMerger()
for pdf in pdfs:
merger.append(open(pdf, 'rb'))
with open('result.pdf', 'wb') as fout:
merger.write(fout)
webbrowser.open_new('file://'+ dir_path + '/result.pdf')
Git Repo: https://github.com/mahaguru24/Python_Merge_PDF.git
Do a row div.
Like this:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
<div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
</div>_x000D_
</div>
_x000D_
If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.exp(x)
fig1, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_title("Axis 1 title")
ax1.set_xlabel("X-label for axis 1")
z = np.sin(x)
fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
ax2.plot(x, z)
ax3.plot(x, -z)
w = np.cos(x)
ax1.plot(x, w) # can continue plotting on the first axis
It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.
The keyword you're looking for is list comprehensions:
>>> x = [1, 2, 3, 4, 5]
>>> y = [2*a for a in x if a % 2 == 1]
>>> print(y)
[2, 6, 10]
The biggest benefit is that the code is more succinct. The VS editor will also have the IntelliSense support that some of the other view engines don't have.
Declarative HTML Helpers also look pretty cool as doing HTML helpers within C# code reminds me of custom controls in ASP.NET. I think they took a page from partials but with the inline code.
So some definite benefits over the asp.net view engine.
With contrast to a view engine like spark though:
Spark is still more succinct, you can keep the if's and loops within a html tag itself. The markup still just feels more natural to me.
You can code partials exactly how you would do a declarative helper, you'd just pass along the variables to the partial and you have the same thing. This has been around with spark for quite awhile.
As of 2019 here is what I elaborated from the answers above and Guzzle docs to handle the exception, get the response body, status code, message and the other sometimes valuable response items.
try {
/**
* We use Guzzle to make an HTTP request somewhere in the
* following theMethodMayThrowException().
*/
$result = theMethodMayThrowException();
} catch (\GuzzleHttp\Exception\RequestException $e) {
/**
* Here we actually catch the instance of GuzzleHttp\Psr7\Response
* (find it in ./vendor/guzzlehttp/psr7/src/Response.php) with all
* its own and its 'Message' trait's methods. See more explanations below.
*
* So you can have: HTTP status code, message, headers and body.
* Just check the exception object has the response before.
*/
if ($e->hasResponse()) {
$response = $e->getResponse();
var_dump($response->getStatusCode()); // HTTP status code;
var_dump($response->getReasonPhrase()); // Response message;
var_dump((string) $response->getBody()); // Body, normally it is JSON;
var_dump(json_decode((string) $response->getBody())); // Body as the decoded JSON;
var_dump($response->getHeaders()); // Headers array;
var_dump($response->hasHeader('Content-Type')); // Is the header presented?
var_dump($response->getHeader('Content-Type')[0]); // Concrete header value;
}
}
// process $result etc. ...
Voila. You get the response's information in conveniently separated items.
Side Notes:
With catch
clause we catch the inheritance chain PHP root exception class
\Exception
as Guzzle custom exceptions extend it.
This approach may be useful for use cases where Guzzle is used under the hood like in Laravel or AWS API PHP SDK so you cannot catch the genuine Guzzle exception.
In this case, the exception class may not be the one mentioned in the Guzzle docs (e.g. GuzzleHttp\Exception\RequestException
as the root exception for Guzzle).
So you have to catch \Exception
instead but bear in mind it is still the Guzzle exception class instance.
Though use with care. Those wrappers may make Guzzle $e->getResponse()
object's genuine methods not available. In this case, you will have to look at the wrapper's actual exception source code and find out how to get status, message, etc. instead of using Guzzle $response
's methods.
If you call Guzzle directly yourself you can catch GuzzleHttp\Exception\RequestException
or any other one mentioned in their exceptions docs with respect to your use case conditions.
Local fonts linking to your react js may be a failure. So, I prefer to use online css file from google to link fonts. Refer the following code,
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
or
<style>
@import url('https://fonts.googleapis.com/css?family=Roboto');
</style>
os.path.abspath(__file__)
will give you an absolute path (relpath()
available as well).
sys.argv[-1]
will give you a relative path.
Perhaps the below method could be the cause if you've set it to
func webView(_ webView: WebView!,decidePolicyForNavigationAction actionInformation: [AnyHashable : Any]!, request: URLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!)
ends with
decisionHandler(.cancel)
for the default navigationAction.request.url
Hope it works!
You can use the below code on your string and you will get the complete string without html part.
string title = "<b> Hulk Hogan's Celebrity Championship Wrestling <font color=\"#228b22\">[Proj # 206010]</font></b> (Reality Series, )".Replace(" ",string.Empty);
string s = Regex.Replace(title, "<.*?>", String.Empty);
You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.
Simply adding the following line of code should fix your problems:
mainFrame.setLayout(new BorderLayout());
(Do this before adding components to the JFrame)
I agree with others that it's likely how you're accessing the elements that is the problem. Quoting the file names in the array assignment is correct:
FILES=(
"2011-09-04 21.43.02.jpg"
"2011-09-05 10.23.14.jpg"
"2011-09-09 12.31.16.jpg"
"2011-09-11 08.43.12.jpg"
)
for f in "${FILES[@]}"
do
echo "$f"
done
Using double quotes around any array of the form "${FILES[@]}"
splits the array into one word per array element. It doesn't do any word-splitting beyond that.
Using "${FILES[*]}"
also has a special meaning, but it joins the array elements with the first character of $IFS, resulting in one word, which is probably not what you want.
Using a bare ${array[@]}
or ${array[*]}
subjects the result of that expansion to further word-splitting, so you'll end up with words split on spaces (and anything else in $IFS
) instead of one word per array element.
Using a C-style for loop is also fine and avoids worrying about word-splitting if you're not clear on it:
for (( i = 0; i < ${#FILES[@]}; i++ ))
do
echo "${FILES[$i]}"
done
You can use hex colors:
your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
This extension helps you to constraint a UIVIew to its superview and superview+safeArea:
extension UIView {
///Constraints a view to its superview
func constraintToSuperView() {
guard let superview = superview else { return }
translatesAutoresizingMaskIntoConstraints = false
topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
}
///Constraints a view to its superview safe area
func constraintToSafeArea() {
guard let superview = superview else { return }
translatesAutoresizingMaskIntoConstraints = false
topAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.topAnchor).isActive = true
leftAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.leftAnchor).isActive = true
bottomAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.bottomAnchor).isActive = true
rightAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.rightAnchor).isActive = true
}
}
I don't think you can set any part of the sheet to be editable only by VBA, but you can do something that has basically the same effect -- you can unprotect the worksheet in VBA before you need to make changes:
wksht.Unprotect()
and re-protect it after you're done:
wksht.Protect()
Edit: Looks like this workaround may have solved Dheer's immediate problem, but for anyone who comes across this question/answer later, I was wrong about the first part of my answer, as Joe points out below. You can protect a sheet to be editable by VBA-only, but it appears the "UserInterfaceOnly" option can only be set when calling "Worksheet.Protect" in code.
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
If you only want the filename (not the full path) use this:
$ScriptName = $MyInvocation.MyCommand.Name
You have many ways to add Bootstrap 4 in your Angular project:
Including the Bootstrap CSS and JavaScript files in the section of the index.html file of your Angular project with a and tags,
Importing the Bootstrap CSS file in the global styles.css file of your Angular project with an @import keyword.
Adding the Bootstrap CSS and JavaScript files in the styles and scripts arrays of the angular.json file of your project
I would create a property to access the variable, like this:
protected string Test
{
get; set;
}
And in your markup:
<%= this.Test %>
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
this also works:
$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);
then I just run a forloop to grab the stuff from the nodes.
like this:`
for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;
***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.
For clarity since some other comments are incorrect, when using System.Timers
setting Enabled to true will reset the elapsed time. I just tested the behavior with the below:
Timer countDown= new Timer(3000);
Main()
{
TextBox.TextDidChange += TextBox_TextDidChange;
countdown.Elapsed += CountDown_Elapsed;
}
void TextBox_TextDidChange(Object sender, EventArgs e)
{
countdown.Enabled = true;
}
void CountDown_Elapsed(object sender, EventArgs e)
{
System.Console.WriteLine("Elapsed");
}
I would input text to the text box repeatedly and the timer would only run 3 seconds after the last keystroke. It's hinted at in the docs as well, as you'll see: calling Timers.Start()
simply sets Enabled to true.
And to be sure, which I should've just went straight to from the beginning, you'll see in the .NET reference source that if enabling an already Enabled timer it calls the private UpdateTimer()
method, which internally calls Change()
.
Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.
When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.
Words in italics are system calls.
Ref
you'd use another join, something along these lines:
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
EDIT:
All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read here.
In windows 10, just exit out of current login and run this on command line
--> mysqladmin -u root password “newpassword”
where instead of root could be any user.
I'm using VSCode 1.12.1
OSX press : Cmd + pSome reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
By the way - ASP.NET has nothing to do with it. Encodings are universal.
This blog post gives a nice explanation and some background. Basically, the "permanent generation" (whose size is given by PermSize) is used to store things that the JVM has to allocate space for, but which will not (normally) be garbage-collected (hence "permanent") (+). That means for example loaded classes and static fields.
There is also a FAQ on garbage collection directly from Sun, which answers some questions about the permanent generation. Finally, here's a blog post with a lot of technical detail.
(+) Actually parts of the permanent generation will be GCed, e.g. class objects will be removed when a class is unloaded. But that was uncommon when the permanent generation was introduced into the JVM, hence the name.
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).
The 'trick' here is to use the node priority to as the vote count...
The data is:
vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote
,"vote": {
".read" : true
,".write" : true
,"$issue" : {
"user" : {
"$user" : {
".validate" : "!data.exists() &&
newData.val()==data.parent().parent().child('count').getPriority()+1 &&
newData.val()==newData.GetPriority()"
user can only vote once && count must be one higher than current count && data value must be same as priority.
}
}
,"count" : {
".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
newData.getPriority()==data.getPriority()+1 "
}
count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.
}
}
Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.
<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
window.fb = new Firebase('https:...vote/iss1/');
window.fb.child('count').once('value', function (dss) {
votes = dss.getPriority();
for (var i=1;i<10;i++) vote(dss,i+votes);
} );
function vote(dss,count)
{
var user='user/zz' + count; // replace with auth.id or whatever
window.fb.child(user).setWithPriority(count,count);
window.fb.child('count').setWithPriority(user,count);
}
</script>
The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)
The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).
You can use extension methods to do the same thing with less code.
public enum AccountType
{
Retailer = 1,
Customer = 2,
Manager = 3,
Employee = 4
}
static class AccountTypeMethods
{
public static bool IsRetailer(this AccountType ac)
{
return ac == AccountType.Retailer;
}
}
And to use:
if (userProfile.AccountType.isRetailer())
{
//your code
}
I would recommend to rename the AccountType
to Account
. It's not a name convention.
In brief words:
If you need better sorting order - use utf8_unicode_ci
(this is the preferred method),
but if you utterly interested in performance - use utf8_general_ci
, but know that it is a little outdated.
The differences in terms of performance are very slight.
You could do it like this:
<a>
with a class, say "cancel"set up the dialog by acting on all elements with class="cancel":
$('a.cancel').click(function() {
var a = this;
$('#myDialog').dialog({
buttons: {
"Yes": function() {
window.location = a.href;
}
}
});
return false;
});
(plus your other options)
The key points here are:
However, I recommend that you make this a POST instead of a GET, since a cancel action has side effects and thus doesn't comply with GET semantics...
To specify a port for the ASP.NET Development Server
In Solution Explorer, click the name of the application.
In the Properties pane, click the down-arrow beside Use dynamic ports and select False from the dropdown list.
This will enable editing of the Port number property.
In the Properties pane, click the text box beside Port number and
type in a port number. Click outside of the Properties pane. This
saves the property settings.
Each time you run a file-system Web site within Visual Web Developer, the ASP.NET Development Server will listen on the specified port.
Hope this helps.
This worked for me, in my case I had a button with a data-id attribute:
$("a").data("item-id");
This batch script will do exactly what the O.P. wants (tested on Windows XP SP3).
I also used that clever registry trick described by "jph" previously which IMHO is the simplest way of getting 100% consistent formatting of the date to "yyyy_MM_dd"
on any Windows system new or old. The change to one Registry value for doing this is instantaneous temporary and trivial; it only lasts a few milliseconds before it is immediately reverted back.
Double-click this batch file for an instant demo, Command Prompt window will pop up and display your timestamp . . . . .
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: generates a custom formatted timestamp string using date and time.
:: run this batch file for an instant demo.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@ECHO OFF
SETLOCAL & MODE CON:COLS=80 LINES=15 & COLOR 0A
:: --- CHANGE THE COMPUTER DATE FORMAT TEMPORARILY TO MY PREFERENCE "yyyy_MM_dd",
REG COPY "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f 2>nul >nul
REG ADD "HKCU\Control Panel\International" /v sShortDate /d "yyyy_MM_dd" /f 2>nul >nul
SET MYDATE=%date%
:: --- REVERT COMPUTER DATE BACK TO SYSTEM PREFERENCE
REG COPY "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f 2>nul >nul
REG DELETE "HKCU\Control Panel\International-Temp" /f 2>nul >nul
:: --- SPLIT THE TIME [HH:MM:SS.SS] TO THREE SEPARATE VARIABLES [HH] [MM] [SS.SS]
FOR /F "tokens=1-3 delims=:" %%A IN ('echo %time%') DO (
SET HOUR=%%A
SET MINUTES=%%B
SET SECONDS=%%C
)
:: --- CHOOSE ONE OF THESE TWO OPTIONS :
:: --- FOR 4 DIGIT SECONDS //REMOVES THE DOT FROM THE SECONDS VARIABLE [SS.SS]
:: SET SECONDS=%SECONDS:.=%
:: --- FOR 2 DIGIT SECONDS //GETS THE FIRST TWO DIGITS FROM THE SECONDS VARIABLE [SS.SS]
SET SECONDS=%SECONDS:~0,2%
:: --- FROM 12 AM TO 9 AM, THE HOUR VARIABLE WE EXTRACTED FROM %TIME% RETURNS A SINGLE DIGIT,
:: --- WE PREFIX A ZERO CHARACTER TO THOSE CASES, SO THAT OUR WANTED TIMESTAMP
:: --- ALWAYS GENERATES DOUBLE-DIGIT HOURS (24-HOUR CLOCK TIME SYSTEM).
IF %HOUR%==0 (SET HOUR=00)
IF %HOUR%==1 (SET HOUR=01)
IF %HOUR%==2 (SET HOUR=02)
IF %HOUR%==3 (SET HOUR=03)
IF %HOUR%==4 (SET HOUR=04)
IF %HOUR%==5 (SET HOUR=05)
IF %HOUR%==6 (SET HOUR=06)
IF %HOUR%==7 (SET HOUR=07)
IF %HOUR%==8 (SET HOUR=08)
IF %HOUR%==9 (SET HOUR=09)
:: --- GENERATE OUR WANTED TIMESTAMP
SET TIMESTAMP=%MYDATE%__%HOUR%_%MINUTES%_%SECONDS%
:: --- VIEW THE RESULT IN THE CONSOLE SCREEN
ECHO.
ECHO Generate a custom formatted timestamp string using date and time.
ECHO.
ECHO Your timestamp is: %TIMESTAMP%
ECHO.
ECHO.
ECHO Job is done. Press any key to exit . . .
PAUSE > NUL
EXIT
You can use ExtendedXmlSerializer. If you have a class:
public class TestClass
{
public Dictionary<int, string> Dictionary { get; set; }
}
and create instance of this class:
var obj = new TestClass
{
Dictionary = new Dictionary<int, string>
{
{1, "First"},
{2, "Second"},
{3, "Other"},
}
};
You can serialize this object using ExtendedXmlSerializer:
var serializer = new ConfigurationContainer()
.UseOptimizedNamespaces() //If you want to have all namespaces in root element
.Create();
var xml = serializer.Serialize(
new XmlWriterSettings { Indent = true }, //If you want to formated xml
obj);
Output xml will look like:
<?xml version="1.0" encoding="utf-8"?>
<TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples">
<Dictionary>
<sys:Item>
<Key>1</Key>
<Value>First</Value>
</sys:Item>
<sys:Item>
<Key>2</Key>
<Value>Second</Value>
</sys:Item>
<sys:Item>
<Key>3</Key>
<Value>Other</Value>
</sys:Item>
</Dictionary>
</TestClass>
You can install ExtendedXmlSerializer from nuget or run the following command:
Install-Package ExtendedXmlSerializer
You can easily do this by:
::variableName.isInitialized
or
this::variableName.isInitialized
But if you are inside a listener or inner class, do this:
this@OuterClassName::variableName.isInitialized
Note: The above statements work fine if you are writing them in the same file(same class or inner class) where the variable is declared but this will not work if you want to check the variable of other class (which could be a superclass or any other class which is instantiated), for ex:
class Test {
lateinit var str:String
}
And to check if str is initialized:
What we are doing here: checking isInitialized
for field str
of Test
class in Test2
class.
And we get an error backing field of var is not accessible at this point.
Check a question already raised about this.
Just had the same problem myself.
What happens is, that even if you drop the database, innodb will still not release disk space. I had to export, stop mysql, remove the files manually, start mysql, create database and users, and then import. Thank god I only had 200MB worth of rows, but it spared 250GB of innodb file.
Fail by design.
Late Entry.
Following is a succinct implementation using Java8 streams, a one liner:
String foobarspam = "foobarspam";
AtomicInteger splitCounter = new AtomicInteger(0);
Collection<String> splittedStrings = foobarspam
.chars()
.mapToObj(_char -> String.valueOf((char)_char))
.collect(Collectors.groupingBy(stringChar -> splitCounter.getAndIncrement() / 3
,Collectors.joining()))
.values();
Output:
[foo, bar, spa, m]
you can select the ids like so:
set @rank = 0;
select id, @rank:=@rank+1 from tbl order by id
the result is a list of ids, and their positions in the sequence.
you can also reset the ids like so:
set @rank = 0;
update tbl a join (select id, @rank:=@rank+1 as rank from tbl order by id) b
on a.id = b.id set a.id = b.rank;
you could also just print out the first unused id like so:
select min(id) as next_id from ((select a.id from (select 1 as id) a
left join tbl b on a.id = b.id where b.id is null) union
(select min(a.id) + 1 as id from tbl a left join tbl b on a.id+1 = b.id
where b.id is null)) c;
after each insert, you can reset the auto_increment:
alter table tbl auto_increment = 16
or explicitly set the id value when doing the insert:
insert into tbl values (16, 'something');
typically this isn't necessary, you have count(*)
and the ability to create a ranking number in your result sets. a typical ranking might be:
set @rank = 0;
select a.name, a.amount, b.rank from cust a,
(select amount, @rank:=@rank+1 as rank from cust order by amount desc) b
where a.amount = b.amount
customers ranked by amount spent.
In case you need to apply a dynamic delay with the lodash's debounce
function:
props: {
delay: String
},
data: () => ({
search: null
}),
created () {
this.valueChanged = debounce(function (event) {
// Here you have access to `this`
this.makeAPIrequest(event.target.value)
}.bind(this), this.delay)
},
methods: {
makeAPIrequest (newVal) {
// ...
}
}
And the template:
<template>
//...
<input type="text" v-model="search" @input="valueChanged" />
//...
</template>
NOTE: in the example above I made an example of search input which can call the API with a custom delay which is provided in props
At least for me, the signal(SIGSEGV ...)
approach mentioned in another answer did not work on Win32 with Visual C++ 2015. What did work for me was to use _set_se_translator()
found in eh.h
. It works like this:
Step 1) Make sure you enable Yes with SEH Exceptions (/EHa) in Project Properties / C++ / Code Generation / Enable C++ Exceptions, as mentioned in the answer by Volodymyr Frytskyy.
Step 2) Call _set_se_translator()
, passing in a function pointer (or lambda) for the new exception translator. It is called a translator because it basically just takes the low-level exception and re-throws it as something easier to catch, such as std::exception
:
#include <string>
#include <eh.h>
// Be sure to enable "Yes with SEH Exceptions (/EHa)" in C++ / Code Generation;
_set_se_translator([](unsigned int u, EXCEPTION_POINTERS *pExp) {
std::string error = "SE Exception: ";
switch (u) {
case 0xC0000005:
error += "Access Violation";
break;
default:
char result[11];
sprintf_s(result, 11, "0x%08X", u);
error += result;
};
throw std::exception(error.c_str());
});
Step 3) Catch the exception like you normally would:
try{
MakeAnException();
}
catch(std::exception ex){
HandleIt();
};
A better alternative to Control Panel is to use this freeware program from SourceForge called Pathenator.
However, it only works for a system that has .NET 4.0 or greater such as Windows 7, Windows 8, or Windows 10.
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
Probably the best cross browser solution for pdf display on web pages is to use the Mozilla PDF.js project code, it can be run as a node.js service and used as follows
<iframe style="width:100%;height:500px" src="http://www.mysite.co.uk/libs/pdfjs/web/viewer.html?file="http://www.mysite.co.uk/mypdf.pdf"></iframe>
A tutorial on how to use pdf.js can be found at this ejectamenta blog article
You can use Json
from the action directly,
Your action would be something like this:
virtual public JsonResult DisplaySomeWidget(int id)
{
SomeModelView returnData = someDataMapper.getbyid(id);
return Json(returnData);
}
Edit
Just saw that you assume this is the Model
of a View so the above isn't strictly correct, you would have to make an Ajax
call to the controller method to get this, the ascx
would not then have a model per se, I will leave my code in just in case it is useful to you and you can amend the call
Edit 2 just put id into the code
You have to put java in lower case and you have to add .class!
java HelloWorld2.class
They are all the same in the work they do. You can do the same things using any of them. But for readability, usability, convenience etc., they differ.
You can use justify-content: space-between
in .test
like so:
.test {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
For those who want to use Bootstrap 4 can use justify-content-between
:
div {_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:
render: function() {
return (
<span>
// This will go through all the elements in arrayFromJson and
// render each one as a <SomeComponent /> with data from the object
{this.state.arrayFromJson.map(function(object) {
return (
<SomeComponent key={object.id} data={object} />
);
})}
</span>
);
}
This CSS worked for me:
.form-group.required.control-label:before{
color: red;
content: "*";
position: absolute;
margin-left: -10px;
}
and this HTML:
<div class="form-group required control-label">
<label for="emailField">Email</label>
<input type="email" class="form-control" id="emailField" placeholder="Type Your Email Address Here" />
</div>
You can do this from the twig template:
{{ form_widget(form.birthdate, { 'attr': {'class': 'calendar'} }) }}
From http://symfony.com/doc/current/book/forms.html#rendering-each-field-by-hand
I faced the same issue. Just download and install the SQL Server suite from the following link :http://www.microsoft.com/en-US/download/details.aspx?id=42299
restart your SSMS and you should be able to "Register Local Servers" via right-click on "Local Servers Groups", select "tasks", click "register local servers"
Keep the previous path, don't overwrite it:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/your/custom/path/
You can add it to your ~/.bashrc:
echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/your/custom/path/' >> ~/.bashrc
This is what I used
public static Toast displayCustomToast(FragmentActivity mAct, String toastText, String toastLength, String succTypeColor) {
final Toast toast;
if (toastLength.equals("short")) {
toast = Toast.makeText(mAct, toastText, Toast.LENGTH_SHORT);
} else {
toast = Toast.makeText(mAct, toastText, Toast.LENGTH_LONG);
}
View tView = toast.getView();
tView.setBackgroundColor(Color.parseColor("#053a4d"));
TextView mText = (TextView) tView.findViewById(android.R.id.message);
mText.setTypeface(applyFont(mAct));
mText.setShadowLayer(0, 0, 0, 0);
tView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toast.cancel();
}
});
tView.invalidate();
if (succTypeColor.equals("red")) {
mText.setTextColor(Color.parseColor("#debe33"));
tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_red));
// this is to show error message
}
if (succTypeColor.equals("green")) {
mText.setTextColor(Color.parseColor("#053a4d"));
tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_green));
// this is to show success message
}
return toast;
}
While calling just write below.
AllMethodsInOne.displayCustomToast(act, "This is custom toast", "long", "red").show();
This method is easy and powerful.
Value is a date and "DD-MM-YYYY" is the mask of the date.
moment().diff(moment(value, "DD-MM-YYYY"), 'years');