How to easily consume a web service from PHP
In PHP 5 you can use SoapClient on the WSDL to call the web service functions. For example:
$client = new SoapClient("some.wsdl");
and $client is now an object which has class methods as defined in some.wsdl. So if there was a method called getTime in the WSDL then you would just call:
$result = $client->getTime();
And the result of that would (obviously) be in the $result variable. You can use the __getFunctions method to return a list of all the available methods.
Why is a "GRANT USAGE" created the first time I grant a user privileges?
As you said, in MySQL USAGE
is synonymous with "no privileges". From the MySQL Reference Manual:
The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.
USAGE
is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE
. It corresponds to a row in the `mysql`.`user`
table with no privileges set.
The IDENTIFIED BY
clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.
A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user`
table. If the user does not have any other privileges ON *.*
, they are granted USAGE ON *.*
and their password hash is displayed there. This is often a side effect of a CREATE USER
statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE
.
How to get StackPanel's children to fill maximum space downward?
It sounds like you want a StackPanel
where the final element uses up all the remaining space. But why not use a DockPanel
? Decorate the other elements in the DockPanel
with DockPanel.Dock="Top"
, and then your help control can fill the remaining space.
XAML:
<DockPanel Width="200" Height="200" Background="PowderBlue">
<TextBlock DockPanel.Dock="Top">Something</TextBlock>
<TextBlock DockPanel.Dock="Top">Something else</TextBlock>
<DockPanel
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="Auto"
Margin="10">
<GroupBox
DockPanel.Dock="Right"
Header="Help"
Width="100"
Background="Beige"
VerticalAlignment="Stretch"
VerticalContentAlignment="Stretch"
Height="Auto">
<TextBlock Text="This is the help that is available on the news screen."
TextWrapping="Wrap" />
</GroupBox>
<StackPanel DockPanel.Dock="Left" Margin="10"
Width="Auto" HorizontalAlignment="Stretch">
<TextBlock Text="Here is the news that should wrap around."
TextWrapping="Wrap"/>
</StackPanel>
</DockPanel>
</DockPanel>
If you are on a platform without DockPanel
available (e.g. WindowsStore), you can create the same effect with a grid. Here's the above example accomplished using grids instead:
<Grid Width="200" Height="200" Background="PowderBlue">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<TextBlock>Something</TextBlock>
<TextBlock>Something else</TextBlock>
</StackPanel>
<Grid Height="Auto" Grid.Row="1" Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<GroupBox
Width="100"
Height="Auto"
Grid.Column="1"
Background="Beige"
Header="Help">
<TextBlock Text="This is the help that is available on the news screen."
TextWrapping="Wrap"/>
</GroupBox>
<StackPanel Width="Auto" Margin="10" DockPanel.Dock="Left">
<TextBlock Text="Here is the news that should wrap around."
TextWrapping="Wrap"/>
</StackPanel>
</Grid>
</Grid>
Post multipart request with Android SDK
Here is a Simple approach if you are using the AOSP library Volley
.
Extend the class Request<T>
as follows-
public class MultipartRequest extends Request<String> {
private static final String FILE_PART_NAME = "file";
private final Response.Listener<String> mListener;
private final Map<String, File> mFilePart;
private final Map<String, String> mStringPart;
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, Map<String, File> file,
Map<String, String> mStringPart) {
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
this.mStringPart = mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
buildMultipartEntity();
}
public void addStringBody(String param, String value) {
mStringPart.put(param, value);
}
private void buildMultipartEntity() {
for (Map.Entry<String, File> entry : mFilePart.entrySet()) {
// entity.addPart(entry.getKey(), new FileBody(entry.getValue(), ContentType.create("image/jpeg"), entry.getKey()));
try {
entity.addBinaryBody(entry.getKey(), Utils.toByteArray(new FileInputStream(entry.getValue())), ContentType.create("image/jpeg"), entry.getKey() + ".JPG");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
}
@Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity = entity.build();
httpentity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
Log.d("Response", new String(response.data));
return Response.success(new String(response.data), getCacheEntry());
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}
You can create and add a request like-
Map<String, String> params = new HashMap<>();
params.put("name", name.getText().toString());
params.put("email", email.getText().toString());
params.put("user_id", appPreferences.getInt( Utils.PROPERTY_USER_ID, -1) + "");
params.put("password", password.getText().toString());
params.put("imageName", pictureName);
Map<String, File> files = new HashMap<>();
files.put("photo", new File(Utils.LOCAL_RESOURCE_PATH + pictureName));
MultipartRequest multipartRequest = new MultipartRequest(Utils.BASE_URL + "editprofile/" + appPreferences.getInt(Utils.PROPERTY_USER_ID, -1), new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("Error: ", error.toString());
FugaDialog.showErrorDialog(ProfileActivity.this);
}
}, new Response.Listener<String>() {
@Override
public void onResponse(String jsonResponse) {
JSONObject response = null;
try {
Log.d("jsonResponse: ", jsonResponse);
response = new JSONObject(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (response != null && response.has("statusmessage") && response.getBoolean("statusmessage")) {
updateLocalRecord();
}
} catch (JSONException e) {
e.printStackTrace();
}
FugaDialog.dismiss();
}
}, files, params);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(multipartRequest);
Why does Math.Round(2.5) return 2 instead of 3?
From MSDN:
By default, Math.Round uses
MidpointRounding.ToEven. Most people
are not familiar with "rounding to
even" as the alternative, "rounding
away from zero" is more commonly
taught in school. .NET defaults to
"Rounding to even" as it is
statistically superior because it
doesn't share the tendency of
"rounding away from zero" to round up
slightly more often than it rounds
down (assuming the numbers being
rounded tend to be positive.)
http://msdn.microsoft.com/en-us/library/system.math.round.aspx
Get image data url in JavaScript?
This Function takes the URL then returns the image BASE64
function getBase64FromImageUrl(url) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
img.src = url;
}
Call it like this :
getBase64FromImageUrl("images/slbltxt.png")
Global variables in Java
In general, Java doesn't have any global variables. Other than local variables, all variables comes under the scope of any class defined in the program.
We can have static variables to have the scope of global variables.
Pod install is staying on "Setting up CocoaPods Master repo"
The issue is that you haven't got command line tools installed, I believe.
Try run in terminal:
sudo gem update --system
after that download command line tools from Apple
just search for 'Command Line Tools' and download the right version for your OS.
Once you install it run in terminal:
sudo gem install cocoapods
pod setup
Best way to work with transactions in MS SQL Server Management Studio
The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.
For example,
Begin Transaction
-Do some T-SQL queries here.
Rollback transaction -- OR commit transaction
If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.
For example:
USE AdventureWorks;
GO
BEGIN TRANSACTION;
BEGIN TRY
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
See the following link for more details.
http://msdn.microsoft.com/en-us/library/ms175976.aspx
Hope this helps but please let me know if you need more details.
parse html string with jquery
MarvinS.-
Try:
$.ajax({
url: uri+'?js',
success: function(data) {
var imgAttr = $("img", data).attr('src');
var htmlCode = $(data).html();
$('#imgSrc').html(imgAttr);
$('#fullHtmlOutput').html(htmlCode);
}
});
This should load the whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.
How to send a POST request in Go?
You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.
req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
Entity Framework - Include Multiple Levels of Properties
I'm going to add my solution to my particular problem. I had two collections at the same level I needed to include. The final solution looked like this.
var recipe = _bartendoContext.Recipes
.Include(r => r.Ingredients)
.ThenInclude(r => r.Ingredient)
.Include(r => r.Ingredients)
.ThenInclude(r => r.MeasurementQuantity)
.FirstOrDefault(r => r.Id == recipeId);
if (recipe?.Ingredients == null) return 0m;
var abv = recipe.Ingredients.Sum(ingredient => ingredient.Ingredient.AlcoholByVolume * ingredient.MeasurementQuantity.Quantity);
return abv;
This is calculating the percent alcohol by volume of a given drink recipe. As you can see I just included the ingredients collection twice then included the ingredient and quantity onto that.
Java client certificates over HTTPS/SSL
For me, this is what worked using Apache HttpComponents ~ HttpClient 4.x:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
try {
keyStore.load(instream, "helloworld".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "helloworld".toCharArray())
//.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) //custom trust store
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
CloseableHttpClient httpclient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
The P12 file contains the client certificate and client private key, created with BouncyCastle:
public static byte[] convertPEMToPKCS12(final String keyFile, final String cerFile,
final String password)
throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException,
NoSuchProviderException
{
// Get the private key
FileReader reader = new FileReader(keyFile);
PEMParser pem = new PEMParser(reader);
PEMKeyPair pemKeyPair = ((PEMKeyPair)pem.readObject());
JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
PrivateKey key = keyPair.getPrivate();
pem.close();
reader.close();
// Get the certificate
reader = new FileReader(cerFile);
pem = new PEMParser(reader);
X509CertificateHolder certHolder = (X509CertificateHolder) pem.readObject();
java.security.cert.Certificate x509Certificate =
new JcaX509CertificateConverter().setProvider("BC")
.getCertificate(certHolder);
pem.close();
reader.close();
// Put them into a PKCS12 keystore and write it to a byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
ks.load(null);
ks.setKeyEntry("key-alias", (Key) key, password.toCharArray(),
new java.security.cert.Certificate[]{x509Certificate});
ks.store(bos, password.toCharArray());
bos.close();
return bos.toByteArray();
}
MySQL with Node.js
Imo, you should try MySQL Connector/Node.js which is the official Node.js driver for MySQL.
See ref-1 and ref-2 for detailed explanation.
I have tried mysqljs/mysql which is available here, but I don't find detailed documentation on classes, methods, properties of this library.
So I switched to the standard MySQL Connector/Node.js
with X DevAPI
, since it is an asynchronous Promise-based client library and provides good documentation.
Take a look at the following code snippet :
const mysqlx = require('@mysql/xdevapi');
const rows = [];
mysqlx.getSession('mysqlx://localhost:33060')
.then(session => {
const table = session.getSchema('testSchema').getTable('testTable');
// The criteria is defined through the expression.
return table.update().where('name = "bar"').set('age', 50)
.execute()
.then(() => {
return table.select().orderBy('name ASC')
.execute(row => rows.push(row));
});
})
.then(() => {
console.log(rows);
});
Factory Pattern. When to use factory methods?
It is important to clearly differentiate the idea behind using factory or factory method.
Both are meant to address mutually exclusive different kind of object creation problems.
Let's be specific about "factory method":
First thing is that, when you are developing library or APIs which in turn will be used for further application development, then factory method is one of the best selections for creation pattern. Reason behind; We know that when to create an object of required functionality(s) but type of object will remain undecided or it will be decided ob dynamic parameters being passed.
Now the point is, approximately same can be achieved by using factory pattern itself but one huge drawback will introduce into the system if factory pattern will be used for above highlighted problem, it is that your logic of crating different objects(sub classes objects) will be specific to some business condition so in future when you need to extend your library's functionality for other platforms(In more technically, you need to add more sub classes of basic interface or abstract class so factory will return those objects also in addition to existing one based on some dynamic parameters) then every time you need to change(extend) the logic of factory class which will be costly operation and not good from design perspective.
On the other side, if "factory method" pattern will be used to perform the same thing then you just need to create additional functionality(sub classes) and get it registered dynamically by injection which doesn't require changes in your base code.
interface Deliverable
{
/*********/
}
abstract class DefaultProducer
{
public void taskToBeDone()
{
Deliverable deliverable = factoryMethodPattern();
}
protected abstract Deliverable factoryMethodPattern();
}
class SpecificDeliverable implements Deliverable
{
/***SPECIFIC TASK CAN BE WRITTEN HERE***/
}
class SpecificProducer extends DefaultProducer
{
protected Deliverable factoryMethodPattern()
{
return new SpecificDeliverable();
}
}
public class MasterApplicationProgram
{
public static void main(String arg[])
{
DefaultProducer defaultProducer = new SpecificProducer();
defaultProducer.taskToBeDone();
}
}
jQuery selectors on custom data attributes using HTML5
jsFiddle Demo
jQuery provides several selectors (full list) in order to make the queries you are looking for work. To address your question "In other cases is it possible to use other selectors like "contains, less than, greater than, etc..."." you can also use contains, starts with, and ends with to look at these html5 data attributes. See the full list above in order to see all of your options.
The basic querying has been covered above, and using John Hartsock's answer is going to be the best bet to either get every data-company element, or to get every one except Microsoft (or any other version of :not
).
In order to expand this to the other points you are looking for, we can use several meta selectors. First, if you are going to do multiple queries, it is nice to cache the parent selection.
var group = $('ul[data-group="Companies"]');
Next, we can look for companies in this set who start with G
var google = $('[data-company^="G"]',group);//google
Or perhaps companies which contain the word soft
var microsoft = $('[data-company*="soft"]',group);//microsoft
It is also possible to get elements whose data attribute's ending matches
var facebook = $('[data-company$="book"]',group);//facebook
_x000D_
_x000D_
//stored selector_x000D_
var group = $('ul[data-group="Companies"]');_x000D_
_x000D_
//data-company starts with G_x000D_
var google = $('[data-company^="G"]',group).css('color','green');_x000D_
_x000D_
//data-company contains soft_x000D_
var microsoft = $('[data-company*="soft"]',group).css('color','blue');_x000D_
_x000D_
//data-company ends with book_x000D_
var facebook = $('[data-company$="book"]',group).css('color','pink');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul data-group="Companies">_x000D_
<li data-company="Microsoft">Microsoft</li>_x000D_
<li data-company="Google">Google</li>_x000D_
<li data-company ="Facebook">Facebook</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_
How do you find the first key in a dictionary?
Update: as of Python 3.7, insertion order is maintained, so you don't need an OrderedDict
here. You can use the below approaches with a normal dict
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
source
Python 3.6 and earlier*
If you are talking about a regular dict
, then the "first key" doesn't mean anything. The keys are not ordered in any way you can depend on. If you iterate over your dict
you will likely not get "banana"
as the first thing you see.
If you need to keep things in order, then you have to use an OrderedDict
and not just a plain dictionary.
import collections
prices = collections.OrderedDict([
("banana", 4),
("apple", 2),
("orange", 1.5),
("pear", 3),
])
If you then wanted to see all the keys in order you could do so by iterating through it
for k in prices:
print(k)
You could, alternatively put all of the keys into a list and then work with that
ks = list(prices)
print(ks[0]) # will print "banana"
A faster way to get the first element without creating a list would be to call next
on the iterator. This doesn't generalize nicely when trying to get the nth
element though
>>> next(iter(prices))
'banana'
* CPython had guaranteed insertion order as an implementation detail in 3.6.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Calculate row means on subset of columns
rowMeans
is nice, but if you are still trying to wrap your head around the apply
family of functions, this is a good opprotunity to begin understanding it.
DF['Mean'] <- apply(DF[,2:4], 1, mean)
Notice I'm doing a slightly different assignment than the first example. This approach makes it easier to incorporate it into for loops.
How to include files outside of Docker's build context?
I believe the simpler workaround would be to change the 'context' itself.
So, for example, instead of giving:
docker build -t hello-demo-app .
which sets the current directory as the context, let's say you wanted the parent directory as the context, just use:
docker build -t hello-demo-app ..
Text in a flex container doesn't wrap in IE11
Somehow all these solutions didn't work for me. There is clearly an IE bug in flex-direction:column
.
I only got it working after removing flex-direction
:
flex-wrap: wrap;
align-items: center;
align-content: center;
What is the best JavaScript code to create an img element
oImg.setAttribute('width', '1px');
px
is for CSS only. Use either:
oImg.width = '1';
to set a width through HTML, or:
oImg.style.width = '1px';
to set it through CSS.
Note that old versions of IE don't create a proper image with document.createElement()
, and old versions of KHTML don't create a proper DOM Node with new Image()
, so if you want to be fully backwards compatible use something like:
// IEWIN boolean previously sniffed through eg. conditional comments
function img_create(src, alt, title) {
var img = IEWIN ? new Image() : document.createElement('img');
img.src = src;
if ( alt != null ) img.alt = alt;
if ( title != null ) img.title = title;
return img;
}
Also be slightly wary of document.body.appendChild
if the script may execute as the page is in the middle of loading. You can end up with the image in an unexpected place, or a weird JavaScript error on IE. If you need to be able to add it at load-time (but after the <body>
element has started), you could try inserting it at the start of the body using body.insertBefore(body.firstChild)
.
To do this invisibly but still have the image actually load in all browsers, you could insert an absolutely-positioned-off-the-page <div>
as the body's first child and put any tracking/preload images you don't want to be visible in there.
Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app
For those using beta versions of Xcode, just change the application name in the command to Xcode-beta.app:
cd ~
mv .itmstransporter/ .old_itmstransporter/
"/Applications/Xcode-beta.app/Contents/Applications/Application Loader.app/Contents/itms/bin/iTMSTransporter"
Depending on your internet connection, the update may take some time. For me it was around 15 minutes.
alternatives to REPLACE on a text or ntext datatype
IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
For SQL Server 2005+:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
How to refresh table contents in div using jquery/ajax
You can load HTML page partial, in your case is everything inside div#mytable.
setTimeout(function(){
$( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds
more information read this http://api.jquery.com/load/
Update Code (if you don't want it auto-refresh)
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#mytable" ).load( "your-current-page.html #mytable" );
}
$("#refresh-btn").on("click", RefreshTable);
// OR CAN THIS WAY
//
// $("#refresh-btn").on("click", function() {
// $( "#mytable" ).load( "your-current-page.html #mytable" );
// });
});
</script>
How to make child divs always fit inside parent div?
There are two techniques commonly used for this:
- Absolute Positioning
- Table Styles
Given the HTML you provided here is the solution using Absolute positioning:
_x000D_
_x000D_
body #one {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
width: auto;_x000D_
height: auto;_x000D_
}_x000D_
body #two {_x000D_
width: auto; _x000D_
}_x000D_
body #three {_x000D_
position: absolute;_x000D_
top: 60px;_x000D_
bottom: 0;_x000D_
height: auto;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
html, body {width:100%;height:100%;margin:0;padding:0;}_x000D_
.border {border:1px solid black;}_x000D_
.margin { margin:5px;}_x000D_
#one {width:100%;height:100%;}_x000D_
#two {width:100%;height:50px;}_x000D_
#three {width:100px;height:100%;}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div id="one" class="border">_x000D_
<div id="two" class="border margin"></div>_x000D_
<div id="three" class="border margin"></div>_x000D_
</div>_x000D_
</body
_x000D_
_x000D_
_x000D_
You can always just use the table, tr, and td elements directly despite common criticisms as it will get the job done. If you prefer to use CSS there is no equivalent for colspan so you will likely end up with nested tables. Here is an example:
_x000D_
_x000D_
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
width: 100%;_x000D_
}_x000D_
#one {_x000D_
box-sizing: border-box;_x000D_
display: table;_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
width: 100%;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#two {_x000D_
box-sizing: border-box;_x000D_
display: table;_x000D_
height: 50px;_x000D_
padding: 5px;_x000D_
width: 100%;_x000D_
}_x000D_
#three {_x000D_
box-sizing: border-box;_x000D_
display: table;_x000D_
height: 100%;_x000D_
padding-bottom: 60px;_x000D_
padding-left: 5px;_x000D_
_x000D_
}_x000D_
#four {_x000D_
display: table-cell;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#five {_x000D_
display: table-cell;_x000D_
width: 100px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#six {_x000D_
display: table-cell; _x000D_
}
_x000D_
<html>_x000D_
<div id="one">_x000D_
<div id="two">_x000D_
<div id="four"></div>_x000D_
</div>_x000D_
<div id="three">_x000D_
<div id="five"></div>_x000D_
<div id="six"></div>_x000D_
</div>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_
How to set focus on an input field after rendering?
This is the proper way, how to autofocus. When you use callback instead of string as ref value, it is automatically called. You got your ref available than without the need of touching the DOM using getDOMNode
render: function() {
return <TextInput ref={(c) => this._input = c} />;
},
componentDidMount: function() {
this._input.focus();
},
Error including image in Latex
To include png and jpg, you need to specify the Bounding Box explicitly.
\includegraphics[bb=0 0 1280 960]{images/some_image.png}
Where 1280 and 960 are respectively width and height.
Why not inherit from List<T>?
Let me rewrite your question. so you might see the subject from a different perspective.
When I need to represent a football team, I understand that it is basically a name. Like: "The Eagles"
string team = new string();
Then later I realized teams also have players.
Why can't I just extend the string type so that it also holds a list of players?
Your point of entry into the problem is arbitrary. Try to think what does a team have (properties), not what it is.
After you do that, you could see if it shares properties with other classes. And think about inheritance.
How to Cast Objects in PHP
You can opt for this example below. Hope it will help.
/** @var ClassName $object */
$object->whateverMethod() // any method defined in the class can be accessed by $object
I know this is not a cast but it can be useful sometimes.
How to use Simple Ajax Beginform in Asp.net MVC 4?
Simple example: Form with textbox and Search button.
If you write "name" into the textbox
and submit form, it will brings you patients with "name" in table.
View:
@using (Ajax.BeginForm("GetPatients", "Patient", new AjaxOptions {//GetPatients is name of method in PatientController
InsertionMode = InsertionMode.Replace, //target element(#patientList) will be replaced
UpdateTargetId = "patientList",
LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading
}))
{
string patient_Name = "";
@Html.EditorFor(x=>patient_Name) //text box with name and id, that it will pass to controller
<input type="submit" value="Search" />
}
@* ... *@
<div id="loader" class=" aletr" style="display:none">
Loading...<img src="~/Images/ajax-loader.gif" />
</div>
@Html.Partial("_patientList") @* this is view with patient table. Same view you will return from controller *@
_patientList.cshtml:
@model IEnumerable<YourApp.Models.Patient>
<table id="patientList" >
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Number)
</th>
</tr>
@foreach (var patient in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => patient.Name)
</td>
<td>
@Html.DisplayFor(modelItem => patient.Number)
</td>
</tr>
}
</table>
Patient.cs
public class Patient
{
public string Name { get; set; }
public int Number{ get; set; }
}
PatientController.cs
public PartialViewResult GetPatients(string patient_Name="")
{
var patients = yourDBcontext.Patients.Where(x=>x.Name.Contains(patient_Name))
return PartialView("_patientList", patients);
}
And also as TSmith said in comments, don´t forget to install jQuery Unobtrusive Ajax library through NuGet.
Using partial views in ASP.net MVC 4
You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet
of Note
s, where you need to pass in a single Note
.
You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
Can I use DIV class and ID together in CSS?
#y.x should work. And it's convenient too. You can make a page with different kinds of output. You can give a certain element an id, but give it different classes depending on the look you want.
Python String and Integer concatenation
for i in range(11):
string = "string{0}".format(i)
What you did (range[1,10]
) is
- a TypeError since brackets denote an index (
a[3]
) or a slice (a[3:5]
) of a list,
- a SyntaxError since
[1,10]
is invalid, and
- a double off-by-one error since
range(1,10)
is [1, 2, 3, 4, 5, 6, 7, 8, 9]
, and you seem to want [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
And string = "string" + i
is a TypeError since you can't add an integer to a string (unlike JavaScript).
Look at the documentation for Python's new string formatting method, it is very powerful.
Solving "adb server version doesn't match this client" error
I had same problem since updated platfrom-tool to version 24
and not sure for root cause...(current adb version is 1.0.36)
Also try adb kill-server
and adb start-server
but problem still happened
but when I downgrade adb version to 1.0.32 everything work will
How to read values from the querystring with ASP.NET Core?
I have a better solution for this problem,
- request is a member of abstract class ControllerBase
- GetSearchParams() is an extension method created in bellow helper
class.
var searchparams = await Request.GetSearchParams();
I have created a static class with few extension methods
public static class HttpRequestExtension
{
public static async Task<SearchParams> GetSearchParams(this HttpRequest request)
{
var parameters = await request.TupledParameters();
try
{
for (var i = 0; i < parameters.Count; i++)
{
if (parameters[i].Item1 == "_count" && parameters[i].Item2 == "0")
{
parameters[i] = new Tuple<string, string>("_summary", "count");
}
}
var searchCommand = SearchParams.FromUriParamList(parameters);
return searchCommand;
}
catch (FormatException formatException)
{
throw new FhirException(formatException.Message, OperationOutcome.IssueType.Invalid, OperationOutcome.IssueSeverity.Fatal, HttpStatusCode.BadRequest);
}
}
public static async Task<List<Tuple<string, string>>> TupledParameters(this HttpRequest request)
{
var list = new List<Tuple<string, string>>();
var query = request.Query;
foreach (var pair in query)
{
list.Add(new Tuple<string, string>(pair.Key, pair.Value));
}
if (!request.HasFormContentType)
{
return list;
}
var getContent = await request.ReadFormAsync();
if (getContent == null)
{
return list;
}
foreach (var key in getContent.Keys)
{
if (!getContent.TryGetValue(key, out StringValues values))
{
continue;
}
foreach (var value in values)
{
list.Add(new Tuple<string, string>(key, value));
}
}
return list;
}
}
in this way you can easily access all your search parameters. I hope this will help many developers :)
c# Image resizing to different size while preserving aspect ratio
Here's a less specific extension method that works with Image rather than doing the loading and saving for you. It also allows you to specify interpolation method and correctly renders edges when you use NearestNeighbour interpolation.
The image will be rendered within the bounds of the area you specify so you always know your output width and height. e.g:
namespace YourApp
{
#region Namespaces
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
#endregion
/// <summary>Generic helper functions related to graphics.</summary>
public static class ImageExtensions
{
/// <summary>Resizes an image to a new width and height value.</summary>
/// <param name="image">The image to resize.</param>
/// <param name="newWidth">The width of the new image.</param>
/// <param name="newHeight">The height of the new image.</param>
/// <param name="mode">Interpolation mode.</param>
/// <param name="maintainAspectRatio">If true, the image is centered in the middle of the returned image, maintaining the aspect ratio of the original image.</param>
/// <returns>The new image. The old image is unaffected.</returns>
public static Image ResizeImage(this Image image, int newWidth, int newHeight, InterpolationMode mode = InterpolationMode.Default, bool maintainAspectRatio = false)
{
Bitmap output = new Bitmap(newWidth, newHeight, image.PixelFormat);
using (Graphics gfx = Graphics.FromImage(output))
{
gfx.Clear(Color.FromArgb(0, 0, 0, 0));
gfx.InterpolationMode = mode;
if (mode == InterpolationMode.NearestNeighbor)
{
gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
gfx.SmoothingMode = SmoothingMode.HighQuality;
}
double ratioW = (double)newWidth / (double)image.Width;
double ratioH = (double)newHeight / (double)image.Height;
double ratio = ratioW < ratioH ? ratioW : ratioH;
int insideWidth = (int)(image.Width * ratio);
int insideHeight = (int)(image.Height * ratio);
gfx.DrawImage(image, new Rectangle((newWidth / 2) - (insideWidth / 2), (newHeight / 2) - (insideHeight / 2), insideWidth, insideHeight));
}
return output;
}
}
}
Android : How to read file in bytes?
here it's a simple:
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Add permission in manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
How to pause for specific amount of time? (Excel/VBA)
Wait and Sleep functions lock Excel and you can't do anything else until the delay finishes. On the other hand Loop delays doesn't give you an exact time to wait.
So, I've made this workaround joining a little bit of both concepts. It loops until the time is the time you want.
Private Sub Waste10Sec()
target = (Now + TimeValue("0:00:10"))
Do
DoEvents 'keeps excel running other stuff
Loop Until Now >= target
End Sub
You just need to call Waste10Sec where you need the delay
JavaScript: SyntaxError: missing ) after argument list
just posting in case anyone else has the same error...
I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.
The solution was to make the function asynchronous
function functionName(args) {}
becomes
async function functionName(args) {}
Error: Cannot match any routes. URL Segment: - Angular 2
Solved myself. Done some small structural changes also. Route from Component1 to Component2 is done by a single <router-outlet>
. Component2 to Comonent3 and Component4 is done by multiple <router-outlet name= "xxxxx">
The resulting contents are :
Component1.html
<nav>
<a routerLink="/two" class="dash-item">Go to 2</a>
</nav>
<router-outlet></router-outlet>
Component2.html
<a [routerLink]="['/two', {outlets: {'nameThree': ['three']}}]">In Two...Go to 3 ... </a>
<a [routerLink]="['/two', {outlets: {'nameFour': ['four']}}]"> In Two...Go to 4 ...</a>
<router-outlet name="nameThree"></router-outlet>
<router-outlet name="nameFour"></router-outlet>
The '/two'
represents the parent component and ['three']
and ['four']
represents the link to the respective children of component2
. Component3.html and Component4.html are the same as in the question.
router.module.ts
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree'
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
}
]
},];
How to make html table vertically scrollable
Here's my solution (in Spring with Thymeleaf and jQuery):
html:
<!DOCTYPE html>
<html
xmlns:th="http://www.thymeleaf.org"
xmlns:tiles="http://www.thymeleaf.org">
<body>
<div id="objects" th:fragment="ObjectList">
<br/>
<div id='cap'>
<span>Objects</span>
</div>
<div id="hdr">
<div>
<div class="Cell">Name</div>
<div class="Cell">Type</div>
</div>
</div>
<div id="bdy">
<div th:each="object : ${objectlist}">
<div class="Cell" th:text="${object.name}">name</div>
<div class="Cell" th:text="${object.type}">type</div>
</div>
</div>
</div>
</body>
</html>
css:
@CHARSET "UTF-8";
#cap span {
display: table-caption;
border:2px solid;
font-size: 200%;
padding: 3px;
}
#hdr {
display:block;
padding:0px;
margin-left:0;
border:2px solid;
}
#bdy {
display:block;
padding:0px;
margin-left:0;
border:2px solid;
}
#objects #bdy {
height:300px;
overflow-y: auto;
}
#hdr div div{
margin-left:-3px;
margin-right:-3px;
text-align: right;
}
#hdr div:first-child {
text-align: left;
}
#bdy div div {
margin-left:-3px;
margin-right:-3px;
text-align: right;
}
#bdy div div:first-child {
text-align: left;
}
.Cell
{
display: table-cell;
border: solid;
border-width: thin;
padding-left: 5px;
padding-right: 5px;
}
javascript:
$(document).ready(function(){
var divs = ['#objects'];
divs.forEach(function(div)
{
if ($(div).length > 0)
{
var widths = [];
var totalWidth = 0;
$(div+' #hdr div div').each(function() {
widths.push($(this).width())
});
$(div+' #bdy div div').each(function() {
var col = $(this).index();
if ( $(this).width() > widths[col] )
{
widths[col] = $(this).width();
}
});
$(div+' #hdr div div').each(function() {
var newWidth = widths[$(this).index()]+5;
$(this).css("width", newWidth);
totalWidth += $(this).outerWidth();
});
$(div+' #bdy div div').each(function() {
$(this).css("width", widths[$(this).index()]+5);
});
$(div+' #hdr').css("width", totalWidth);
$(div+' #bdy').css("width", totalWidth+($(div+' #bdy').css('overflow-y')=='auto'?15:0));
}
})
});
Volley JsonObjectRequest Post request not working
All you need to do is to override getParams method in Request class. I had the same problem and I searched through the answers but I could not find a proper one. The problem is unlike get request, post parameters being redirected by the servers may be dropped. For instance, read this. So, don't risk your requests to be redirected by webserver. If you are targeting http://example/myapp , then mention the exact address of your service, that is http://example.com/myapp/index.php.
Volley is OK and works perfectly, the problem stems from somewhere else.
Print a div using javascript in angularJS single page application
Okay i might have some even different approach.
I am aware that it won't suit everybody but nontheless someone might find it useful.
For those who do not want to pupup a new window, and like me, are concerned about css styles this is what i came up with:
I wrapped view of my app into additional container, which is being hidden when printing and there is additional container for what needs to be printed which is shown when is printing.
Below working example:
_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
app.controller('myCtrl', function($scope) {_x000D_
_x000D_
$scope.people = [{_x000D_
"id" : "000",_x000D_
"name" : "alfred"_x000D_
},_x000D_
{_x000D_
"id" : "020",_x000D_
"name" : "robert"_x000D_
},_x000D_
{_x000D_
"id" : "200",_x000D_
"name" : "me"_x000D_
}];_x000D_
_x000D_
$scope.isPrinting = false;_x000D_
$scope.printElement = {};_x000D_
_x000D_
$scope.printDiv = function(e)_x000D_
{_x000D_
console.log(e);_x000D_
$scope.printElement = e;_x000D_
_x000D_
$scope.isPrinting = true;_x000D_
_x000D_
//does not seem to work without toimeouts_x000D_
setTimeout(function(){_x000D_
window.print();_x000D_
},50);_x000D_
_x000D_
setTimeout(function(){_x000D_
$scope.isPrinting = false;_x000D_
},50);_x000D_
_x000D_
_x000D_
};_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
_x000D_
<div ng-show="isPrinting">_x000D_
<p>Print me id: {{printElement.id}}</p>_x000D_
<p>Print me name: {{printElement.name}}</p>_x000D_
</div>_x000D_
_x000D_
<div ng-hide="isPrinting">_x000D_
<!-- your actual application code -->_x000D_
<div ng-repeat="person in people">_x000D_
<div ng-click="printDiv(person)">Print {{person.name}}</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
Note that i am aware that this is not an elegant solution, and it has several drawbacks, but it has some ups as well:
- does not need a popup window
- keeps the css intact
- does not store your whole page into a var (for whatever reason you don't want to do it)
Well, whoever you are reading this, have a nice day and keep coding :)
EDIT:
If it suits your situation you can actually use:
@media print { .noprint { display: none; } }
@media screen { .noscreen { visibility: hidden; position: absolute; } }
instead of angular booleans to select your printing and non printing content
EDIT:
Changed the screen css because it appears that display:none breaks printiing when printing first time after a page load/refresh.
visibility:hidden approach seem to be working so far.
How to use Python requests to fake a browser visit a.k.a and generate User Agent?
The root of the answer is that the person asking the question needs to have a JavaScript interpreter to get what they are after. What I have found is I am able to get all of the information I wanted on a website in json before it was interpreted by JavaScript. This has saved me a ton of time in what would be parsing html hoping each webpage is in the same format.
So when you get a response from a website using requests really look at the html/text because you might find the javascripts JSON in the footer ready to be parsed.
Could someone explain this for me - for (int i = 0; i < 8; i++)
it's the same as think the next:
"starting with i = 0, while i is less than 8, and adding one to i at the end of the parenthesis, do the instructions between brackets"
It's also the same as:
while( i < 8 )
{
// instrucctions like:
Console.WriteLine(i);
i++;
}
the For sentences is a basis of coding, and it's as useful as necessary its understanding.
It's the way to repeat n-times the same instrucction, or browse ( or do something with each element) an array
How to pretty print nested dictionaries?
Another option with yapf
:
from pprint import pformat
from yapf.yapflib.yapf_api import FormatCode
dict_example = {'1': '1', '2': '2', '3': [1, 2, 3, 4, 5], '4': {'1': '1', '2': '2', '3': [1, 2, 3, 4, 5]}}
dict_string = pformat(dict_example)
formatted_code, _ = FormatCode(dict_string)
print(formatted_code)
Output:
{
'1': '1',
'2': '2',
'3': [1, 2, 3, 4, 5],
'4': {
'1': '1',
'2': '2',
'3': [1, 2, 3, 4, 5]
}
}
How to check if a string is a number?
The problem is that the result of your code "isDigit" is reflecting only the last digit test. As far as I understand your qustion, you want to return isDigit = 0 whenever you have any character that is not a number in your string. Following your logic, you should code it like this:
char tmp[16];
scanf("%s", tmp);
int isDigit = 0;
int j=0;
isDigit = 1; /* Initialised it here */
while(j<strlen(tmp) && isDigit == 0){
if(tmp[j] > 57 || tmp[j] < 48) /* changed it to OR || */
isDigit = 0;
j++;
}
To get a more understandable code, I'd also change the test:
if(tmp[j] > 57 || tmp[j] < 48)
to the following:
if(tmp[j] > '9' || tmp[j] < '0')
log4net vs. Nlog
I second NLog too because it works with unmanaged code too.
I suppose it could be possibe to use log4net and log4cxx together, but NLog handles both managed and unmanaged code out of the box.
I also looked at Common.Logging, a facade that makes abstraction of the logging api, it supports log4net, NLog and Entreprise Library. I don't think i'll use it, but i like how they use lambdas to improve performance when logging is disabled (a feature shared with NLog and probably others).
What does InitializeComponent() do, and how does it work in WPF?
The call to InitializeComponent()
(which is usually called in the default constructor of at least Window
and UserControl
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the Window
/UserControl
that is loading, and passes it to the System.Windows.Application.LoadComponent()
static method. LoadComponent()
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail, LoadComponent
creates an instance of the XamlParser
, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode()
. This gets passed to the BamlRecordWriter
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the InitializeComponent
is a method on the System.Windows.Markup.IComponentConnector
interface, of which Window
/UserControl
implement in the partial generated class.
Hope this helps!
JPA Query.getResultList() - use in a generic way
Here is the sample on what worked for me. I think that put method is needed in entity class to map sql columns to java class attributes.
//simpleExample
Query query = em.createNativeQuery(
"SELECT u.name,s.something FROM user u, someTable s WHERE s.user_id = u.id",
NameSomething.class);
List list = (List<NameSomething.class>) query.getResultList();
Entity class:
@Entity
public class NameSomething {
@Id
private String name;
private String something;
// getters/setters
/**
* Generic put method to map JPA native Query to this object.
*
* @param column
* @param value
*/
public void put(Object column, Object value) {
if (((String) column).equals("name")) {
setName(String) value);
} else if (((String) column).equals("something")) {
setSomething((String) value);
}
}
}
Is it possible to 'prefill' a google form using data from a google spreadsheet?
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
buildUrls()
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
betterBuildUrls()
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
yymmdd Function
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
max value of integer
in standard C, you can use INT_MAX as the maximum 'int' value, this constant must be defined in "limits.h". Similar constants are defined for other types (http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.5.html), as stated, these constant are implementation-dependent but have a minimum value according to the minimum bits for each type, as specified in the standard.
Why is "throws Exception" necessary when calling a function?
package javaexception;
public class JavaException {
void show() throws Exception
{
throw new Exception("my.own.Exception");
}
void show2() throws Exception // Why throws is necessary here ?
{
show();
}
void show3() throws Exception // Why throws is necessary here ?
{
show2();
}
public static void main(String[] args) {
JavaException a = new JavaException();
try{
a.show3();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Only small changes in your program. What It seems to be misunderstood by many regarding the main issue, is whenever you throw exception you need to handle it, not necessary in the same place ( ex. show1,2,3 method in your program) but you must at first caller method inside the 'main'. in one word, there is 'throw', there must be 'catch/try', even if not same method where exception happens.
Regular expression for matching latitude/longitude coordinates?
^-?[0-9]{1,3}(?:\.[0-9]{1,10})?$
Regex breakdown:
^-?[0-9]{1,3}(?:\.[0-9]{1,10})?$
-?
# accept negative values
^
# Start of string
[0-9]{1,3}
# Match 1-3 digits (i. e. 0-999)
(?:
# Try to match...
\.
# a decimal point
[0-9]{1,10}
# followed by one to 10 digits (i. e. 0-9999999999)
)?
# ...optionally
$
# End of string
What techniques can be used to define a class in JavaScript, and what are their trade-offs?
Here's the way to do it without using any external libraries:
// Define a class like this
function Person(name, gender){
// Add object properties like this
this.name = name;
this.gender = gender;
}
// Add methods like this. All Person objects will be able to invoke this
Person.prototype.speak = function(){
alert("Howdy, my name is" + this.name);
};
// Instantiate new objects with 'new'
var person = new Person("Bob", "M");
// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"
Now the real answer is a whole lot more complex than that. For instance, there is no such thing as classes in JavaScript. JavaScript uses a prototype
-based inheritance scheme.
In addition, there are numerous popular JavaScript libraries that have their own style of approximating class-like functionality in JavaScript. You'll want to check out at least Prototype and jQuery.
Deciding which of these is the "best" is a great way to start a holy war on Stack Overflow. If you're embarking on a larger JavaScript-heavy project, it's definitely worth learning a popular library and doing it their way. I'm a Prototype guy, but Stack Overflow seems to lean towards jQuery.
As far as there being only "one way to do it", without any dependencies on external libraries, the way I wrote is pretty much it.
Is ini_set('max_execution_time', 0) a bad idea?
At the risk of irritating you;
You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.
Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.
What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.
It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.
In short, it's just unnecessarily conflating the matter when there is no need to.
Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit()
than ini_set()
.
Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)
How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?
The Syntax as specified by Microsoft for the dropping a column part of an ALTER statement is this
DROP
{
[ CONSTRAINT ]
{
constraint_name
[ WITH
( <drop_clustered_constraint_option> [ ,...n ] )
]
} [ ,...n ]
| COLUMN
{
column_name
} [ ,...n ]
} [ ,...n ]
Notice that the [,...n] appears after both the column name and at the end of the whole drop clause. What this means is that there are two ways to delete multiple columns. You can either do this:
ALTER TABLE TableName
DROP COLUMN Column1, Column2, Column3
or this
ALTER TABLE TableName
DROP
COLUMN Column1,
COLUMN Column2,
COLUMN Column3
This second syntax is useful if you want to combine the drop of a column with dropping a constraint:
ALTER TBALE TableName
DROP
CONSTRAINT DF_TableName_Column1,
COLUMN Column1;
When dropping columns SQL Sever does not reclaim the space taken up by the columns dropped. For data types that are stored inline in the rows (int for example) it may even take up space on the new rows added after the alter statement. To get around this you need to create a clustered index on the table or rebuild the clustered index if it already has one. Rebuilding the index can be done with a REBUILD command after modifying the table. But be warned this can be slow on very big tables. For example:
ALTER TABLE Test
REBUILD;
What does `set -x` do?
set -x
Prints a trace of simple commands, for commands, case commands, select
commands, and arithmetic for commands and their arguments or
associated word lists after they are expanded and before they are
executed. The value of the PS4 variable is expanded and the resultant
value is printed before the command and its expanded arguments.
[source]
Example
set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
30
set +x
echo `expr 10 + 20 `
30
Above example illustrates the usage of set -x
. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.
- First step
expr
has been evaluated.
- Second step
echo
has been evaluated.
To know more about set ? visit this link
when it comes to your shell script,
[ "$DEBUG" == 'true' ] && set -x
Your script might have been printing some additional lines of information when the execution mode selected as DEBUG
. Traditionally people used to enable debug mode when a script called with optional argument such as -d
Simple PowerShell LastWriteTime compare
I can't fault any of the answers here for the OP accepted one of them as resolving their problem. However, I found them flawed in one respect. When you output the result of the assignment to the variable, it contains numerous blank lines, not just the sought after answer. Example:
PS C:\brh> [datetime](Get-ItemProperty -Path .\deploy.ps1 -Name LastWriteTime).LastWriteTime
Friday, December 12, 2014 2:33:09 PM
PS C:\brh>
I'm a fan of two things in code, succinctness and correctness. brianary has the right of it for succinctness with a tip of the hat to Roger Lipscombe but both miss correctness due to the extra lines in the result. Here's what I think the OP was looking for since it's what got me over the finish line.
PS C:\brh> (ls .\deploy.ps1).LastWriteTime.DateTime
Friday, December 12, 2014 2:33:09 PM
PS C:\brh>
Note the lack of extra lines, only the one that PowerShell uses to separate prompts. Now this can be assigned to a variable for comparison or, as in my case, stored in a file for reading and comparison in a later session.
How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps
As mentioned by Dan Abramov
Do it right inside render
We actually use that approach with memoise one for any kind of proxying props to state calculations.
Our code looks this way
// ./decorators/memoized.js
import memoizeOne from 'memoize-one';
export function memoized(target, key, descriptor) {
descriptor.value = memoizeOne(descriptor.value);
return descriptor;
}
// ./components/exampleComponent.js
import React from 'react';
import { memoized } from 'src/decorators';
class ExampleComponent extends React.Component {
buildValuesFromProps() {
const {
watchedProp1,
watchedProp2,
watchedProp3,
watchedProp4,
watchedProp5,
} = this.props
return {
value1: buildValue1(watchedProp1, watchedProp2),
value2: buildValue2(watchedProp1, watchedProp3, watchedProp5),
value3: buildValue3(watchedProp3, watchedProp4, watchedProp5),
}
}
@memoized
buildValue1(watchedProp1, watchedProp2) {
return ...;
}
@memoized
buildValue2(watchedProp1, watchedProp3, watchedProp5) {
return ...;
}
@memoized
buildValue3(watchedProp3, watchedProp4, watchedProp5) {
return ...;
}
render() {
const {
value1,
value2,
value3
} = this.buildValuesFromProps();
return (
<div>
<Component1 value={value1}>
<Component2 value={value2}>
<Component3 value={value3}>
</div>
);
}
}
The benefits of it are that you don't need to code tons of comparison boilerplate inside getDerivedStateFromProps
or componentWillReceiveProps
and you can skip copy-paste initialization inside a constructor.
NOTE:
This approach is used only for proxying the props to state, in case you have some inner state logic it still needs to be handled in component lifecycles.
@UniqueConstraint and @Column(unique = true) in hibernate annotation
In addition to Boaz's answer ....
@UniqueConstraint
allows you to name the constraint, while @Column(unique = true)
generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq
).
Sometimes it can be helpful to know what table a constraint is associated with. E.g.:
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {
@UniqueConstraint(
columnNames = {"mask", "group"},
name="uk_product_serial_group_mask"
)
}
)
c# replace \" characters
Try it like this:
Replace("\\\"","");
This will replace occurrences of \"
with empty string.
Ex:
string t = "\\\"the dog is my friend\\\"";
t = t.Replace("\\\"","");
This will result in:
the dog is my friend
Java 8 stream map to list of keys sorted by values
You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted
to tell it how you want to sort.
And you want to get the keys; use map
to transform entries to keys.
List<Type> types = countByType.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
Writing unit tests in Python: How do I start?
The docs for unittest would be a good place to start.
Also, it is a bit late now, but in the future please consider writing unit tests before or during the project itself. That way you can use them to test as you go along, and (in theory) you can use them as regression tests, to verify that your code changes have not broken any existing code. This would give you the full benefit of writing test cases :)
Remove ALL styling/formatting from hyperlinks
if you state a.redLink{color:red;}
then to keep this on hover and such add a.redLink:hover{color:red;}
This will make sure no other hover states will change the color of your links
Convert an enum to List<string>
Use Enum
's static method, GetNames
. It returns a string[]
, like so:
Enum.GetNames(typeof(DataSourceTypes))
If you want to create a method that does only this for only one type of enum
, and also converts that array to a List
, you can write something like this:
public List<string> GetDataSourceTypes()
{
return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}
You will need Using System.Linq;
at the top of your class to use .ToList()
POST request with JSON body
I made API sending data via form on website to prosperworks based on @Rocket Hazmat, @dbau and @maraca code.
I hope, it will help somebody:
<?php
if(isset($_POST['submit'])) {
//form's fields name:
$name = $_POST['nameField'];
$email = $_POST['emailField'];
//API url:
$url = 'https://api.prosperworks.com/developer_api/v1/leads';
//JSON data(not exact, but will be compiled to JSON) file:
//add as many data as you need (according to prosperworks doc):
$data = array(
'name' => $name,
'email' => array('email' => $email)
);
//sending request (according to prosperworks documentation):
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n".
"X-PW-AccessToken: YOUR_TOKEN_HERE\r\n".
"X-PW-Application:developer_api\r\n".
"X-PW-UserEmail: YOUR_EMAIL_HERE\r\n",
'method' => 'POST',
'content' => json_encode($data)
)
);
//engine:
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
//compiling to JSON (as wrote above):
$resultData = json_decode($result, TRUE);
//display what was sent:
echo '<h2>Sent: </h2>';
echo $resultData['published'];
//dump var:
var_dump($result);
}
?>
<html>
<head>
</head>
<body>
<form action="" method="POST">
<h1><?php echo $msg; ?></h1>
Name: <input type="text" name="nameField"/>
<br>
Email: <input type="text" name="emailField"/>
<input type="submit" name="submit" value="Send"/>
</form>
</body>
</html>
How do I split a string on a delimiter in Bash?
In Bash, a bullet proof way, that will work even if your variable contains newlines:
IFS=';' read -d '' -ra array < <(printf '%s;\0' "$in")
Look:
$ in=$'one;two three;*;there is\na newline\nin this field'
$ IFS=';' read -d '' -ra array < <(printf '%s;\0' "$in")
$ declare -p array
declare -a array='([0]="one" [1]="two three" [2]="*" [3]="there is
a newline
in this field")'
The trick for this to work is to use the -d
option of read
(delimiter) with an empty delimiter, so that read
is forced to read everything it's fed. And we feed read
with exactly the content of the variable in
, with no trailing newline thanks to printf
. Note that's we're also putting the delimiter in printf
to ensure that the string passed to read
has a trailing delimiter. Without it, read
would trim potential trailing empty fields:
$ in='one;two;three;' # there's an empty field
$ IFS=';' read -d '' -ra array < <(printf '%s;\0' "$in")
$ declare -p array
declare -a array='([0]="one" [1]="two" [2]="three" [3]="")'
the trailing empty field is preserved.
Update for Bash=4.4
Since Bash 4.4, the builtin mapfile
(aka readarray
) supports the -d
option to specify a delimiter. Hence another canonical way is:
mapfile -d ';' -t array < <(printf '%s;' "$in")
How can I access the MySQL command line with XAMPP for Windows?
In terminal:
cd C:\xampp\mysql\bin
mysql -h 127.0.0.1 --port=3306 -u root --password
Hit ENTER if the password is an empty string. Now you are in.
You can list all available databases, and select one using the fallowing:
SHOW DATABASES;
USE database_name_here;
SHOW TABLES
DESC table_name_here
SELECT * FROM table_name_here
Remember about the ";" at the end of each SQL statement.
Windows cmd terminal is not very nice and does not support Ctrl + C, Ctrl + V (copy, paste) shortcuts. If you plan to work a lot in terminal, consider installing an alternative terminal cmd line, I use cmder terminal - Download Page
jQuery Multiple ID selectors
You can use multiple id
's the way you wrote:
$('#upload_link, #upload_link2, #upload_link3')
However, that doesn't mean that those ids exist within the DOM when you've executed your code. It also doesn't mean that upload
is a legitimate function. It also doesn't mean that upload
has been built in a way that allows for multiple elements in a selection.
upload
is a custom jQuery plugin, so you'll have to show what's going on with upload
for us to be able to help you.
What is a predicate in c#?
The following code can help you to understand some real world use of predicates (Combined with named iterators).
namespace Predicate
{
class Person
{
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
foreach (Person person in OlderThan(18))
{
Console.WriteLine(person.Age);
}
}
static IEnumerable<Person> OlderThan(int age)
{
Predicate<Person> isOld = x => x.Age > age;
Person[] persons = { new Person { Age = 10 }, new Person { Age = 20 }, new Person { Age = 19 } };
foreach (Person person in persons)
if (isOld(person)) yield return person;
}
}
}
Hide all elements with class using plain Javascript
function getElementsByClassName(classname, node) {
if(!node) node = document.getElementsByTagName("body")[0];
var a = [];
var re = new RegExp('\\b' + classname + '\\b');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
var elements = new Array();
elements = getElementsByClassName('yourClassName');
for(i in elements ){
elements[i].style.display = "none";
}
Convert double to Int, rounded down
I think I had a better output, especially for a double datatype sorting.
Though this question has been marked answered, perhaps this will help someone else;
Arrays.sort(newTag, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
return time1.compareTo(time2);
}
});
How to align iframe always in the center
If all you want to do is display an iframe on a page, the simplest solution I was able to come up with doesn't require divs or flex stuff is:
html {
width: 100%;
height: 100%;
display: table;
}
body {
text-align: center;
vertical-align: middle;
display: table-cell;
}
And then the HTML is just:
<html>
<body>
<iframe ...></iframe>
</body>
</html>
If this is all you need you don't need wrapper divs to do it. This works for text content and stuff, too.
Fiddle.
Also this looks even simpler.
PHP function ssh2_connect is not working
For WHM Panel
Menu > Server Configuration > Terminal:
yum install libssh2-devel -y
Menu > Software > Module Installers
- PHP PECL Manage Click
- ssh2 Install Now Click
Menu > Restart Services > HTTP Server (Apache)
Are you sure you wish to restart this service?
Yes
ssh2_connect() Work!
Five equal columns in twitter bootstrap
Five columns are clearly not the part of bootstrap by design.
But with Bootstrap v4 (alpha), there are 2 things to help with a complicated grid layout
- Flex (http://v4-alpha.getbootstrap.com/getting-started/flexbox/), the new element type (official - https://www.w3.org/TR/css-flexbox-1/)
- Responsive utilities (http://v4-alpha.getbootstrap.com/layout/responsive-utilities/)
In simple term, I'm using
<style>
.flexc { display: flex; align-items: center; padding: 0; justify-content: center; }
.flexc a { display: block; flex: auto; text-align: center; flex-basis: 0; }
</style>
<div class="container flexc hidden-sm-down">
<!-- content to show in MD and larger viewport -->
<a href="#">Link/Col 1</a>
<a href="#">Link/Col 2</a>
<a href="#">Link/Col 3</a>
<a href="#">Link/Col 4</a>
<a href="#">Link/Col 5</a>
</div>
<div class="container hidden-md-up">
<!-- content to show in SM and smaller viewport, I don't think 5 cols in smaller viewport are gonna be alright :) -->
</div>
Be it 5,7,9,11,13 or something odds, it'll be okay.
I'm quite sure that 12-grids standard is able to serve more than 90% of use case - so let's design that way - develop more easier too!
The nice flex tutorial is here "https://css-tricks.com/snippets/css/a-guide-to-flexbox/"
Calculating a directory's size using Python?
This walks all sub-directories; summing file sizes:
import os
def get_size(start_path = '.'):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
return total_size
print(get_size(), 'bytes')
And a oneliner for fun using os.listdir (Does not include sub-directories):
import os
sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))
Reference:
Updated
To use os.path.getsize, this is clearer than using the os.stat().st_size method.
Thanks to ghostdog74 for pointing this out!
os.stat - st_size Gives the size in bytes. Can also be used to get file size and other file related information.
import os
nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())
Update 2018
If you use Python 3.4 or previous then you may consider using the more efficient walk
method provided by the third-party scandir
package. In Python 3.5 and later, this package has been incorporated into the standard library and os.walk
has received the corresponding increase in performance.
Update 2019
Recently I've been using pathlib
more and more, here's a pathlib
solution:
from pathlib import Path
root_directory = Path('.')
sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())
Issue with virtualenv - cannot activate
For activation you can go to the venv
your virtualenv directory
by cd venv
.
Then on Windows, type dir
(on unix, type ls
).
You will get 5 folders include
, Lib
, Scripts
, tcl
and 60
Now type .\Scripts\activate
to activate your virtualenv venv
.
Your prompt will change to indicate that you are now operating within the virtual environment. It will look something like this (venv)user@host:~/venv$
.
And your venv
is activated now.
Android- create JSON Array and JSON Object
Have been struggling with this till I found out the answer:
Use GSON library:
Gson gson = Gson();
String str_json = gson.tojson(jsonArray);`
Pass the json array. This will be auto stringfied. This option worked perfectly for me.
Usage of MySQL's "IF EXISTS"
I found the example RichardTheKiwi quite informative.
Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...
-- what I might write in MSSQL
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
-- rewritten for MySQL
IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
INSERT INTO Table (FieldValue) VALUES('');
SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;
How can I access an internal class from an external assembly?
Reflection.
using System.Reflection;
Vendor vendor = new Vendor();
object tag = vendor.Tag;
Type tagt = tag.GetType();
FieldInfo field = tagt.GetField("test");
string value = field.GetValue(tag);
Use the power wisely. Don't forget error checking. :)
Define constant variables in C++ header
C++17 inline
variables
This awesome C++17 feature allow us to:
- conveniently use just a single memory address for each constant
- store it as a
constexpr
: How to declare constexpr extern?
- do it in a single line from one header
main.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
// Both files see the same memory address.
assert(¬main_i == notmain_func());
assert(notmain_i == 42);
}
notmain.hpp
#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP
inline constexpr int notmain_i = 42;
const int* notmain_func();
#endif
notmain.cpp
#include "notmain.hpp"
const int* notmain_func() {
return ¬main_i;
}
Compile and run:
g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
./main
GitHub upstream.
See also: How do inline variables work?
C++ standard on inline variables
The C++ standard guarantees that the addresses will be the same. C++17 N4659 standard draft
10.1.6 "The inline specifier":
6 An inline function or variable with external linkage shall have the same address in all translation units.
cppreference https://en.cppreference.com/w/cpp/language/inline explains that if static
is not given, then it has external linkage.
Inline variable implementation
We can observe how it is implemented with:
nm main.o notmain.o
which contains:
main.o:
U _GLOBAL_OFFSET_TABLE_
U _Z12notmain_funcv
0000000000000028 r _ZZ4mainE19__PRETTY_FUNCTION__
U __assert_fail
0000000000000000 T main
0000000000000000 u notmain_i
notmain.o:
0000000000000000 T _Z12notmain_funcv
0000000000000000 u notmain_i
and man nm
says about u
:
"u" The symbol is a unique global symbol. This is a GNU extension to the standard set of ELF symbol bindings. For such a symbol the dynamic linker will make sure that in the entire process
there is just one symbol with this name and type in use.
so we see that there is a dedicated ELF extension for this.
C++17 standard draft on "global" const
implies static
This is the quote for what was mentioned at: https://stackoverflow.com/a/12043198/895245
C++17 n4659 standard draft 6.5 "Program and linkage":
3
A name having namespace scope (6.3.6) has internal linkage if it is the name of
- (3.1) — a variable, function or function template that is explicitly declared static; or,
- (3.2) — a non-inline variable of non-volatile const-qualified type that is neither explicitly declared extern nor
previously declared to have external linkage; or
- (3.3) — a data member of an anonymous union.
"namespace" scope is what we colloquially often refer to as "global".
Annex C (informative) Compatibility, C.1.2
Clause 6: "basic concepts" gives the rationale why this was changed from C:
6.5 [also 10.1.7]
Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has
internal linkage, while in C it would have external linkage.
Rationale: Because const objects may be used as values during translation in C++, this feature urges
programmers to provide an explicit initializer for each const object. This feature allows the user to put
const objects in source files that are included in more than one translation unit.
Effect on original feature: Change to semantics of well-defined feature.
Difficulty of converting: Semantic transformation.
How widely used: Seldom.
See also: Why does const imply internal linkage in C++, when it doesn't in C?
Tested in GCC 7.4.0, Ubuntu 18.04.
Mouseover or hover vue.js
This worked for me for nuxt
<template>
<span
v-if="item"
class="primary-navigation-list-dropdown"
@mouseover="isTouchscreenDevice ? null : openDropdownMenu()"
@mouseleave="isTouchscreenDevice ? null : closeDropdownMenu()"
>
<nuxt-link
to="#"
@click.prevent.native="openDropdownMenu"
v-click-outside="closeDropdownMenu"
:title="item.title"
:class="[
item.cssClasses,
{ show: isDropdownMenuVisible }
]"
:id="`navbarDropdownMenuLink-${item.id}`"
:aria-expanded="[isDropdownMenuVisible ? true : false]"
class="
primary-navigation-list-dropdown__toggle
nav-link
dropdown-toggle"
aria-current="page"
role="button"
data-toggle="dropdown"
>
{{ item.label }}
</nuxt-link>
<ul
:class="{ show: isDropdownMenuVisible }"
:aria-labelledby="`navbarDropdownMenuLink-${item.id}`"
class="
primary-navigation-list-dropdown__menu
dropdown-menu-list
dropdown-menu"
>
<li
v-for="item in item.children" :key="item.id"
class="dropdown-menu-list__item"
>
<NavLink
:attributes="item"
class="dropdown-menu-list__link dropdown-item"
/>
</li>
</ul>
</span>
</template>
<script>
import NavLink from '@/components/Navigation/NavLink';
export default {
name: "DropdownMenu",
props: {
item: {
type: Object,
required: true,
},
},
data() {
return {
isDropdownMenuVisible: false,
isTouchscreenDevice: false
};
},
mounted() {
this.detectTouchscreenDevice();
},
methods: {
openDropdownMenu() {
if (this.isTouchscreenDevice) {
this.isDropdownMenuVisible = !this.isDropdownMenuVisible;
} else {
this.isDropdownMenuVisible = true;
}
},
closeDropdownMenu() {
if (this.isTouchscreenDevice) {
this.isDropdownMenuVisible = false;
} else {
this.isDropdownMenuVisible = false;
}
},
detectTouchscreenDevice() {
if (window.PointerEvent && ('maxTouchPoints' in navigator)) {
if (navigator.maxTouchPoints > 0) {
this.isTouchscreenDevice = true;
}
} else {
if (window.matchMedia && window.matchMedia("(any-pointer:coarse)").matches) {
this.isTouchscreenDevice = true;
} else if (window.TouchEvent || ('ontouchstart' in window)) {
this.isTouchscreenDevice = true;
}
}
return this.isTouchscreenDevice;
}
},
components: {
NavLink
}
};
</script>
<style scoped lang="scss">
.primary-navigation-list-dropdown {
&__toggle {
color: $white;
&:hover {
color: $blue;
}
}
&__menu {
margin-top: 0;
}
&__dropdown {
}
}
.dropdown-menu-list {
&__item {
}
&__link {
&.active,
&.nuxt-link-exact-active {
border-bottom: 1px solid $blue;
}
}
}
</style>
Razor/CSHTML - Any Benefit over what we have?
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.
get enum name from enum value
You could create a lookup method. Not the most efficient (depending on the enum's size) but it works.
public static String getNameByCode(int code){
for(RelationActiveEnum e : RelationActiveEnum.values()){
if(code == e.value) return e.name();
}
return null;
}
And call it like this:
RelationActiveEnum.getNameByCode(3);
How to make sure that string is valid JSON using JSON.NET
Just to add something to @Habib's answer, you can also check if given JSON is from a valid type:
public static bool IsValidJson<T>(this string strInput)
{
if(string.IsNullOrWhiteSpace(strInput)) return false;
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try
{
var obj = JsonConvert.DeserializeObject<T>(strInput);
return true;
}
catch // not valid
{
return false;
}
}
else
{
return false;
}
}
How to get last items of a list in Python?
The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.
>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]
embedding image in html email
For those who couldnt get one of these solutions working:
Send inline image in email
Following the steps laid out in the solution offered by @T30 i was able to get my inline image to display without being blocked by outlook (previous methods it was blocked). If you are using exchange like we are then also when doing:
service = new ExchangeService(ExchangeVersion);
service.AutodiscoverUrl("[email protected]");
SmtpClient smtp = new SmtpClient(service.Url.Host);
you will need to pass it your exchange service url host. Other than that following this solution should allow you to easily send embedded imgages.
Combine two (or more) PDF's
There's some good answers here already, but I thought I might mention that pdftk might be useful for this task. Instead of producing one PDF directly, you could produce each PDF you need and then combine them together as a post-process with pdftk. This could even be done from within your program using a system() or ShellExecute() call.
Moment JS start and end of given month
_x000D_
_x000D_
const year = 2014;_x000D_
const month = 09;_x000D_
_x000D_
// months start at index 0 in momentjs, so we subtract 1_x000D_
const startDate = moment([year, month - 1, 01]).format("YYYY-MM-DD");_x000D_
_x000D_
// get the number of days for this month_x000D_
const daysInMonth = moment(startDate).daysInMonth();_x000D_
_x000D_
// we are adding the days in this month to the start date (minus the first day)_x000D_
const endDate = moment(startDate).add(daysInMonth - 1, 'days').format("YYYY-MM-DD");_x000D_
_x000D_
console.log(`start date: ${startDate}`);_x000D_
console.log(`end date: ${endDate}`);
_x000D_
<script_x000D_
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js">_x000D_
</script>
_x000D_
_x000D_
_x000D_
How can I convert spaces to tabs in Vim or Linux?
To use Vim to retab a set of files (e.g. all the *.ts files in a directory hierarchy) from say 2 spaces to 4 spaces you can try this from the command line:
find . -name '*.ts' -print0 | xargs -0 -n1 vim -e '+set ts=2 noet | retab! | set ts=4 et | retab | wq'
What this is doing is using find
to pass all the matching files to xargs
(the -print0 option on find works with the -0 option to xargs in order to handle files w/ spaces in the name).
xargs runs vim in ex mode (-e
) on each file executing the given ex command which is actually several commands, to change the existing leading spaces to tabs, resetting the tab stop and changing the tabs back to spaces and finally saving and exiting.
Running in ex mode prevents this: Vim: Warning: Input is not from a terminal
for each file.
Remove querystring from URL
An approach using the standard URL
:
/**
* @param {string} path - A path starting with "/"
* @return {string}
*/
function getPathname(path) {
return new URL(`http://_${path}`).pathname
}
getPathname('/foo/bar?cat=5') // /foo/bar
How to enable loglevel debug on Apache2 server
Do note that on newer Apache versions the RewriteLog
and RewriteLogLevel
have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):
AH00526: Syntax error on line xx of path/to/config/file.conf:
Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`
Instead, you're now supposed to use the general LogLevel
directive, with a level of trace1
up to trace8
. 'debug' didn't display any rewrite messages in the log for me.
Example: LogLevel warn rewrite:trace3
For the official documentation, see here.
Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.
How do I set up CLion to compile and run?
I met some problems in Clion and finally, I solved them. Here is some experience.
- Download and install MinGW
- g++ and gcc package should be installed by default. Use the MinGW installation manager to install mingw32-libz and mingw32-make. You can open MinGW installation manager through C:\MinGW\libexec\mingw-get.exe This step is the most important step. If Clion cannot find make, C compiler and C++ compiler, recheck the MinGW installation manager to make every necessary package is installed.
- In Clion, open File->Settings->Build,Execution,Deployment->Toolchains. Set MinGW home as your local MinGW file.
- Start your "Hello World"!
GIT vs. Perforce- Two VCS will enter... one will leave
The one important difference between Perforce and git (and the one most commonly mentioned) is their respective handling of huge binary files.
Like, for example, in this blog of an employee at a video game development company: http://corearchitecture.blogspot.com/2011/09/git-vs-perforce-from-game-development.html
However, the important thing is that, the speed difference between git and perforce, when you have a huge 6gb repository, containing everything from documentation to every binary ever built (and finally, oh yes! the actual source history), usually comes from the fact that huge companies tend to run Perforce, and so they set it up to offload all significant operations to the huge server bank in the basement.
This important advantage on Perforce's part comes only from a factor that has nothing whatsoever to do with Perforce, the fact that the company running it can afford said server bank.
And, anyway, in the end, Perforce and git are different products. Git was designed to be solely a VCS, and it does this far better than Perforce (in that it has more features, which are generally easier to use, in particular, in the words of another, branching in Perforce is like performing open-heart surgery, it should only be done by experts :P ) ( http://stevehanov.ca/blog/index.php?id=50 )
Any other benefits which companies that use Perforce gain have come merely because Perforce is not solely a VCS, it's also a fileserver, as well as having a host of other features for testing the performance of builds, etc.
Finally: Git being open-source and far more flexible to boot, it would not be so hard to patch git to offload important operations to a central server, running mounds of expensive hardware.
Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml
This is the quickest way to solve the problem but it's not recommended because its applicable only for your local system.
Download the jar, comment your previous entry for ojdbc6
, and give a new local entry like so:
Previous Entry:
<!-- OJDBC6 Dependency -->
<!-- <dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>1.0</version>
<scope>runtime</scope>
</dependency> -->
New Entry:
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/ojdbc6/ojdbc6.jar</systemPath>
</dependency>
Check if a string is a valid Windows directory (folder) path
Path.GetFullPath gives below exceptions only
ArgumentException path is a zero-length string, contains only white
space, or contains one or more of the invalid characters defined in
GetInvalidPathChars.
-or- The system could not retrieve the absolute path.
SecurityException The caller does not have the required permissions.
ArgumentNullException path is null.
NotSupportedException path contains a colon (":") that is not part of
a volume identifier (for example, "c:\").
PathTooLongException The specified path, file name, or both exceed
the system-defined maximum length. For example, on Windows-based
platforms, paths must be less than 248 characters, and file names must
be less than 260 characters.
Alternate way is to use the following :
/// <summary>
/// Validate the Path. If path is relative append the path to the project directory by default.
/// </summary>
/// <param name="path">Path to validate</param>
/// <param name="RelativePath">Relative path</param>
/// <param name="Extension">If want to check for File Path</param>
/// <returns></returns>
private static bool ValidateDllPath(ref string path, string RelativePath = "", string Extension = "")
{
// Check if it contains any Invalid Characters.
if (path.IndexOfAny(Path.GetInvalidPathChars()) == -1)
{
try
{
// If path is relative take %IGXLROOT% as the base directory
if (!Path.IsPathRooted(path))
{
if (string.IsNullOrEmpty(RelativePath))
{
// Exceptions handled by Path.GetFullPath
// ArgumentException path is a zero-length string, contains only white space, or contains one or more of the invalid characters defined in GetInvalidPathChars. -or- The system could not retrieve the absolute path.
//
// SecurityException The caller does not have the required permissions.
//
// ArgumentNullException path is null.
//
// NotSupportedException path contains a colon (":") that is not part of a volume identifier (for example, "c:\").
// PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
// RelativePath is not passed so we would take the project path
path = Path.GetFullPath(RelativePath);
}
else
{
// Make sure the path is relative to the RelativePath and not our project directory
path = Path.Combine(RelativePath, path);
}
}
// Exceptions from FileInfo Constructor:
// System.ArgumentNullException:
// fileName is null.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.ArgumentException:
// The file name is empty, contains only white spaces, or contains invalid characters.
//
// System.IO.PathTooLongException:
// The specified path, file name, or both exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters, and file names must be less than 260 characters.
//
// System.NotSupportedException:
// fileName contains a colon (:) in the middle of the string.
FileInfo fileInfo = new FileInfo(path);
// Exceptions using FileInfo.Length:
// System.IO.IOException:
// System.IO.FileSystemInfo.Refresh() cannot update the state of the file or
// directory.
//
// System.IO.FileNotFoundException:
// The file does not exist.-or- The Length property is called for a directory.
bool throwEx = fileInfo.Length == -1;
// Exceptions using FileInfo.IsReadOnly:
// System.UnauthorizedAccessException:
// Access to fileName is denied.
// The file described by the current System.IO.FileInfo object is read-only.-or-
// This operation is not supported on the current platform.-or- The caller does
// not have the required permission.
throwEx = fileInfo.IsReadOnly;
if (!string.IsNullOrEmpty(Extension))
{
// Validate the Extension of the file.
if (Path.GetExtension(path).Equals(Extension, StringComparison.InvariantCultureIgnoreCase))
{
// Trim the Library Path
path = path.Trim();
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
catch (ArgumentNullException)
{
// System.ArgumentNullException:
// fileName is null.
}
catch (System.Security.SecurityException)
{
// System.Security.SecurityException:
// The caller does not have the required permission.
}
catch (ArgumentException)
{
// System.ArgumentException:
// The file name is empty, contains only white spaces, or contains invalid characters.
}
catch (UnauthorizedAccessException)
{
// System.UnauthorizedAccessException:
// Access to fileName is denied.
}
catch (PathTooLongException)
{
// System.IO.PathTooLongException:
// The specified path, file name, or both exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters, and file names must be less than 260 characters.
}
catch (NotSupportedException)
{
// System.NotSupportedException:
// fileName contains a colon (:) in the middle of the string.
}
catch (FileNotFoundException)
{
// System.FileNotFoundException
// The exception that is thrown when an attempt to access a file that does not
// exist on disk fails.
}
catch (IOException)
{
// System.IO.IOException:
// An I/O error occurred while opening the file.
}
catch (Exception)
{
// Unknown Exception. Might be due to wrong case or nulll checks.
}
}
else
{
// Path contains invalid characters
}
return false;
}
getaddrinfo: nodename nor servname provided, or not known
rest-client's RestClient
needs the http:
scheme when resolving the URL. It calls Net::HTTP
for you, which doesn't want the http:
part, but rest-client takes care of that.
Is the URL the actual one you are attempting to reach? example.org is a valid domain used for testing and documentation and is reachable; I'd expect the "api" and "api_endpoint" parts to fail and see that when I try to reach them.
require 'socket'
IPSocket.getaddress('example.org') # => "2620:0:2d0:200::10"
IPSocket.getaddress('api.example.org') # =>
# ~> -:7:in `getaddress': getaddrinfo: nodename nor servname provided, or not known (SocketError)
# ~> from -:7:in `<main>'
Here's what I get using Curl:
greg-mbp-wireless:~ greg$ curl api.example.org/api_endpoint
curl: (6) Couldn't resolve host 'api.example.org'
greg-mbp-wireless:~ greg$ curl example.org/api_endpoint
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /api_endpoint was not found on this server.</p>
<hr>
<address>Apache Server at example.org Port 80</address>
</body></html>
greg-mbp-wireless:~ greg$ curl example.org
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>Example Web Page</TITLE>
</HEAD>
<body>
<p>You have reached this web page by typing "example.com",
"example.net","example.org"
or "example.edu" into your web browser.</p>
<p>These domain names are reserved for use in documentation and are not available
for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC
2606</a>, Section 3.</p>
</BODY>
</HTML>
iPhone - Get Position of UIView within entire UIWindow
That's an easy one:
[aView convertPoint:localPosition toView:nil];
... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:
[aView.superview convertPoint:aView.frame.origin toView:nil];
2014 Edit: Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...
- don't change when rotating the device.
- always have their origin in the top left corner of the unrotated screen.
- are window coordinates: The coordinate system ist defined by the bounds of the window. The screen's and device coordinate systems are different and should not be mixed up with window coordinates.
How do I test if a variable is a number in Bash?
Just a follow up to @mary. But because I don't have enough rep, couldn't post this as a comment to that post. Anyways, here is what I used:
isnum() { awk -v a="$1" 'BEGIN {print (a == a + 0)}'; }
The function will return "1" if the argument is a number, otherwise will return "0". This works for integers as well as floats. Usage is something like:
n=-2.05e+07
res=`isnum "$n"`
if [ "$res" == "1" ]; then
echo "$n is a number"
else
echo "$n is not a number"
fi
How to get all elements inside "div" that starts with a known text
With modern browsers, this is easy without jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^=
which means "starts with".
Note that all browsers released since June 2009 support this.
How do I configure Maven for offline development?
You can run maven in offline mode mvn -o install
. Of course any artifacts not available in your local repository will fail. Maven is not predicated on distributed repositories, but they certainly make things more seamless. Its for this reason that many shops use internal mirrors that are incrementally synced with the central repos.
In addition, the mvn dependency:go-offline
can be used to ensure you have all of your dependencies installed locally before you begin to work offline.
JFrame background image
You can do:
setContentPane(new JLabel(new ImageIcon("resources/taverna.jpg")));
At first line of the Jframe class constructor, that works fine for me
Extracting Nupkg files using command line
You can also use the NuGet command line, by specifying a local host as part of an install. For example if your package is stored in the current directory
nuget install MyPackage -Source %cd% -OutputDirectory packages
will unpack it into the target directory.
date format yyyy-MM-ddTHH:mm:ssZ
You could split things up, it would require more code but would work just the way you like it:
DateTime year = DateTime.Now.Year;
DateTime month = DateTime.Now.Month;
DateTime day = DateTime.Now.Day;
ect.
finally:
Console.WriteLine(year+month+day+etc.);
This is a very bold way of handling it though...
How do I find the length/number of items present for an array?
If the array is statically allocated, use sizeof(array) / sizeof(array[0])
If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0])
(which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.
Detecting when Iframe content has loaded (Cross browser)
to detect when the iframe has loaded and its document is ready?
It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).
If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:
<img id="x" ... />
<script type="text/javascript">
document.getElementById('x').onload= function() {
...
};
</script>
there is no guarantee that the item won't already have loaded by the time the script executes.
The ways out of load-races are:
on IE, you can use the ‘readyState’ property to see if something's already loaded;
if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;
the old-school way of including it in the markup:
<img onload="callback(this)" ... />
Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.
Notepad++ Multi editing
You can add/edit content on multiple lines by using control button. This is multi edit feature in Notepad++, we need to enable it from settings. Press and hold control, select places where you want to enter text, release control and start typing, this will update the text at all the places selected previously.
Ref: http://notepad-plus-plus.org/features/multi-editing.html
My docker container has no internet
I do not know what I am doing but that worked for me :
OTHER_BRIDGE=br-xxxxx # this is the other random docker bridge (`ip addr` to find)
service docker stop
ip link set dev $OTHER_BRIDGE down
ip link set dev docker0 down
ip link delete $OTHER_BRIDGE type bridge
ip link delete docker0 type bridge
service docker start && service docker stop
iptables -t nat -A POSTROUTING ! -o docker0 -s 172.17.0.0/16 -j MASQUERADE
iptables -t nat -A POSTROUTING ! -o docker0 -s 172.18.0.0/16 -j MASQUERADE
service docker start
How do I detect "shift+enter" and generate a new line in Textarea?
I use div by adding contenteditable true instead of using textarea.
Hope can help you.
$("#your_textarea").on('keydown', function(e){//textarea keydown events
if(e.key == "Enter")
{
if(e.shiftKey)//jump new line
{
// do nothing
}
else // do sth,like send message or else
{
e.preventDefault();//cancell the deafult events
}
}
})
Handling NULL values in Hive
Try using isnull(a), isnotnull(a), nvl(), etc. On some versions(potentially in conjunction with the server settings - atleast with the one I am working on) of hive the 'IS NULL' and 'IS NOT NULL' syntax does not execute the logic when it is compiled. Check here for more information.
Batch File; List files in directory, only filenames?
The full command is:
dir /b /a-d
Let me break it up;
Basically the /b
is what you look for.
/a-d
will exclude the directory names.
For more information see dir /?
for other arguments that you can use with the dir
command.
Difference between using Makefile and CMake to compile the code
The statement about CMake being a "build generator" is a common misconception.
It's not technically wrong; it just describes HOW it works, but not WHAT it does.
In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.
So, what is the real difference?
CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make
has some built-in C/C++ rules as well, but they are useless at best.
CMake
does a two-step build: it generates a low-level build script in ninja
or make
or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile
are only executed at the generation stage. Thus, CMake
build can be orders of magnitude faster.
The grammar of CMake
is much easier to support for external tools than make's.
Once make
builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake
tracks it, make
leaves it up to you. If one of library sources was removed since the previous version of Makefile
, make
won't rebuild it.
Modern CMake
(starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies.
These transitive dependencies can be exposed to or hidden from the dependent packages. CMake
will manage directories for you. With make
, you're stuck on a file-by-file and manage-directories-by-hand level.
You could code up something in make
using intermediate files to cover the last two gaps, but you're on your own. make
does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.
To be honest, this is what CMake
and make
have in common -- their languages are pretty horrible. Here's what comes to mind:
- They have no user-defined types;
CMake
has three data types: string, list, and a target with properties. make
has one: string;
- you normally pass arguments to functions by setting global variables.
- This is partially dealt with in modern CMake - you can set a target's properties:
set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}")
;
- referring to an undefined variable is silently ignored by default;
jQuery Remove string from string
If you just want to remove "username1" you can use a simple replace.
name.replace("username1,", "")
or you could use split like you mentioned.
var name = "username1, username2 and username3 like this post.".split(",")[1];
$("h1").text(name);
jsfiddle example
-didSelectRowAtIndexPath: not being called
If the cell you are clicking is being highlighted but the function is still not being called, double check your function's signature. It should look like this:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
How can I use Helvetica Neue Condensed Bold in CSS?
After a lot of fiddling, got it working (only tested in Webkit) using:
font-family: "HelveticaNeue-CondensedBold";
font-stretch was dropped between CSS2 and 2.1, though is back in CSS3, but is only supported in IE9 (never thought I'd be able to say that about any CSS prop!)
This works because I'm using the postscript name (find the font in Font Book, hit cmd+I), which is non-standard behaviour. It's probably worth using:
font-family: "HelveticaNeue-CondensedBold", "Helvetica Neue";
As a fallback, else other browsers might default to serif if they can't work it out.
Demo: http://jsfiddle.net/ndFTL/12/
How to create a md5 hash of a string in C?
All of the existing answers use the deprecated MD5Init()
, MD5Update()
, and MD5Final()
.
Instead, use EVP_DigestInit_ex()
, EVP_DigestUpdate()
, and EVP_DigestFinal_ex()
, e.g.
// example.c
//
// gcc example.c -lssl -lcrypto -o example
#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>
void bytes2md5(const char *data, int len, char *md5buf) {
// Based on https://www.openssl.org/docs/manmaster/man3/EVP_DigestUpdate.html
EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
const EVP_MD *md = EVP_md5();
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len, i;
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, data, len);
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_free(mdctx);
for (i = 0; i < md_len; i++) {
snprintf(&(md5buf[i * 2]), 16 * 2, "%02x", md_value[i]);
}
}
int main(void) {
const char *hello = "hello";
char md5[33]; // 32 characters + null terminator
bytes2md5(hello, strlen(hello), md5);
printf("%s\n", md5);
}
How to dynamically insert a <script> tag via jQuery after page load?
Example:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
It should work. I tried it; same outcome. But when I used this:
var length = 1;
var html = "";
for (var i = 0; i < length; i++) {
html += '<div id="codeSnippet"></div>';
html += '<script type="text/javascript">';
html += 'your script here';
html += '</script>';
}
$('#someElement').replaceWith(a);
This worked for me.
Edit: I forgot the #someelement
(btw I might want to use #someElement
because of conventions)
The most important thing here is the += so the html is added and not replaced.
Leave a comment if it didn't work. I'd like to help you out!
Add new line in text file with Windows batch file
DISCLAIMER: The below solution does not preserve trailing tabs.
If you know the exact number of lines in the text file, try the following method:
@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /P L=
IF %%i==%insertbefore% ECHO(
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.
After finishing, the original file is deleted and the temporary one gets assigned the original name.
UPDATE
If the number of lines is unknown beforehand, you can use the following method to obtain it:
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
(This line simply replaces the SET totallines=200
line in the above script.)
The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.
SQL Server - inner join when updating
UPDATE R
SET R.status = '0'
FROM dbo.ProductReviews AS R
INNER JOIN dbo.products AS P
ON R.pid = P.id
WHERE R.id = '17190'
AND P.shopkeeper = '89137';
htons() function in socket programing
htons
is host-to-network short
This means it works on 16-bit short integers. i.e. 2 bytes.
This function swaps the endianness of a short.
Your number starts out at:
0001 0011 1000 1001 = 5001
When the endianness is changed, it swaps the two bytes:
1000 1001 0001 0011 = 35091
How do I detect a click outside an element?
I have an application that works similarly to Eran's example, except I attach the click event to the body when I open the menu... Kinda like this:
$('#menucontainer').click(function(event) {
$('html').one('click',function() {
// Hide the menus
});
event.stopPropagation();
});
More information on jQuery's one()
function
JUnit Eclipse Plugin?
You should be able to add the Java Development Tools by selecting 'Help' -> 'Install New Software', there you select the 'Juno' update site, then 'Programming Languages' -> 'Eclipse Java Development Tools'.
After that, you will be able to run your JUnit tests with 'Right Click' -> 'Run as' -> 'JUnit test'.
How to change the default docker registry from docker.io to my private registry?
I'm adding up to the original answer given by Guy which is still valid today (soon 2020).
Overriding the default docker registry, like you would do with maven
, is actually not a good practice.
When using maven
, you pull artifacts from Maven Central Repository through your local repository management system that will act as a proxy. These artifacts are plain, raw libs (jars) and it is quite unlikely that you will push jars with the same name.
On the other hand, docker images are fully operational, runnable, environments, and it makes total sens to pull an image from the Docker Hub, modify it and push this image in your local registry management system with the same name, because it is exactly what its name says it is, just in your enterprise context. In this case, the only distinction between the two images would precisely be its path!!
Therefore the need to set the following rule: the prefix of an image indicates its origin; by default if an image does not have a prefix, it is pulled from Docker Hub.
Selecting with complex criteria from pandas.DataFrame
You can use pandas it has some built in functions for comparison. So if you want to select values of "A" that are met by the conditions of "B" and "C" (assuming you want back a DataFrame pandas object)
df[['A']][df.B.gt(50) & df.C.ne(900)]
df[['A']]
will give you back column A in DataFrame format.
pandas 'gt' function will return the positions of column B that are greater than 50 and 'ne' will return the positions not equal to 900.
How to execute a program or call a system command from Python
As of Python 3.7.0 released on June 27th 2018 (https://docs.python.org/3/whatsnew/3.7.html), you can achieve your desired result in the most powerful while equally simple way. This answer intends to show you the essential summary of various options in a short manner. For in-depth answers, please see the other ones.
TL;DR in 2021
The big advantage of os.system(...)
was its simplicity. subprocess
is better and still easy to use, especially as of Python 3.5.
import subprocess
subprocess.run("ls -a", shell=True)
Note: This is the exact answer to your question - running a command
like in a shell
Preferred Way
If possible, remove the shell overhead and run the command directly (requires a list).
import subprocess
subprocess.run(["help"])
subprocess.run(["ls", "-a"])
Pass program arguments in a list. Don't include \"
-escaping for arguments containing spaces.
Advanced Use Cases
Checking The Output
The following code speaks for itself:
import subprocess
result = subprocess.run(["ls", "-a"], capture_output=True, text=True)
if "stackoverflow-logo.png" in result.stdout:
print("You're a fan!")
else:
print("You're not a fan?")
result.stdout
is all normal program output excluding errors. Read result.stderr
to get them.
capture_output=True
- turns capturing on. Otherwise result.stderr
and result.stdout
would be None
. Available from Python 3.7.
text=True
- a convenience argument added in Python 3.7 which converts the received binary data to Python strings you can easily work with.
Checking the returncode
Do
if result.returncode == 127: print("The program failed for some weird reason")
elif result.returncode == 0: print("The program succeeded")
else: print("The program failed unexpectedly")
If you just want to check if the program succeeded (returncode == 0) and otherwise throw an Exception, there is a more convenient function:
result.check_returncode()
But it's Python, so there's an even more convenient argument check
which does the same thing automatically for you:
result = subprocess.run(..., check=True)
stderr should be inside stdout
You might want to have all program output inside stdout, even errors. To accomplish this, run
result = subprocess.run(..., stderr=subprocess.STDOUT)
result.stderr
will then be None
and result.stdout
will contain everything.
using shell=False with an argument string
shell=False
expects a list of arguments. You might however, split an argument string on your own using shlex.
import subprocess
import shlex
subprocess.run(shlex.split("ls -a"))
That's it.
Common Problems
Chances are high you just started using Python when you come across this question. Let's look at some common problems.
FileNotFoundError: [Errno 2] No such file or directory: 'ls -a': 'ls -a'
You're running a subprocess without shell=True
. Either use a list (["ls", "-a"]
) or set shell=True
.
TypeError: [...] NoneType [...]
Check that you've set capture_output=True
.
TypeError: a bytes-like object is required, not [...]
You always receive byte results from your program. If you want to work with it like a normal string, set text=True
.
subprocess.CalledProcessError: Command '[...]' returned non-zero exit status 1.
Your command didn't run successfully. You could disable returncode checking or check your actual program's validity.
TypeError: init() got an unexpected keyword argument [...]
You're likely using a version of Python older than 3.7.0; update it to the most recent one available. Otherwise there are other answers in this StackOverflow post showing you older alternative solutions.
Git SSH error: "Connect to host: Bad file number"
The following solution worked for me when tried to SSH into to AWS EC2 Ubuntu instance from my Windows 7 (32 Bit) PC behind corporate firewall setting up Proxy-
Add the following block to C:\Users\<YOUR_WINDOWS_USER>\.ssh\config
file-
> Host *
> ProxyCommand "C:/Program Files/Git/mingw32/bin/connect.exe" -H <YOUR_PROXY_SERVER_HOST>:<YOUR_PROXY_SERVER_PORT> %h %p
> IdentityFile "<PATH_OF_YOUR_IDENTITY_FILE>"
> TCPKeepAlive yes
> IdentitiesOnly yes
>
> Host <SERVER_HOST_NAME_OR_IP_YOU_WANT_TO_SSH_INTO>
> Port <SERVER_HOST_PORT_YOU_WANT_TO_SSH_INTO>
> Hostname <SERVER_HOST_NAME_OR_IP_YOU_WANT_TO_SSH_INTO>
You will need to add similar configuration per host that you want to SSH into.
UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7
If the log indicates java.lang.UnsupportedClassVersionError: JVM**** bad major version.
Then the code and server is not compiled with the same JDK version.
To fix this, please switch the JDK version either in code or server JDK.
Try this:-
In the below use case, im switching to 1.7_64 (JDK 1.7 64 bit)
c:\IBM\WebSphere\WSRR\v8.5\bin\managesdk.bat -enableProfile
-profileName WSRRSrv01 -sdkname 1.7_64
Local storage in Angular 2
You can also consider using library maintained by me: ngx-store (npm i ngx-store
)
It makes working with localStorage, sessionStorage and cookies incredibly easy. There are a few supported methods to manipulate the data:
1) Decorator:
export class SomeComponent {
@LocalStorage() items: Array<string> = [];
addItem(item: string) {
this.items.push(item);
console.log('current items:', this.items);
// and that's all: parsing and saving is made by the lib in the background
}
}
Variables stored by decorators can be also shared across different classes - there is also @TempStorage()
(with an alias of @SharedStorage()
)) decorator designed for it.
2) Simple service methods:
export class SomeComponent {
constructor(localStorageService: LocalStorageService) {}
public saveSettings(settings: SettingsInterface) {
this.localStorageService.set('settings', settings);
}
public clearStorage() {
this.localStorageService.utility
.forEach((value, key) => console.log('clearing ', key));
this.localStorageService.clear();
}
}
3) Builder pattern:
interface ModuleSettings {
viewType?: string;
notificationsCount: number;
displayName: string;
}
class ModuleService {
constructor(public localStorageService: LocalStorageService) {}
public get settings(): NgxResource<ModuleSettings> {
return this.localStorageService
.load(`userSettings`)
.setPath(`modules`)
.setDefaultValue({}) // we have to set {} as default value, because numeric `moduleId` would create an array
.appendPath(this.moduleId)
.setDefaultValue({});
}
public saveModuleSettings(settings: ModuleSettings) {
this.settings.save(settings);
}
public updateModuleSettings(settings: Partial<ModuleSettings>) {
this.settings.update(settings);
}
}
Another important thing is you can listen for (every) storage changes, e.g. (the code below uses RxJS v5 syntax):
this.localStorageService.observe()
.filter(event => !event.isInternal)
.subscribe((event) => {
// events here are equal like would be in:
// window.addEventListener('storage', (event) => {});
// excluding sessionStorage events
// and event.type will be set to 'localStorage' (instead of 'storage')
});
WebStorageService.observe()
returns a regular Observable, so you can zip, filter, bounce them etc.
I'm always open to hearing suggestions and questions helping me to improve this library and its documentation.
Append data frames together in a for loop
Try to use rbindlist
approach over rbind
as it's very, very fast.
Example:
library(data.table)
##### example 1: slow processing ######
table.1 <- data.frame(x = NA, y = NA)
time.taken <- 0
for( i in 1:100) {
start.time = Sys.time()
x <- rnorm(100)
y <- x/2 +x/3
z <- cbind.data.frame(x = x, y = y)
table.1 <- rbind(table.1, z)
end.time <- Sys.time()
time.taken <- (end.time - start.time) + time.taken
}
print(time.taken)
> Time difference of 0.1637917 secs
####example 2: faster processing #####
table.2 <- list()
t0 <- 0
for( i in 1:100) {
s0 = Sys.time()
x <- rnorm(100)
y <- x/2 + x/3
z <- cbind.data.frame(x = x, y = y)
table.2[[i]] <- z
e0 <- Sys.time()
t0 <- (e0 - s0) + t0
}
s1 = Sys.time()
table.3 <- rbindlist(table.2)
e1 = Sys.time()
t1 <- (e1-s1) + t0
t1
> Time difference of 0.03064394 secs
How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned
Try this,
It worked for me
SELECT * FROM (
SELECT
[Code],
[Name],
[CategoryCode],
[CreatedDate],
[ModifiedDate],
[CreatedBy],
[ModifiedBy],
[IsActive],
ROW_NUMBER() OVER(PARTITION BY [Code],[Name],[CategoryCode] ORDER BY ID DESC) rownumber
FROM MasterTable
) a
WHERE rownumber = 1
Run function from the command line
I had a requirement of using various python utilities (range, string, etc.) on the command line and had written the tool pyfunc specifically for that. You can use it to enrich you command line usage experience:
$ pyfunc -m range -a 1 7 2
1
3
5
$ pyfunc -m string.upper -a test
TEST
$ pyfunc -m string.replace -a 'analyze what' 'what' 'this'
analyze this
Scheduling recurring task in Android
I am not sure but as per my knowledge I share my views. I always accept best answer if I am wrong .
Alarm Manager
The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive()
method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive()
returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive()
method completes. If your alarm receiver called Context.startService()
, it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver
and Service
will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
Timer
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
\\ here your todo;
}
}, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));
Timer
has some drawbacks that are solved by ScheduledThreadPoolExecutor
. So it's not the best choice
ScheduledThreadPoolExecutor.
You can use java.util.Timer
or ScheduledThreadPoolExecutor
(preferred) to schedule an action to occur at regular intervals on a background thread.
Here is a sample using the latter:
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
(new Runnable() {
public void run() {
// call service
}
}, 0, 10, TimeUnit.MINUTES);
So I preferred ScheduledExecutorService
But Also think about that if the updates will occur while your application is running, you can use a Timer
, as suggested in other answers, or the newer ScheduledThreadPoolExecutor
.
If your application will update even when it is not running, you should go with the AlarmManager
.
The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.
Take note that if you plan on updating when your application is turned off, once every ten minutes is quite frequent, and thus possibly a bit too power consuming.
C# loop - break vs. continue
To break completely out of a foreach loop, break is used;
To go to the next iteration in the loop, continue is used;
Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.
Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.
How to make a gui in python
While some suggestions have included tkinter and wxPython, the other part of the answer to your question is that you will also need to package it using something like py2app, pyinstaller, or py2exe (depending on the operating system). You mentioned the other machines do not have python, so this would be required in order to distribute the entire python environment with your app.
Also have a look at PySide or PyQt. They have a ton of tutorials everywhere and heavy documentation from Qt.
how to set width for PdfPCell in ItextSharp
Try something like this
PdfPCell cell;
PdfPTable tableHeader;
PdfPTable tmpTable;
PdfPTable table = new PdfPTable(10) { WidthPercentage = 100, RunDirection = PdfWriter.RUN_DIRECTION_LTR, ExtendLastRow = false };
// row 1 / cell 1 (merge)
PdfPCell _c = new PdfPCell(new Phrase("SER. No")) { Rotation = -90, VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1 };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 2
_c = new PdfPCell(new Phrase("TYPE OF SHIPPING")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 3
_c = new PdfPCell(new Phrase("ORDER NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 4
_c = new PdfPCell(new Phrase("QTY.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 5
_c = new PdfPCell(new Phrase("DISCHARGE PPORT")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 6 (merge)
_c = new PdfPCell(new Phrase("DESCRIPTION OF GOODS")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 7
_c = new PdfPCell(new Phrase("LINE DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 8 (merge)
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 9 (merge)
_c = new PdfPCell(new Phrase("CLEARANCE DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 10 (merge)
_c = new PdfPCell(new Phrase("CUSTOM PERMIT NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 2 / cell 2
_c = new PdfPCell(new Phrase("AWB / BL NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 3
_c = new PdfPCell(new Phrase("COMPLEX NAME")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 4
_c = new PdfPCell(new Phrase("G.W Kgs.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 5
_c = new PdfPCell(new Phrase("DESTINATON")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 7
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
_doc.Add(table);
///////////////////////////////////////////////////////////
_doc.Close();
You might need to re-adjust slightly on the widths and borders but that is a one shot to do.
How can I install a package with go get?
First, we need GOPATH
The $GOPATH
is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT
directory where Go is installed.
export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin
We used ~/gocode
path in our computer to store the source of our application and its dependencies. The GOPATH
directory will also store the binaries of their packages.
Then check Go env
You system must have $GOPATH
and $GOROOT
, below is my Env:
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Now, you run download go package:
go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]
Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.
Appending an id to a list if not already present in a string
If you really don't want to change your structure, or at least create a copy of it containing the same data (e.g. make a class property with a setter and getter that read from/write to that string behind the scenes), then you can use a regular expression to check if an item is in that "list" at any given time, and if not, append it to the "list" as a separate element.
if not re.match("\b{}\b".format(348521), some_list[0]): some_list.append(348521)
This is probably faster than converting it to a set every time you want to check if an item is in it. But using set
as others have suggested here is a million times better.