I think this is what we like to do very much.
--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;
-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello;
-- step 3 (then authorized the user for that specific database , you have to use the master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO
If you already created a user and assigned to that database before by doing
USE [yourDB]
CREATE USER hello FOR LOGIN hello WITH DEFAULT_SCHEMA=[dbo]
GO
then kindly delete it by doing below and follow the steps
USE yourDB;
GO
DROP USER newlogin;
GO
For more information please follow the links:
Hiding databases for a login on Microsoft Sql Server 2008R2 and above
If you want to access event object as well as data passed, you have to pass event
and ticket.id
both as parameters, like following:
HTML
<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">
Javascript
methods: {
addToCart: function (event, id) {
// use event here as well as id
console.log('In addToCart')
console.log(id)
}
}
See working fiddle: https://jsfiddle.net/nee5nszL/
In case you are using vue-router, you may have to use $event in your v-on:input
method like following:
<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">
Here is working fiddle.
string s = "ABCDEFGH";
s= s.Remove(3, 2).Insert(3, "ZX");
Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq
Save your JSON example to a file, say ex.json and then
yq -y '.' ex.json
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
I installed the Role plugin under Jenkins-3.5, but it does not show the "Manage Roles" option under "Manage Jenkins", and when one follows the security install page from the wiki, all users are locked out instantly. I had to manually shutdown Jenkins on the server, restore the correct configuration settings (/me is happy to do proper backups) and restart Jenkins.
I didn't have high hopes, as that plugin was last updated in 2011
Create some nice new 10 year certificates and install them. The procedure is fairly easy.
Start at (1B) Generate your own CA (Certificate Authority) on this web page: Creating Certificate Authorities and self-signed SSL certificates and generate your CA Certificate and Key. Once you have these, generate your Server Certificate and Key. Create a Certificate Signing Request (CSR) and then sign the Server Key with the CA Certificate. Now install your Server Certificate and Key on the web server as usual, and import the CA Certificate into Internet Explorer's Trusted Root Certification Authority Store (used by the Flex uploader and Chrome as well) and into Firefox's Certificate Manager Authorities Store on each workstation that needs to access the server using the self-signed, CA-signed server key/certificate pair.
You now should not see any warning about using self-signed Certificates as the browsers will find the CA certificate in the Trust Store and verify the server key has been signed by this trusted certificate. Also in e-commerce applications like Magento, the Flex image uploader will now function in Firefox without the dreaded "Self-signed certificate" error message.
If you (or other searchers of this question) were actually interested in creating a contiguous array to fill with integers, consider bytearray and memoryivew:
# cast() is available starting Python 3.3
size = 10**6
ints = memoryview(bytearray(size)).cast('i')
ints.contiguous, ints.itemsize, ints.shape
# (True, 4, (250000,))
ints[0]
# 0
ints[0] = 16
ints[0]
# 16
For Chrome, instead of
response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);
you need to add Content-Security-Policy
string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);
to the HTTP-response-headers.
Note that this assumes you checked on the server whether or not refAuth is allowed.
And also, note that you need to do browser-detection in order to avoid adding the allow-from
header for Chrome (outputs error on console).
For details, see my answer here.
WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.
The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).
Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.
To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).
Just because I can:
function pathName(url, a) {
return (a = document.createElement('a'), a.href = url, a.pathname); //optionally, remove leading '/'
}
pathName("http://www.site.com/234234234") -> "/234234234"
Assuming he opens an interactive session (that is, allocates a pseudo terminal) and you have access to stdin, you can call an ioctl on that device to get the device number (/dev/pts/4711) and try to find that one in /var/run/utmp (where there will also be the username and the IP address the connection originated from).
Here is the example directly from PEP 8 on limiting line length:
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
The Kafka clients no longer require zookeeper but the Kafka servers do need it to operate.
You can get a list of topics with the new AdminClient API but the shell command that ship with Kafka have not yet been rewritten to use this new API.
The other way to use Kafka without Zookeeper is to use a SaaS Kafka-as-a-Service provider such as Confluent Cloud so you don’t see or operate the Kafka brokers (and the required backend Zookeeper ensemble).
For example on Confluent Cloud you would just use the following zookeeper free CLI command:
ccloud topic list
This works, but there might be better solutions.
asking="hello! what's your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking
I'm all for good names, and I often write about the importance of taking great care when choosing names for things. For this very same reason, I am wary of metaphors when naming things. In the original question, "factory" and "synchronizer" look like good names for what they seem to mean. However, "shepherd" and "nanny" are not, because they are based on metaphors. A class in your code can't be literally a nanny; you call it a nanny because it looks after some other things very much like a real-life nanny looks after babies or kids. That's OK in informal speech, but not OK (in my opinion) for naming classes in code that will have to be maintained by who knows whom who knows when.
Why? Because metaphors are culture dependent and often individual dependent as well. To you, naming a class "nanny" can be very clear, but maybe it's not that clear to somebody else. We shouldn't rely on that, unless you're writing code that is only for personal use.
In any case, convention can make or break a metaphor. The use of "factory" itself is based on a metaphor, but one that has been around for quite a while and is currently fairly well known in the programming world, so I would say it's safe to use. However, "nanny" and "shepherd" are unacceptable.
You can still use the Update-Database
command.
Update-Database -Migration <migration name> -Context <context name>
However, judging by the name of your migration i'm assuming it's the first migration so that command may not work. You should be able to delete the entry from the __MigrationHistory
table in your database and then run the Remove-Migration
command again. You could also delete the migration file and just start again.
I am not sure about be the best way, but works fine and all code stays in your ArrayAdapter.
package br.com.fontolan.pessoas.arrayadapter;
import java.util.List;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import br.com.fontolan.pessoas.R;
import br.com.fontolan.pessoas.model.Telefone;
public class TelefoneArrayAdapter extends ArrayAdapter<Telefone> {
private TelefoneArrayAdapter telefoneArrayAdapter = null;
private Context context;
private EditText tipoEditText = null;
private EditText telefoneEditText = null;
private ImageView deleteImageView = null;
public TelefoneArrayAdapter(Context context, List<Telefone> values) {
super(context, R.layout.telefone_form, values);
this.telefoneArrayAdapter = this;
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.telefone_form, parent, false);
tipoEditText = (EditText) view.findViewById(R.id.telefone_form_tipo);
telefoneEditText = (EditText) view.findViewById(R.id.telefone_form_telefone);
deleteImageView = (ImageView) view.findViewById(R.id.telefone_form_delete_image);
final int i = position;
final Telefone telefone = this.getItem(position);
tipoEditText.setText(telefone.getTipo());
telefoneEditText.setText(telefone.getTelefone());
TextWatcher tipoTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
telefoneArrayAdapter.getItem(i).setTipo(s.toString());
telefoneArrayAdapter.getItem(i).setIsDirty(true);
}
};
TextWatcher telefoneTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
telefoneArrayAdapter.getItem(i).setTelefone(s.toString());
telefoneArrayAdapter.getItem(i).setIsDirty(true);
}
};
tipoEditText.addTextChangedListener(tipoTextWatcher);
telefoneEditText.addTextChangedListener(telefoneTextWatcher);
deleteImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
telefoneArrayAdapter.remove(telefone);
}
});
return view;
}
}
Use include("class.classname.php");
And class should use <?php //code ?> not <? //code ?>
I usually just run ez_setup.py. IIRC, that works fine, at least with UAC off.
It also creates an easy_install executable in your Python\scripts subdirectory, which should be in your PATH.
UPDATE: I highly recommend not to bother with easy_install anymore! Jump right to pip, it's better in every regard!
Installation is just as simple: from the installation instructions page, you can download get-pip.py and run it. Works just like the ez_setup.py mentioned above.
From what I understand using,
::-webkit-input-placeholder::before
or ::-webkit-input-placeholder::after
,
to add more placeholder content doesn't work anymore. Think its a new Chrome update.
Really annoying as it was a great workaround, now im back to just adding lots of empty spaces between lines that I want in a placeholder. eg:
<input type="text" value="" id="email1" placeholder="I am on one line. I am on a second line etc etc..." />
Break will only stop the loop while return inside a loop will stop the loop and return from the function.
I am late for the answer but I think this is another solution which is not mentioned here so posting.
Step 1: Make a xml of menu which you want to add like I have to add a filter action on my action bar so I have created a xml filter.xml. The main line to notice is android:orderInCategory this will show the action icon at first or last wherever you want to show. One more thing to note down is the value, if the value is less then it will show at first and if value is greater then it will show at last.
filter.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="@+id/action_filter"
android:title="@string/filter"
android:orderInCategory="10"
android:icon="@drawable/filter"
app:showAsAction="ifRoom" />
</menu>
Step 2: In onCreate() method of fragment just put the below line as mentioned, which is responsible for calling back onCreateOptionsMenu(Menu menu, MenuInflater inflater) method just like in an Activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Step 3: Now add the method onCreateOptionsMenu which will be override as:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.filter, menu); // Use filter.xml from step 1
}
Step 4: Now add onOptionsItemSelected method by which you can implement logic whatever you want to do when you select the added action icon from actionBar:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_filter){
//Do whatever you want to do
return true;
}
return super.onOptionsItemSelected(item);
}
For UNIX, try this. It worked for me:
UPDATE mysql.user
SET authentication_string = PASSWORD('MyNewPass'), password_expired = 'N'
WHERE User = 'root' AND Host = 'localhost';
FLUSH PRIVILEGES;
maybe map
, but since you don't want to make a list, you can write your own...
def call_for_all(f, seq):
for i in seq:
f(i)
then you can do:
call_for_all(lamda x: x.start(), all)
call_for_all(lamda x: x.stop(), all)
by the way, all is a built in function, don't overwrite it ;-)
Since it's a POD struct, you could always memset it to 0 - this might be the easiest way to get the fields initialized (assuming that is appropriate).
Use this if you also want to consider non-javascript users:
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Succesfully Updated')
window.location.href='http://someplace.com';
</SCRIPT>
<NOSCRIPT>
<a href='http://someplace.com'>Successfully Updated. Click here if you are not redirected.</a>
</NOSCRIPT>");
So many answers, yet I can't find any solution that does efficiently what the title of the questions literally asks for (splitting on multiple possible separators—instead, many answers split on anything that is not a word, which is different). So here is an answer to the question in the title, that relies on Python's standard and efficient re
module:
>>> import re # Will be splitting on: , <space> - ! ? :
>>> filter(None, re.split("[, \-!?:]+", "Hey, you - what are you doing here!?"))
['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']
where:
[…]
matches one of the separators listed inside,\-
in the regular expression is here to prevent the special interpretation of -
as a character range indicator (as in A-Z
),+
skips one or more delimiters (it could be omitted thanks to the filter()
, but this would unnecessarily produce empty strings between matched single-character separators), andfilter(None, …)
removes the empty strings possibly created by leading and trailing separators (since empty strings have a false boolean value).This re.split()
precisely "splits with multiple separators", as asked for in the question title.
This solution is furthermore immune to the problems with non-ASCII characters in words found in some other solutions (see the first comment to ghostdog74's answer).
The re
module is much more efficient (in speed and concision) than doing Python loops and tests "by hand"!
Just Do a "npm audit" on your project directory and then go to your project package.json file. In the package.json file you will find all the versions and the package names.This should work irrespective of the OS.
You need to create Object
for the class.
$obj = new Functions();
$var = $obj->filter($_GET['params']);
You can use this code it works fine.
var pinImage = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/009900/");<br>
var marker = new google.maps.Marker({
position: yourlatlong,
icon: pinImage,
map: map
});
There is another hack I use and never saw in any StackOverflow response : using "src" attribute of an image will yield the complete base path of your site. For instance :
var dummy = new Image;
dummy.src = '$'; // using '' will fail on some browsers
var root = dummy.src.slice(0,-1); // remove trailing '$'
On an URL like http://domain.com/somesite/index.html
,
root
will be set to http://domain.com/somesite/
.
This also works for localhost or any valid base URL.
Note that this will cause a failed HTTP request on the $
dummy image.
You can use an existing image instead to avoid this, with only slight code changes.
Another variant uses a dummy link, with no side effect on HTTP requests :
var dummy = document.createElement ('a');
dummy.href = '';
var root = dummy.href;
I did not test it on every browser, though.
Or use new try with resources clause combined with Scanner:
try (Scanner scanner = new Scanner(value)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// process the line
}
}
Rendering text to a texture is simpler than what the Sprite Text demo make it looks like, the basic idea is to use the Canvas class to render to a Bitmap and then pass the Bitmap to an OpenGL texture:
// Create an empty, mutable bitmap
Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_4444);
// get a canvas to paint over the bitmap
Canvas canvas = new Canvas(bitmap);
bitmap.eraseColor(0);
// get a background image from resources
// note the image format must match the bitmap format
Drawable background = context.getResources().getDrawable(R.drawable.background);
background.setBounds(0, 0, 256, 256);
background.draw(canvas); // draw the background to our bitmap
// Draw the text
Paint textPaint = new Paint();
textPaint.setTextSize(32);
textPaint.setAntiAlias(true);
textPaint.setARGB(0xff, 0x00, 0x00, 0x00);
// draw the text centered
canvas.drawText("Hello World", 16,112, textPaint);
//Generate one texture pointer...
gl.glGenTextures(1, textures, 0);
//...and bind it to our array
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
//Create Nearest Filtered Texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
//Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
//Use the Android GLUtils to specify a two-dimensional texture image from our bitmap
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
//Clean up
bitmap.recycle();
This works even in directories that are; outside of normal git permissions.
sudo chmod -R 664 ./* && git checkout -- . && git clean -dfx
Happened to me recently
I use both depending on who in my department I am helping (Some people prefer 2.7, others 3.5). Anyway, I use Anaconda and my default installation is 3.5. I use environments for other versions of python, packages, etc.. So for example, when I wanted to start using python 2.7 I ran:
conda create -n Python27 python=2.7
This creates a new environment named Python27 and installs Python version 2.7. You can add arguments to that line for installing other packages by default or just start from scratch. The environment will automatically activate, to deactivate simply type deactivate
(windows) or source deactivate
(linux, osx) in the command line. To activate in the future type activate Python27
(windows) or source activate Python27
(linux, osx). I would recommend reading the documentation for Managing Environments in Anaconda, if you choose to take that route.
Update
As of conda
version 4.6 you can now use conda activate
and conda deactivate
. The use of source
is now deprecated and will eventually be removed.
If your form is bound to an entity, just set the default value on the entity itself using the construct method:
public function __construct()
{
$this->field = 'default value';
}
Now in Python >= 3.3 you can just call the timestamp() method to get the timestamp as a float.
import datetime
current_time = datetime.datetime.now(datetime.timezone.utc)
unix_timestamp = current_time.timestamp() # works if Python >= 3.3
unix_timestamp_plus_5_min = unix_timestamp + (5 * 60) # 5 min * 60 seconds
Try this:
Integer startIn = null;
try {
startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
.
.
.
}
if (startIn == null) {
// Prompt for value...
}
hmm, I don't know if I would say that online materials are useless, but I do agree that there is something about books. Maybe they are better written, or maybe it is the act of forking over $50 that makes you more inclined to study the material.
Either way, I agree that books should be part of this question. If anyone has any suggestions for books for languages I will edit the post with the best suggestions.
To add the new repo location,
git remote add new_repo_name new_repo_url
Then push the content to the new location
git push new_repo_name master
Finally remove the old one
git remote rm origin
After that you can do what bdonlan said and edit the.git/config file to change the new_repo_name to origin. If you don't remove the origin (original remote repository), you can simply just push changes to the new repo with
git push new_repo_name master
For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.
I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.
dictionary["C1"]=map(lambda x:x+10,dictionary["C1"])
Should do it...
ponder Try Heap. I believe it's the most consistent of the O(n lg n) sorts.
I had this problem because a dll I was using had Sqlite as a dependency (configured in NuGet with only the Sqlite core package.). The project compiles and copies all the Sqlite dll-s except the 'SQLite.Interop.dll' (both x86 and x64 folder).
The solution was very simple: just add the System.Data.SQLite.Core package as a dependency (with NuGet) to the project you are building/running and the dll-s will be copied.
you could have both of them use a "corpo_button" class, or something like that, and then in $(".corpo_button").click(...)
just call $(this).toggleClass("corpo_buttons_asia corpo_buttons_global");
It seems that your configuration is using the print
option for numpy.seterr
:
>>> import numpy as np
>>> np.array([1])/0 #'warn' mode
__main__:1: RuntimeWarning: divide by zero encountered in divide
array([0])
>>> np.seterr(all='print')
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'}
>>> np.array([1])/0 #'print' mode
Warning: divide by zero encountered in divide
array([0])
This means that the warning you see is not a real warning, but it's just some characters printed to stdout
(see the documentation for seterr
). If you want to catch it you can:
numpy.seterr(all='raise')
which will directly raise the exception. This however changes the behaviour of all the operations, so it's a pretty big change in behaviour.numpy.seterr(all='warn')
, which will transform the printed warning in a real warning and you'll be able to use the above solution to localize this change in behaviour.Once you actually have a warning, you can use the warnings
module to control how the warnings should be treated:
>>> import warnings
>>>
>>> warnings.filterwarnings('error')
>>>
>>> try:
... warnings.warn(Warning())
... except Warning:
... print 'Warning was raised as an exception!'
...
Warning was raised as an exception!
Read carefully the documentation for filterwarnings
since it allows you to filter only the warning you want and has other options. I'd also consider looking at catch_warnings
which is a context manager which automatically resets the original filterwarnings
function:
>>> import warnings
>>> with warnings.catch_warnings():
... warnings.filterwarnings('error')
... try:
... warnings.warn(Warning())
... except Warning: print 'Raised!'
...
Raised!
>>> try:
... warnings.warn(Warning())
... except Warning: print 'Not raised!'
...
__main__:2: Warning:
As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10]
as slicing will return the first 10 elements of the list, not the last 10...
To get the last 10 you should do [-10:]
instead (see here). This will help you avoid using order_by('-id')
with the -
to reverse the elements.
You can also consider using Record
, like this:
const someArray: Record<string, string>[] = [
{'first': 'one'},
{'second': 'two'}
];
Or write something like this:
const someArray: {key: string, value: string}[] = [
{key: 'first', value: 'one'},
{key: 'second', value: 'two'}
];
I know that this post is a little old but I had the same problem and tried to fix it several hours. Finally I found the solution:
if we have 2 boxes positioned absolue
<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px;'></div>
<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px;'></div>
we do expect that there will be one box on the screen. To do that we must set margin-bottom equal to -height, so doing like this:
<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px; margin-bottom: -200px;'></div>
<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px; margin-bottom: -200px;'></div>
works fine for me.
On my machine:
C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data
Here's one specific for your code:
var date = $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val();
More general info available here:
If you use
apply plugin: 'com.android.library'
You can convert .aar -> .jar
If you run a gradle task from AndroidStudio[More]
assembleRelease
//or
bundleReleaseAar
or via terminal
./gradlew <moduleName>:assembleRelease
//or
./gradlew <moduleName>:bundleReleaseAar
then you will able to find .aar
in
<project_path>/build/outputs/aar/<module_name>.aar
//if you do not see it try to remove this folder and repeat the command
.aar
[About] file is a zip file with aar extension that is why you can replace .aar
with .zip
or run
unzip "<path_to/module_name>.aar"
This piece of code from Randy Skretka is working fine for me, but I had the problem, that I still had a newline at the end of the file.
(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt
So I added finally this:
$content = [System.IO.File]::ReadAllText("file.txt")
$content = $content.Trim()
[System.IO.File]::WriteAllText("file.txt", $content)
This solution makes use of the DateTimeStyles enumeration, and it also works with Z.
DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);
This prints the solution perfectly.
From Wikipedia: http://en.wikipedia.org/wiki/Jscript
JScript is the Microsoft dialect of the ECMAScript scripting language specification.
JavaScript (the Netscape/Mozilla implementation of the ECMA specification), JScript, and ECMAScript are very similar languages. In fact the name "JavaScript" is often used to refer to ECMAScript or JScript.
Microsoft uses the name JScript for its implementation to avoid trademark issues (JavaScript is a trademark of Oracle Corporation).
I can't be satisfied by the answers calling for a English-only solution based on manual formats. I've been looking for a proper solution for a while now and I finally found it.
You should be using RuleBasedNumberFormat. It works perfectly and it's respectful of the Locale.
Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.
As pointed out, you can use getElementById
instead, but you can also still achieve the same with a querySelector
:
document.querySelector("[id='22']")
In addition to user701648's answer, you can store your credentials in your home folder (global for all projects), instead of project folder using the following command
$ git config --global credential.helper store
$ git push http://example.com/repo.git
Username: <type your username>
Password: <type your password>
Note that there are two different types of equality in C#
1- Value Equality
(For value types like int, DateTime and struct)
2- Reference Equality
(For objects)
There are two basic standard protocols for implement equality checks.
1- The ==
and !=
operators.
2- The virtual
Equals
method.
The == and != are statically resolve, which means C# will make a compile-time decision as to which type will perform the comparison.
For instance the value-type
int x = 50;
int y = 50;
Console.WriteLine (x == y); // True
but for reference type
object x = 50;
object y = 50;
Console.WriteLine (x == y); // False
The Equals()
originally resoled at runtime according to operand actual type.
For instance, in the following example, at runtime, it will be decided that the Equals()
will apply on int values, the result is true
.
object x = 5;
object y = 5;
Console.WriteLine (x.Equals (y)); // True
However, for a reference type, it will use a reference equality check.
MyObject x = new MyObject();
MyObject y = x;
Console.WriteLine (x.Equals (y)); // True
Note that Equals()
uses structural comparison for struct
, which means it calls Equals on each field of a struct.
Juste add ShowHeaderWhenEmpty property and set it at true
This solution works for me
I think you should edit the anchor tag on bootstrap.css. Otherwise give customized style to the anchor tag with !important
(to override the default style on bootstrap.css).
Example code
.nav {_x000D_
background-color: #000 !important;_x000D_
}_x000D_
_x000D_
.nav>li>a {_x000D_
background-color: #666 !important;_x000D_
color: #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div role="tabpanel">_x000D_
_x000D_
<!-- Nav tabs -->_x000D_
<ul class="nav nav-tabs" role="tablist">_x000D_
<li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>_x000D_
<li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>_x000D_
<li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>_x000D_
<li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>_x000D_
</ul>_x000D_
_x000D_
<!-- Tab panes -->_x000D_
<div class="tab-content">_x000D_
<div role="tabpanel" class="tab-pane active" id="home">...</div>_x000D_
<div role="tabpanel" class="tab-pane" id="profile">tab1</div>_x000D_
<div role="tabpanel" class="tab-pane" id="messages">tab2</div>_x000D_
<div role="tabpanel" class="tab-pane" id="settings">tab3</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Fiddle: http://jsfiddle.net/zjjpocv6/2/
To get it done only with XAML you need to add Validation Rules for individual properties. But i would recommend you to go with code behind approach. In your code, define your specifications in properties setters and throw exceptions when ever it doesn't compliance to your specifications. And use error template to display your errors to user in UI. Your XAML will look like this
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="CustomTextBoxTextStyle" TargetType="TextBox">
<Setter Property="Foreground" Value="Green" />
<Setter Property="MaxLength" Value="40" />
<Setter Property="Width" Value="392" />
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Trigger.Setters>
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
<Setter Property="Background" Value="Red"/>
</Trigger.Setters>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox Name="tb2" Height="30" Width="400"
Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"
Style="{StaticResource CustomTextBoxTextStyle}"/>
</Grid>
Code Behind:
public partial class MainWindow : Window
{
private ExampleViewModel m_ViewModel;
public MainWindow()
{
InitializeComponent();
m_ViewModel = new ExampleViewModel();
DataContext = m_ViewModel;
}
}
public class ExampleViewModel : INotifyPropertyChanged
{
private string m_Name = "Type Here";
public ExampleViewModel()
{
}
public string Name
{
get
{
return m_Name;
}
set
{
if (String.IsNullOrEmpty(value))
{
throw new Exception("Name can not be empty.");
}
if (value.Length > 12)
{
throw new Exception("name can not be longer than 12 charectors");
}
if (m_Name != value)
{
m_Name = value;
OnPropertyChanged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
More efficient ways of concatenating strings are:
join():
Very efficent, but a bit hard to read.
>>> Section = 'C_type'
>>> new_str = ''.join(['Sec_', Section]) # inserting a list of strings
>>> print new_str
>>> 'Sec_C_type'
String formatting:
Easy to read and in most cases faster than '+' concatenating
>>> Section = 'C_type'
>>> print 'Sec_%s' % Section
>>> 'Sec_C_type'
It can be:
echo "Welcome".$_POST['firstname'].$_POST['lastname'];
Got a similar error on IIS Express with Visual Studio 2017.
HTTP Error 413.0 - Request Entity Too Large
The page was not displayed because the request entity is too large.
Most likely causes:
The Web server is refusing to service the request because the request entity is too large.
The Web server cannot service the request because it is trying to negotiate a client certificate but the request entity is too large.
The request URL or the physical mapping to the URL (i.e., the physical file system path to the URL's content) is too long.
Things you can try:
Verify that the request is valid.
If using client certificates, try:
Increasing system.webServer/serverRuntime@uploadReadAheadSize
Configure your SSL endpoint to negotiate client certificates as part of the initial SSL handshake. (netsh http add sslcert ... clientcertnegotiation=enable) .vs\config\applicationhost.config
Solve this by editing \.vs\config\applicationhost.config
. Switch serverRuntime
from Deny
to Allow
like this:
<section name="serverRuntime" overrideModeDefault="Allow" />
If this value is not edited, you will get an error like this when setting uploadReadAheadSize
:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".
Then edit Web.config
with the following values:
<system.webServer>
<serverRuntime uploadReadAheadSize="10485760" />
...
Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.
Ajax call:
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'html',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data == '') ? 'error' : 'success')
.html(data).show(500);
if (data == '') {
$('#message').html("Format your email correcly");
$('#demoForm').show(500);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
post.php
<?php
sleep(1);
function processEmail($email) {
if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
// your logic here (ex: add into database)
return true;
}
return false;
}
if (processEmail($_POST['email'])) {
echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}
Just been doing that myself today... here is code I have working for me...
$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl
I use:
<link rel="stylesheet" href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css">
<a class="icon fa-car" aria-hidden="true" style="color:white;" href="http://viettelquangbinh.com"></a>
and style after:
.icon::before {
display: inline-block;
margin-right: .5em;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
transform: translate(0, 0);
}
It would be either of
There are answers with big number of votes, but when I read your question, I thought you wanted to know the directory where the script is, not that where the script is running. You can get the information with powershell's auto variables
$PSScriptRoot - the directory where the script exists, not the target directory the script is running in
$PSCommandPath - the full path of the script
For example, I have $profile script that finds visual studio solution file and start it. I wanted to store the full path, once a solution file is started. But I wanted to save the file where the original script exists. So I used $PsScriptRoot.
On python 3.5.2
sudo apt-get install libmysqlclient-dev python-dev
You need to add import com.fasterxml.jackson.annotation.JsonInclude;
Add
@JsonInclude(JsonInclude.Include.NON_NULL)
on top of POJO
If you have nested POJO then
@JsonInclude(JsonInclude.Include.NON_NULL)
need to add on every values.
NOTE: JAXRS (Jersey) automatically handle this scenario 2.6 and above.
Compared to window.location="url";
it is much easyer to do just location="url";
I always use that
Here's my thread control function:
#!/bin/bash
# This function just checks jobs in background, don't do more things.
# if jobs number is lower than MAX, then return to get more jobs;
# if jobs number is greater or equal to MAX, then wait, until someone finished.
# Usage:
# thread_max 8
# thread_max 0 # wait, until all jobs completed
thread_max() {
local CHECK_INTERVAL="3s"
local CUR_THREADS=
local MAX=
[[ $1 ]] && MAX=$1 || return 127
# reset MAX value, 0 is easy to remember
[ $MAX -eq 0 ] && {
MAX=1
DEBUG "waiting for all tasks finish"
}
while true; do
CUR_THREADS=`jobs -p | wc -w`
# workaround about jobs bug. If don't execute it explicitily,
# CUR_THREADS will stick at 1, even no jobs running anymore.
jobs &>/dev/null
DEBUG "current thread amount: $CUR_THREADS"
if [ $CUR_THREADS -ge $MAX ]; then
sleep $CHECK_INTERVAL
else
return 0
fi
done
}
Just adding to the correct answer you can set the timeout with the arrow function like this:
it('Some test', () => {
}).timeout(5000)
You just need to put the file path (directory) before the name of the image. Example:
fig.savefig('/home/user/Documents/graph.png')
Other example:
fig.savefig('/home/user/Downloads/MyImage.png')
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
UPDATED ANSWER:
Old answer, correct method nowadays is to use jQuery's .prop()
. IE, element.prop("selected", true)
OLD ANSWER:
Use this instead:
$("#routetype option[value='quietest']").attr("selected", "selected");
Fiddle'd: http://jsfiddle.net/x3UyB/4/
decimal d = // your number..
decimal t = d - Math.Floor(d);
if(t >= 0.3d && t <= 0.7d)
{
return Math.Floor(d) + 0.5d;
}
else if(t>0.7d)
return Math.Ceil(d);
return Math.Floor(d);
In most recent versions of Kafka Manager, there is a column titled Summed Recent Offsets.
public abstract class Refl {
/** Use: Refl.<TargetClass>get(myObject,"x.y[0].z"); */
public static<T> T get(Object obj, String fieldPath) {
return (T) getValue(obj, fieldPath);
}
public static Object getValue(Object obj, String fieldPath) {
String[] fieldNames = fieldPath.split("[\\.\\[\\]]");
String success = "";
Object res = obj;
for (String fieldName : fieldNames) {
if (fieldName.isEmpty()) continue;
int index = toIndex(fieldName);
if (index >= 0) {
try {
res = ((Object[])res)[index];
} catch (ClassCastException cce) {
throw new RuntimeException("cannot cast "+res.getClass()+" object "+res+" to array, path:"+success, cce);
} catch (IndexOutOfBoundsException iobe) {
throw new RuntimeException("bad index "+index+", array size "+((Object[])res).length +" object "+res +", path:"+success, iobe);
}
} else {
Field field = getField(res.getClass(), fieldName);
field.setAccessible(true);
try {
res = field.get(res);
} catch (Exception ee) {
throw new RuntimeException("cannot get value of ["+fieldName+"] from "+res.getClass()+" object "+res +", path:"+success, ee);
}
}
success += fieldName + ".";
}
return res;
}
public static Field getField(Class<?> clazz, String fieldName) {
Class<?> tmpClass = clazz;
do {
try {
Field f = tmpClass.getDeclaredField(fieldName);
return f;
} catch (NoSuchFieldException e) {
tmpClass = tmpClass.getSuperclass();
}
} while (tmpClass != null);
throw new RuntimeException("Field '" + fieldName + "' not found in class " + clazz);
}
private static int toIndex(String s) {
int res = -1;
if (s != null && s.length() > 0 && Character.isDigit(s.charAt(0))) {
try {
res = Integer.parseInt(s);
if (res < 0) {
res = -1;
}
} catch (Throwable t) {
res = -1;
}
}
return res;
}
}
It supports fetching fields and array items, e.g.:
System.out.println(""+Refl.getValue(b,"x.q[0].z.y"));
there is no difference between dots and braces, they are just delimiters, and empty field names are ignored:
System.out.println(""+Refl.getValue(b,"x.q[0].z.y[value]"));
System.out.println(""+Refl.getValue(b,"x.q.1.y.z.value"));
System.out.println(""+Refl.getValue(b,"x[q.1]y]z[value"));
java.io.File
class contains four static separator variables. For better understanding, Let's understand with the help of some code
Note that all of these are final variables and system dependent.
Here is the java program to print these separator variables. FileSeparator.java
import java.io.File;
public class FileSeparator {
public static void main(String[] args) {
System.out.println("File.separator = "+File.separator);
System.out.println("File.separatorChar = "+File.separatorChar);
System.out.println("File.pathSeparator = "+File.pathSeparator);
System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
}
}
Output of above program on Unix system:
File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :
Output of the program on Windows system:
File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;
To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.
Here is the code snippet showing how to use separators correctly.
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");
This will draw a line that passes through the points (-1, 1) and (12, 4), and another one that passes through the points (1, 3) et (10, 2)
x1 are the x coordinates of the points for the first line, y1 are the y coordinates for the same -- the elements in x1 and y1 must be in sequence.
x2 and y2 are the same for the other line.
import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 4]
x2, y2 = [1, 10], [3, 2]
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()
I suggest you spend some time reading / studying the basic tutorials found on the very rich matplotlib website to familiarize yourself with the library.
There are no direct ways to have lines extend to infinity... matplotlib will either resize/rescale the plot so that the furthest point will be on the boundary and the other inside, drawing line segments in effect; or you must choose points outside of the boundary of the surface you want to set visible, and set limits for the x and y axis.
As follows:
import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 10]
x2, y2 = [-1, 10], [3, -1]
plt.xlim(0, 8), plt.ylim(-2, 8)
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()
if you are on linux, edit the /etc/php/php.ini
(or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment
;extension=imap.so
so that it becomes like this:
extension=imap.so
Then, restart the apache by
# /etc/rc.d/httpd restart
This is what I have done in order to get the column "first_name" fill the space when all the columns cannot do it.
When the grid go to small the column "first_name" gets almost invisible (very thin) so I can set the DataGridViewAutoSizeColumnMode to AllCells as the others visible columns. For performance issues it´s important to set them to None before data binding it and set back to AllCell in the DataBindingComplete event handler of the grid. Hope it helps!
private void dataGridView1_Resize(object sender, EventArgs e)
{
int ColumnsWidth = 0;
foreach(DataGridViewColumn col in dataGridView1.Columns)
{
if (col.Visible) ColumnsWidth += col.Width;
}
if (ColumnsWidth <dataGridView1.Width)
{
dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
else if (dataGridView1.Columns["first_name"].Width < 10) dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
I was tearing my hair out because for some items, the renamed item would get renamed again (repeatedly, unless max file name length was reached). This was happening both for Get-ChildItem and piping the output of dir. I guess that the renamed files got picked up because of a change in the alphabetical ordering. I solved this problem in the following way:
Get-ChildItem -Path . -OutVariable dirs
foreach ($i in $dirs) { Rename-Item $i.name ("<MY_PREFIX>"+$i.name) }
This "locks" the results returned by Get-ChildItem in the variable $dirs and you can iterate over it without fear that ordering will change or other funny business will happen.
Dave.Gugg's tip for using -Exclude should also solve this problem, but this is a different approach; perhaps if the files being renamed already contain the pattern used in the prefix.
(Disclaimer: I'm very much a PowerShell n00b.)
It is my solution for the same problem
Here's a simple trick that defines column indices "in place". Because set_index
sets row indices in place, we can do the same thing for columns by transposing the data frame, setting the index, and transposing it back:
df = df.T.set_index(0).T
Note you may have to change the 0
in set_index(0)
if your rows have a different index already.
In any one of your js pages you are missing
module.exports = router;
Check and verify all your JS pages
In Ruby and other languages that support POSIX character classes in bracket expressions, you can do simply:
/\A[[:alpha:]]+\z/i
That will match alpha-chars in all Unicode alphabet languages. Easy peasy.
More info: http://en.wikipedia.org/wiki/Regular_expression#Character_classes http://ruby-doc.org/core-2.0/Regexp.html
l = Location.find(:id => id, :select => "name, website, city", :limit => 1)
...or...
l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])
This reference doc gives you the entire list of options you can use with .find
, including how to limit by number, id, or any other arbitrary column/constraint.
l = Location.where(["id = ?", id]).select("name, website, city").first
Ref: Active Record Query Interface
You can also swap the order of these chained calls, doing .select(...).where(...).first
- all these calls do is construct the SQL query and then send it off.
You can't directly control this, because it's an option controlled by Internet Explorer users.
Opening pages using Window.open with a different window name will open in a new browser window like a popup, OR open in a new tab, if the user configured the browser to do so.
I don't think you need the trailing slash in the URL entry. Ie, put this instead:
(r'^led-tv$', filter_by_led ),
This is assuming you have trailing slashes enabled, which is the default.
You could turn '%string%'
to contains()
, 'string%'
to startsWith()
and '%string"'
to endsWith()
.
You should also run toLowerCase()
on both the string and pattern as LIKE
is case-insenstive.
Not sure how you'd handle '%string%other%'
except with a Regular Expression though.
If you're using Regular Expressions:
The following seems to confirm that there are comparison operators for the DateTime class:
dev:~# php
<?php
date_default_timezone_set('Europe/London');
$d1 = new DateTime('2008-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');
var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);
?>
bool(false)
bool(true)
bool(false)
dev:~# php -v
PHP 5.2.6-1+lenny3 with Suhosin-Patch 0.9.6.2 (cli) (built: Apr 26 2009 20:09:03)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
dev:~#
Using Moshi:
When building your Retrofit Service add .asLenient() to your MoshiConverterFactory. You don't need a ScalarsConverter. It should look something like this:
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(ENDPOINT)
.addConverterFactory(MoshiConverterFactory.create().asLenient())
.build()
.create(UserService::class.java)
I found a solution here: http://www.sitepoint.com/maintain-image-aspect-ratios-responsive-web-design/
The trick is possible because it exists a relation between WIDTH and PADDING-BOTTOM of an element. So:
parent:
container {
height: 0;
padding-bottom: 66%; /* for a 4:3 container size */
}
child (remove all css related to width, i.e. width:100%):
img {
max-height: 100%;
max-width: 100%;
position: absolute;
display:block;
margin:0 auto; /* center */
left:0; /* center */
right:0; /* center */
}
Try an OutputStream
or more specifically FileOutputStream
move does not make sense for a hashmap since its a dictionary with a hashcode for bucketing based on key and then a linked list for colliding hashcodes resolved via equals. Use a TreeMap for sorted maps and then pass in a custom comparator.
I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added background-color:white
to the HTML element. I overwrote that and everything was easy to handle from there.
Function pointers in C can be used to perform object-oriented programming in C.
For example, the following lines is written in C:
String s1 = newString();
s1->set(s1, "hello");
Yes, the ->
and the lack of a new
operator is a dead give away, but it sure seems to imply that we're setting the text of some String
class to be "hello"
.
By using function pointers, it is possible to emulate methods in C.
How is this accomplished?
The String
class is actually a struct
with a bunch of function pointers which act as a way to simulate methods. The following is a partial declaration of the String
class:
typedef struct String_Struct* String;
struct String_Struct
{
char* (*get)(const void* self);
void (*set)(const void* self, char* value);
int (*length)(const void* self);
};
char* getString(const void* self);
void setString(const void* self, char* value);
int lengthString(const void* self);
String newString();
As can be seen, the methods of the String
class are actually function pointers to the declared function. In preparing the instance of the String
, the newString
function is called in order to set up the function pointers to their respective functions:
String newString()
{
String self = (String)malloc(sizeof(struct String_Struct));
self->get = &getString;
self->set = &setString;
self->length = &lengthString;
self->set(self, "");
return self;
}
For example, the getString
function that is called by invoking the get
method is defined as the following:
char* getString(const void* self_obj)
{
return ((String)self_obj)->internal->value;
}
One thing that can be noticed is that there is no concept of an instance of an object and having methods that are actually a part of an object, so a "self object" must be passed in on each invocation. (And the internal
is just a hidden struct
which was omitted from the code listing earlier -- it is a way of performing information hiding, but that is not relevant to function pointers.)
So, rather than being able to do s1->set("hello");
, one must pass in the object to perform the action on s1->set(s1, "hello")
.
With that minor explanation having to pass in a reference to yourself out of the way, we'll move to the next part, which is inheritance in C.
Let's say we want to make a subclass of String
, say an ImmutableString
. In order to make the string immutable, the set
method will not be accessible, while maintaining access to get
and length
, and force the "constructor" to accept a char*
:
typedef struct ImmutableString_Struct* ImmutableString;
struct ImmutableString_Struct
{
String base;
char* (*get)(const void* self);
int (*length)(const void* self);
};
ImmutableString newImmutableString(const char* value);
Basically, for all subclasses, the available methods are once again function pointers. This time, the declaration for the set
method is not present, therefore, it cannot be called in a ImmutableString
.
As for the implementation of the ImmutableString
, the only relevant code is the "constructor" function, the newImmutableString
:
ImmutableString newImmutableString(const char* value)
{
ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));
self->base = newString();
self->get = self->base->get;
self->length = self->base->length;
self->base->set(self->base, (char*)value);
return self;
}
In instantiating the ImmutableString
, the function pointers to the get
and length
methods actually refer to the String.get
and String.length
method, by going through the base
variable which is an internally stored String
object.
The use of a function pointer can achieve inheritance of a method from a superclass.
We can further continue to polymorphism in C.
If for example we wanted to change the behavior of the length
method to return 0
all the time in the ImmutableString
class for some reason, all that would have to be done is to:
length
method.length
method.Adding an overriding length
method in ImmutableString
may be performed by adding an lengthOverrideMethod
:
int lengthOverrideMethod(const void* self)
{
return 0;
}
Then, the function pointer for the length
method in the constructor is hooked up to the lengthOverrideMethod
:
ImmutableString newImmutableString(const char* value)
{
ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));
self->base = newString();
self->get = self->base->get;
self->length = &lengthOverrideMethod;
self->base->set(self->base, (char*)value);
return self;
}
Now, rather than having an identical behavior for the length
method in ImmutableString
class as the String
class, now the length
method will refer to the behavior defined in the lengthOverrideMethod
function.
I must add a disclaimer that I am still learning how to write with an object-oriented programming style in C, so there probably are points that I didn't explain well, or may just be off mark in terms of how best to implement OOP in C. But my purpose was to try to illustrate one of many uses of function pointers.
For more information on how to perform object-oriented programming in C, please refer to the following questions:
You can use display:inline-block
.
This property allows a DOM element to have all the attributes of a block element, but keeping it inline. There's some drawbacks, but most of the time it's good enough. Why it's good and why it may not work for you.
EDIT: The only modern browser that has some problems with it is IE7. See Quirksmode.org
Another possible solution is to use a Scanner
object like this:
Scanner scanner = new Scanner(inputString);
if (scanner.hasNextInt()) {
return true;
}
else {
return false
}
Of course, if you are looking for a double
, use hasNextDouble()
method (see: Scanner javadoc)
Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.
As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.
long unixTime = System.currentTimeMillis() / 1000L;
Here is the code for upload to encode and save it to the MySQL
if (!isset($_GET["getfile"])) {
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
$bin_string = file_get_contents($_FILES["file"]["name"]);
$hex_string = base64_encode($bin_string);
$mysqli = mysqli_init();
if (!$mysqli->real_connect('localhost', 'root', '', 'arihant')) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$mysqli->query("INSERT INTO upload(image) VALUES ('" . $hex_string . "')");
}
}
For showing the image use this
echo "<img src='data:image/jpeg;base64, $image' width=300>";
Apple's FixIt supplied %hhd, which correctly gave me the value of my BOOL.
It could be because of couple of Browser settings. Try with these options checked..
Tools > Internet Options > Advanced > Enable Integrated Windows Authentication (works with Integrated Windows Authentication set on IIS)
Tools > Internet Options> Security > Local Intranet > Custom Level > Automatic Logon
Worst case, try adding localhost to the Trusted sites.
If you are in a network, you can also try debugging by getting a network trace. Could be because of some proxy trying to authenticate.
Hey guys this is a good way of link w/ image and has lot of props in case you want to css attribute for example replace "alt" or "title" etc.....also including a logical restriction (?)
<%= link_to image_tag("#{request.ssl? ? @image_domain_secure : @image_domain}/images/linkImage.png", {:alt=>"Alt title", :title=>"Link title"}) , "http://www.site.com"%>
Hope this helps!
Ben Nadel has written a good article about this, he points out the difference in the parameters to these functions:
String.slice( begin [, end ] )
String.substring( from [, to ] )
String.substr( start [, length ] )
He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn't.
Here is his article about this.
for windows; set your proxy in command prompt as
set HTTP_PROXY=domain\username:password@myproxy:myproxyport
example: set http_proxy=IND\namit.kewat:[email protected]:8880
You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.
As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
The function name does not reflect the semantic of the function. In fact you do not append a character. You create a new character array that contains the original array plus the given character. So if you indeed need a function that appends a character to a character array I would write it the following way
bool AppendCharToCharArray( char *array, size_t n, char c )
{
size_t sz = std::strlen( array );
if ( sz + 1 < n )
{
array[sz] = c;
array[sz + 1] = '\0';
}
return ( sz + 1 < n );
}
If you need a function that will contain a copy of the original array plus the given character then it could look the following way
char * CharArrayPlusChar( const char *array, char c )
{
size_t sz = std::strlen( array );
char *s = new char[sz + 2];
std::strcpy( s, array );
s[sz] = c;
s[sz + 1] = '\0';
return ( s );
}
I mixed few answers from answers above and from How to remove the arrows from input[type="number"] in Opera in scss:
input[type=number] {
&,
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
-webkit-appearance: none;
-moz-appearance: textfield;
appearance: none;
&:hover,
&:focus {
-moz-appearance: number-input;
}
}
}
Tested on chrome, firefox, safari
I had this problem where my SQL server rounds up 0.5 to 1 while my C# application didn't. So you would see two different results.
Here's an implementation with int/long. This is how Java rounds.
int roundedNumber = (int)Math.Floor(d + 0.5);
It's probably the most efficient method you could think of as well.
If you want to keep it a double and use decimal precision , then it's really just a matter of using exponents of 10 based on how many decimal places.
public double getRounding(double number, int decimalPoints)
{
double decimalPowerOfTen = Math.Pow(10, decimalPoints);
return Math.Floor(number * decimalPowerOfTen + 0.5)/ decimalPowerOfTen;
}
You can input a negative decimal for decimal points and it's word fine as well.
getRounding(239, -2) = 200
That's what ln
is documented to do when the target already exists and is a directory. If you want /etc/nginx
to be a symlink rather than contain a symlink, you had better not create it as a directory first!
Well the answer was sitting right in front of me the whole time.
In SQL Server Management Studio 2008 there is a Debug button in the toolbar. Set a break point in a query window to step through.
I dismissed this functionality at the beginning because I didn't think of stepping INTO the stored procedure, which you can do with ease.
SSMS basically does what FinnNK mentioned with the MSDN walkthrough but automatically.
So easy! Thanks for your help FinnNK.
Edit: I should add a step in there to find the stored procedure call with parameters I used SQL Profiler on my database.
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
I guess something like this would work:
Add System.ServiceProcess
to your project references (It's on the .NET tab).
using System.ServiceProcess;
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
Edit: There is also a method sc.WaitforStatus()
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first.
Reference: ServiceController object in .NET.
You could also do
SELECT row FROM table ORDER BY id DESC LIMIT 1;
This will sort rows by their ID in descending order and return the first row. This is the same as returning the row with the maximum ID. This of course assumes that id
is unique among all rows. Otherwise there could be multiple rows with the maximum value for id
and you'll only get one.
Hive has a relational database on the master node it uses to keep track of state.
For instance, when you CREATE TABLE FOO(foo string) LOCATION 'hdfs://tmp/';
, this table schema is stored in the database.
If you have a partitioned table, the partitions are stored in the database(this allows hive to use lists of partitions without going to the file-system and finding them, etc). These sorts of things are the 'metadata'.
When you drop an internal table, it drops the data, and it also drops the metadata.
When you drop an external table, it only drops the meta data. That means hive is ignorant of that data now. It does not touch the data itself.
I've continued my research and have not found any reasonable way to do this. The Columns property on the DataGrid isn't something I can bind against, in fact it's read only.
Bryan suggested something might be done with AutoGenerateColumns so I had a look. It uses simple .Net reflection to look at the properties of the objects in ItemsSource and generates a column for each one. Perhaps I could generate a type on the fly with a property for each column but this is getting way off track.
Since this problem is so easily sovled in code I will stick with a simple extension method I call whenever the data context is updated with new columns:
public static void GenerateColumns(this DataGrid dataGrid, IEnumerable<ColumnSchema> columns)
{
dataGrid.Columns.Clear();
int index = 0;
foreach (var column in columns)
{
dataGrid.Columns.Add(new DataGridTextColumn
{
Header = column.Name,
Binding = new Binding(string.Format("[{0}]", index++))
});
}
}
// E.g. myGrid.GenerateColumns(schema);
enter the Command Prompt as Admin and run
rmdir /s <FOLDER>
Adding following in the page header works for me:
<?php
if($i_wanna_reload_the_full_page_on_top == "yes")
{
$reloadneeded = "1";
}
else
{
$reloadneeded = "0";
}
if($reloadneeded > 0)
{
?>
<script type="text/javascript">
top.window.location='indexframes.php';
</script>
<?php
}else{}
?>
First:
Transmitting end:
text.getBytes(encodingName)
)Base64
classReceiving end:
Base64
classnew String(bytes, encodingName)
)So something like:
// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
Or with StandardCharsets
:
// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);
I had the same problem but we can use the time zone we want
we use .toLocaleDateString()
eg:
var day=new Date();
const options= {day:'numeric', month:'long', year:"numeric", timeZone:"Asia/Kolkata"};
const today=day.toLocaleDateString("en-IN", options);
console.log(today);
_x000D_
Here's an alternate approach to the 'round up' part. Not the most brilliantly coded solution but it gets the job done, and this type of syntax is a bit easier to remember (plus would work for alignment values that aren't a power of 2). The uintptr_t
cast was necessary to appease the compiler; pointer arithmetic isn't very fond of division or multiplication.
void *mem = malloc(1024 + 15);
void *ptr = (void*) ((uintptr_t) mem + 15) / 16 * 16;
memset_16aligned(ptr, 0, 1024);
free(mem);
I found out that in my version of git bash "2.24.0.windows.2" in my "home" folder under windows users, there will be a file called ".bash-history" with no file extension in that folder. It's only created after you exit from bash.
Here's my workflow:
If you really want points I guess you could make a batch file to do all this but this is good enough for me. Hope it helps someone.
The character is a backslash \
From the bash manual:
The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation.
You can get the width and height of PDF document like below,
var doc = new jsPDF("p", "mm", "a4");
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();
Then you can use this width and height for your image to fit the entire PDF document.
var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJ......';
doc.addImage(imgData, 'JPEG', 0, 0, width, height);
Make sure that your image has the same size (resolution) of the PDF document. Otherwise it will look distorted (stretched).
If you want convert px
to mm
use this link http://www.endmemo.com/sconvert/millimeterpixel.php
You can do this without a JOIN
:
SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
FROM YourTable
)sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids
Demo: SQL Fiddle
I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..
Opening A Seperate File:
ChDir "[Path here]" 'get into the right folder here
Workbooks.Open Filename:= "[Path here]" 'include the filename in this path
'copy data into current workbook or whatever you want here
ActiveWindow.Close 'closes out the file
Opening A File With Specified Date If It Exists:
I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.
Some common error checking statements:
On Error Resume Next 'if error occurs continues on to the next line (ignores it)
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Or (better option):
if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?
you would most likely want to use the GoTo ErrorHandler
shown below to achieve this
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
ErrorHandler:
'Display error message or any code you want to run on error here
Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm
Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/
Hope this helps!
Example on how to ensure error code doesn't run EVERYtime:
if you debug through the code without the Exit Sub
BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.
Sub Macro
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Exit Sub 'Code will exit BEFORE ErrorHandler if everything goes smoothly
'Otherwise, on error, ErrorHandler will be run
ErrorHandler:
'Display error message or any code you want to run on error here
End Sub
Also, look at this other question in you need more reference to how this works: goto block not working VBA
I think you should have a directory per container with a Dockerfile (no extension) in it. For example:
/db/Dockerfile
/web/Dockerfile
/api/Dockerfile
When you build just use the directory name, Docker will find the Dockerfile. e.g:
docker build -f ./db .
Assuming you want to float the elements, you would also have to float the label
elements too.
Something like this would work:
label {
/* Other styling... */
text-align: right;
clear: both;
float:left;
margin-right:15px;
}
#form {_x000D_
background-color: #FFF;_x000D_
height: 600px;_x000D_
width: 600px;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
margin-top: 0px;_x000D_
border-top-left-radius: 10px;_x000D_
border-top-right-radius: 10px;_x000D_
padding: 0px;_x000D_
text-align:center;_x000D_
}_x000D_
label {_x000D_
font-family: Georgia, "Times New Roman", Times, serif;_x000D_
font-size: 18px;_x000D_
color: #333;_x000D_
height: 20px;_x000D_
width: 200px;_x000D_
margin-top: 10px;_x000D_
margin-left: 10px;_x000D_
text-align: right;_x000D_
clear: both;_x000D_
float:left;_x000D_
margin-right:15px;_x000D_
}_x000D_
input {_x000D_
height: 20px;_x000D_
width: 300px;_x000D_
border: 1px solid #000;_x000D_
margin-top: 10px;_x000D_
float: left;_x000D_
}_x000D_
input[type=button] {_x000D_
float:none;_x000D_
}
_x000D_
<div id="form">_x000D_
<form action="" method="post" name="registration" class="register">_x000D_
<fieldset>_x000D_
<label for="Student">Name:</label>_x000D_
<input name="Student" id="Student" />_x000D_
<label for="Matric_no">Matric number:</label>_x000D_
<input name="Matric_no" id="Matric_no" />_x000D_
<label for="Email">Email:</label>_x000D_
<input name="Email" id="Email" />_x000D_
<label for="Username">Username:</label>_x000D_
<input name="Username" id="Username" />_x000D_
<label for="Password">Password:</label>_x000D_
<input name="Password" id="Password" type="password" />_x000D_
<input name="regbutton" type="button" class="button" value="Register" />_x000D_
</fieldset>_x000D_
</form>_x000D_
</div>
_x000D_
Alternatively, a more common approach would be to wrap the input
/label
elements in groups:
<div class="form-group">
<label for="Student">Name:</label>
<input name="Student" id="Student" />
</div>
#form {_x000D_
background-color: #FFF;_x000D_
height: 600px;_x000D_
width: 600px;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
margin-top: 0px;_x000D_
border-top-left-radius: 10px;_x000D_
border-top-right-radius: 10px;_x000D_
padding: 0px;_x000D_
text-align:center;_x000D_
}_x000D_
label {_x000D_
font-family: Georgia, "Times New Roman", Times, serif;_x000D_
font-size: 18px;_x000D_
color: #333;_x000D_
height: 20px;_x000D_
width: 200px;_x000D_
margin-top: 10px;_x000D_
margin-left: 10px;_x000D_
text-align: right;_x000D_
margin-right:15px;_x000D_
float:left;_x000D_
}_x000D_
input {_x000D_
height: 20px;_x000D_
width: 300px;_x000D_
border: 1px solid #000;_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<div id="form">_x000D_
<form action="" method="post" name="registration" class="register">_x000D_
<fieldset>_x000D_
<div class="form-group">_x000D_
<label for="Student">Name:</label>_x000D_
<input name="Student" id="Student" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Matric_no">Matric number:</label>_x000D_
<input name="Matric_no" id="Matric_no" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Email">Email:</label>_x000D_
<input name="Email" id="Email" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Username">Username:</label>_x000D_
<input name="Username" id="Username" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Password">Password:</label>_x000D_
<input name="Password" id="Password" type="password" />_x000D_
</div>_x000D_
<input name="regbutton" type="button" class="button" value="Register" />_x000D_
</fieldset>_x000D_
</form>_x000D_
</div>
_x000D_
Note that the for
attribute should correspond to the id
of a labelable element, not its name
. This will allow users to click the label
to give focus to the corresponding form element.
A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.
It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)
select
sone_field collate DATABASE_DEFAULT
from
table_1
inner join
table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MaxWidth="200"/>
</Grid.ColumnDefinitions>
<TextBox Background="Azure" Text="Hello" />
</Grid>
Here's a one-liner (imports
don't count :) that can easily be generalized to concatenate N dictionaries:
from itertools import chain
dict(chain.from_iterable(d.items() for d in (d1, d2, d3)))
and:
from itertools import chain
def dict_union(*args):
return dict(chain.from_iterable(d.items() for d in args))
from itertools import chain
dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3))
Output:
>>> from itertools import chain
>>> d1={1:2,3:4}
>>> d2={5:6,7:9}
>>> d3={10:8,13:22}
>>> dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
{1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}
Generalized to concatenate N dicts:
from itertools import chain
def dict_union(*args):
return dict(chain.from_iterable(d.iteritems() for d in args))
I'm a little late to this party, I know, but I hope this helps someone.
For an oneliner, on linux or cygwin, you need to do public key authentication on the host, otherwise ssh will be asking for password.
gunzip -c numbers.sql.gz | ssh user@host mysql --user=user_name --password=your_password db_name
Or do port forwarding and connect to the remote mysql using a "local" connection:
ssh -L some_port:host:local_mysql_port user@host
then do the mysql connection on your local machine to localhost:some_port.
The port forwarding will work from putty too, with the similar -L option or you can configure it from the settings panel, somewhere down on the tree.
From the jQuery documentation - http://api.jquery.com/jQuery.ajax/
contentType When sending data to the server, use this content type.
dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response
"text": A plain text string.
So you want contentType to be application/json
and dataType to be text
:
$.ajax({
type : "POST",
url : /v1/user,
dataType : "text",
contentType: "application/json",
data : dataAttribute,
success : function() {
},
error : function(error) {
}
});
I think that .Net Framework does this automatically but just in case. First, make sure to select what you want to erase, and then call the garbage collector:
randomClass object1 = new randomClass
...
...
// Give a null value to the code you want to delete
object1 = null;
// Then call the garbage collector to erase what you gave the null value
GC.Collect();
I think that's it.. Hope I help someone.
If this need to be done in UIBarButtonItem, additional wrapping in view should be used
This will work
let view = UIView()
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
view.addSubview(button)
view.frame = button.bounds
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)
This won't work
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
Other posters have pointed out how to increase memory and that you could memoize calls. I'd suggest that for many applications, you can use Stirling's formula to approximate large n! very quickly with almost no memory footprint.
Take a gander at this post, which has some analysis of the function and code:
http://threebrothers.org/brendan/blog/stirlings-approximation-formula-clojure/
try to understand the following behavior:
var input = "0014.2";
Regex r1 = new Regex("\\d+.{0,1}\\d+");
Regex r2 = new Regex("\\d*.{0,1}\\d*");
Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // "0014.2"
input = " 0014.2";
Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // " 0014"
input = " 0014.2";
Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // ""
You can use the --system-site-packages
and then "overinstall" the specific stuff for your virtualenv. That way, everything you install into your virtualenv will be taken from there, otherwise it will be taken from your system.
There is no fully compatible alternative in JavaScript as it posses an unsafe security issue to allow client-side code to become aware of the logged in user.
That said, the following code would allow you to get the logged in username, but it will only work on Windows, and only within Internet Explorer, as it makes use of ActiveX. Also Internet Explorer will most likely display a popup alerting you to the potential security problems associated with using this code, which won't exactly help usability.
<!doctype html>
<html>
<head>
<title>Windows Username</title>
</head>
<body>
<script type="text/javascript">
var WinNetwork = new ActiveXObject("WScript.Network");
alert(WinNetwork.UserName);
</script>
</body>
</html>
As Surreal Dreams suggested you could use AJAX to call a server-side method that serves back the username, or render the HTML with a hidden input with a value of the logged in user, for e.g.
(ASP.NET MVC 3 syntax)
<input id="username" type="hidden" value="@User.Identity.Name" />
is there a better syntax?
No. CSS' or
operator (,
) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c
.
Since React 16.8 in 2019 with useState and useEffect Hooks, following are now equivalent (in simple cases):
AngularJS:
$scope.name = 'misko'
$scope.$watch('name', getSearchResults)
<input ng-model="name" />
React:
const [name, setName] = useState('misko')
useEffect(getSearchResults, [name])
<input value={name} onChange={e => setName(e.target.value)} />
Sadly, no.
I agree that such frequent operation should have easier implementation than copying of input line by line in loop, but you'll have to either write helper method or use external library.
or you can try this:
string1 = 'Hello \n World'
tmp = string1.split()
string2 = ' '.join(tmp)
TL;DR: a library
I advise using something like dom-helpers, written by the react team as a regular JS lib.
In their contains implementation you will see a Node#contains based implementation with a Node#compareDocumentPosition fallback.
Support for very old browsers e.g. IE <9 would not be given, which I find acceptable.
This answer incorporates the above ones, however I would advise against looping yourself.
simple add and div atribute to each meta tag example
<meta id="mtlink" name="url" content="">
<meta id="mtdesc" name="description" content="" />
<meta id="mtkwrds" name="keywords" content="" />
now like normal div change for ex. n click
<a href="#" onClick="changeTags(); return false;">Change Meta Tags</a>
function change tags with jQuery
function changeTags(){
$("#mtlink").attr("content","http://albup.com");
$("#mtdesc").attr("content","music all the time");
$("#mtkwrds").attr("content","mp3, download music, ");
}
Also, take a look at FrameLayout
, that's how the Camera's Gallery application implements the Zoom buttons overlay.
Based on this SO question :
grep -rIl "needle text" my_folder
When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”
For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging
In another way,
If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”
There won't be any "merge commit" in fast-forwarding merge.
If you are using a new domain name, and you have done all the above and you are still getting the same error, check to see if you clear the DNS cache on your PC. Clear your DNS for more details.
Windows® 8
To clear your DNS cache if you use Windows 8, perform the following steps:
On your keyboard, press Win+X to open the WinX Menu.
Right-click Command Prompt and select Run as Administrator.
Run the following command:
ipconfig /flushdns
If the command succeeds, the system returns the following message:
Windows IP configuration successfully flushed the DNS Resolver Cache.
Windows® 7
To clear your DNS cache if you use Windows 7, perform the following steps:
Click Start.
Enter cmd in the Start menu search text box.
Right-click Command Prompt and select Run as Administrator.
Run the following command:
ipconfig /flushdns
If the command succeeds, the system returns the following message: Windows IP configuration successfully flushed the DNS Resolver Cache.
FlexPaper is probably still the best viewer out there to be used for this kind of stuff. It has a traditional viewer and a more turn page / flip book style viewer both in flash and html5
It will come in the url so you can get it by two ways. Fist one
<td><?php echo anchor('textarea/delete_row', 'DELETE', 'id="$row->id"'); ?></td>
$id = $this->input->get('id');
2nd one.
$id = $this->uri->segment(3);
But in the second method you have to count the no. of segments in the url that on which no. your id come. 2,3,4 etc. then you have to pass. then in the ();
Hi this is a very simple solution with big O(n)
L = [1, 4, 7, 5, 5, 4, 5]
def mode_f(L):
# your code here
counter = 0
number = L[0]
for i in L:
amount_times = L.count(i)
if amount_times > counter:
counter = amount_times
number = i
return number
Where number the element in the list that repeats most of the time
This line should randomly change the color for you:
setInterval(function(){y.style.color=''+"rgb(1"+Math.floor(Math.random() * 100)+",1"+Math.floor(Math.random() * 100)+",1"+Math.floor(Math.random() * 100)+")"+'';},1000);
You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:
function PersonListCtrl($scope, $http) {
$scope.loadData = function () {
$http.get('/persons').success(function(data) {
$scope.persons = data;
});
};
//initial load
$scope.loadData();
}
then in your markup
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="loadData()">Refresh</button>
</div>
As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:
for example (just puedo code) in your controller:
$scope.addPerson = function() {
$scope.persons.push({ name: 'Test Monkey' });
};
Then you could use that in your view or whatever you'd want to do.
It's several years later, and the Edge browser now uses Chromium as its rendering engine.
Checking for IE 11 is still a thing, sadly.
Here is a more straightforward approach, as ancient versions of IE should be gone.
if (window.document.documentMode) {
// Do IE stuff
}
Here is my old answer (2014):
In Edge the User Agent String has changed.
/**
* detect IEEdge
* returns version of IE/Edge or false, if browser is not a Microsoft browser
*/
function detectIEEdge() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser
return false;
}
Sample usage:
alert('IEEdge ' + detectIEEdge());
Default string of IE 10:
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)
Default string of IE 11:
Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
Default string of Edge 12:
Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0
Default string of Edge 13 (thx @DrCord):
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586
Default string of Edge 14:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/14.14300
Default string of Edge 15:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063
Default string of Edge 16:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299
Default string of Edge 17:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134
Default string of Edge 18 (Insider preview):
Mozilla/5.0 (Windows NT 10.0; Win64; x64; ServiceUI 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17730
Test at CodePen:
I use Nodemon version 1.88.3 in my Node.js project. To install Nodemon, see in https://www.npmjs.com/package/nodemon.
Check your package.json, see if "scripts" has changed like this:
"scripts": {
"dev": "nodemon server.js"
},
server.js
is my file name, you can use another name for this file like app.js
.
After that, run this on your terminal: npm run dev
While LIKE
is suitable for this case, a more general purpose solution is to use instr
, which doesn't require characters in the search string to be escaped. Note: instr
is available starting from Sqlite 3.7.15.
SELECT *
FROM TABLE
WHERE instr(column, 'cats') > 0;
Also, keep in mind that LIKE
is case-insensitive, whereas instr
is case-sensitive.
Setting the execution policy is environment-specific. If you are trying to execute a script from the running x86 ISE you have to use the x86 PowerShell to set the execution policy. Likewise, if you are running the 64-bit ISE you have to set the policy with the 64-bit PowerShell.
>>> import numpy
>>> print numpy.power.__doc__
power(x1, x2[, out])
First array elements raised to powers from second array, element-wise.
Raise each base in `x1` to the positionally-corresponding power in
`x2`. `x1` and `x2` must be broadcastable to the same shape.
Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
Examples
--------
Cube each element in a list.
>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([ 0, 1, 8, 27, 64, 125])
Raise the bases to different exponents.
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([ 0., 1., 8., 27., 16., 5.])
The effect of broadcasting.
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0, 1, 8, 27, 16, 5],
[ 0, 1, 8, 27, 16, 5]])
>>>
As per the discussed observation on numerical precision as per @GarethRees objection in comments:
>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> a.dtype
dtype('float96')
>>> a[0,0]
0.46002700024131926
>>> b[0,0]
0.21162484095102677
>>> print b[0,0]
0.211624840951
>>> print a[0,0]
0.460027000241
>>> c = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )
>>> import zmq
>>> aClk = zmq.Stopwatch()
>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L) # 5 663 [usec]
>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L) # 6 395 [usec]
>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L) # 6 930 [usec]
>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L) # 6 285 [usec]
>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L) # 384 515 [usec]
Use tabs, they work when inputting file paths in vim escape mode!
user8657661's answer is closest to my needs (of lining things up across several lines). However, I couldn't get the example code to work as provided, but I needed to change it as follows:
<html>
<head>
<style>
.tab9 {position:absolute;left:150px; }
</style>
</head>
<body>
Dog Food: <span class="tab9"> $30</span><br/>
Milk of Magnesia:<span class="tab9"> $30</span><br/>
Pizza Kit:<span class="tab9"> $5</span><br/>
Mt Dew <span class="tab9"> $1.75</span><br/>
</body>
</html>
If you need right-aligned numbers you can change left:150px
to right:150px
, but you'll need to alter the number based on the width of the screen (as written the numbers would be 150 pixels from the right edge of the screen).
You can do this in single filter step:
requiredCars = cars.stream().filter(c -> c.getName() != null && c.getName().startsWith("M"));
If you don't want to call getName()
several times (for example, it's expensive call), you can do this:
requiredCars = cars.stream().filter(c -> {
String name = c.getName();
return name != null && name.startsWith("M");
});
Or in more sophisticated way:
requiredCars = cars.stream().filter(c ->
Optional.ofNullable(c.getName()).filter(name -> name.startsWith("M")).isPresent());
On the ASP.NET page, inside the form tags.
Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014
Just be sure to be using correct instance and connect each other
Just pay attention in Stored procs must be recompiled
If our CustomTableSeeder is in same directory with DatabaseSeeder we should use like below:
$this->call('database\seeds\CustomTableSeeder');
in our DatabaseSeeder File; then another error will be thrown that says: 'DB Class not found' then we should add our DB facade to our CustomTableSeeder File like below:
use Illuminate\Support\Facades\DB;
it worked for me!
I combined it, and this is the results -
$(document).ready(function() {
$("#toTop").hide();
// fade in & out
$(window).scroll(function () {
if ($(this).scrollTop() > 400) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
$('a[href*=#]').each(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
if ($target) {
var targetOffset = $target.offset().top;
$(this).click(function() {
$('html, body').animate({scrollTop: targetOffset}, 400);
return false;
});
}
}
});
});
I tested it and it works fine. hope this will help someone :)
I experienced the same error when configuring the WP-Mail-SMTP
plugin in Wordpress.
The problem would persist even when I have 'triple checked' the settings and login credentials, and am able to log in manually using a browser.
There's a list of steps you can take to fix this.
Display Unlock Captcha
page to give your app or website permission to sign in to Gmail. Click Continue
or follow the instructions.del /s /q c:\where ever the file is\*
rmdir /s /q c:\where ever the file is\
mkdir c:\where ever the file is\
stoi is available "since C++11". Make sure your compiler is up to date.
You can try atoi(hours0.c_str()) instead.
ES6 String Template
Here is a simple way if you don't need IE/EDGE support
$(`input[id=${x}]`).hide();
or
$(`input[id=${$(this).attr("name")}]`).hide();
This is a es6 feature called template string
(function($) {_x000D_
$("input[type=button]").click(function() {_x000D_
var x = $(this).attr("name");_x000D_
$(`input[id=${x}]`).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" name="bx" value="1" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" name="by" value="2" />_x000D_
_x000D_
_x000D_
String Concatenation
If you need IE/EDGE support use
$("#" + $(this).attr("name")).hide();
(function($) {_x000D_
$("input[type=button]").click(function() {_x000D_
$("#" + $(this).attr("name")).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" name="bx" value="1" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" name="by" value="2" />_x000D_
_x000D_
_x000D_
Selector in DOM as data attribute
This is my preferred way as it makes you code really DRY
// HTML
<input type="text" id="bx" />
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick"/>
//JS
$($(this).data("input-sel")).hide();
(function($) {_x000D_
$(".js-hide-onclick").click(function() {_x000D_
$($(this).data("input-sel")).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" data-input-sel="#by" value="2" class="js-hide-onclick" />_x000D_
_x000D_
_x000D_
When using WebAPI, you should just return the Object rather than specifically returning Json, as the API will either return JSON or XML depending on the request.
I am not sure why your WebAPI is returning an ActionResult, but I would change the code to something like;
public IEnumerable<ListItems> GetAllNotificationSettings()
{
var result = new List<ListItems>();
// Filling the list with data here...
// Then I return the list
return result;
}
This will result in JSON if you are calling it from some AJAX code.
P.S
WebAPI is supposed to be RESTful, so your Controller should be called ListItemController
and your Method should just be called Get
. But that is for another day.
<section class="min-vh-100 d-flex align-items-center justify-content-center py-3">
<div class="container">
<div class="row justify-content-between align-items-center">
x
x
x
</div>
</div>
</section>
_x000D_
Pass float to sleep, like sleep 0.1
You can use setTableId((short)100)
. I think this was changed in Java 5 so that numeric literals assigned to byte or short and within range for the target are automatically assumed to be the target type. That latest J2ME JVMs are derived from Java 4 though.
The article "Why is my list black? An Android optimization" in the Android Developers Blog has a thorough explanation of why the list background turns black when scrolling. Simple answer: set cacheColorHint on your list to transparent (#00000000).
You're missing service name:
SQL> connect username/password@hostname:port/SERVICENAME
EDIT
If you can connect to the database from other computer try running there:
select sys_context('USERENV','SERVICE_NAME') from dual
and
select sys_context('USERENV','SID') from dual
Chrome will never implement support RTSP streaming.
At least, in the words of a Chromium developer here:
we're never going to add support for this
string input = "super exemple of string key : text I want to keep - end of my string";
var match = Regex.Match(input, @"key : (.+?)-").Groups[1].Value;
or with just string operations
var start = input.IndexOf("key : ") + 6;
var match2 = input.Substring(start, input.IndexOf("-") - start);
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])
#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)
#legend
cbar = plt.colorbar(heatmap)
cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()
#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()
You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.
The formula for German Excel:
=KLEIN(
VERKETTEN(
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;8));8);"-";
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;4));4);"-";"4";
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;3));3);"-";
DEZINHEX(ZUFALLSBEREICH(8;11));
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;3));3);"-";
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;8));8);
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;4));
)
)
I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.
The main benefit of "".equals(s)
is you don't need the null check (equals
will check its argument and return false
if it's null), which you seem to not care about. If you're not worried about s
being null (or are otherwise checking for it), I would definitely use s.isEmpty()
; it shows exactly what you're checking, you care whether or not s
is empty, not whether it equals the empty string
~/Library/Developer/Xcode/DerivedData
I'm experiencing some problems using apply() instead commit(). As stated before in other responses, the apply() is asynchronous. I'm getting the problem that the changes formed to a "string set" preference are never written to the persistent memory.
It happens if you "force detention" of the program or, in the ROM that I have installed on my device with Android 4.1, when the process is killed by the system due to memory necessities.
I recommend to use "commit()" instead "apply()" if you want your preferences alive.
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
If using async & await and desire to use a time out without blocking, then an alternative and simpler approach from the answer provide by mcandal is to execute the connect on a background thread and await the result. For example:
Task<bool> t = Task.Run(() => client.ConnectAsync(ipAddr, port).Wait(1000));
await t;
if (!t.Result)
{
Console.WriteLine("Connect timed out");
return; // Set/return an error code or throw here.
}
// Successful Connection - if we get to here.
See the Task.Wait MSDN article for more info and other examples.
To show line numbers in the current window, go to Options
and click Show Line Numbers
.
To show them automatically, go to Options
> Configure IDLE
> General
and check the Show line numbers in new windows
box.
Unfortunately there is not an option to display line numbers in IDLE although there is an enhancement request open for this.
However, there are a couple of ways to work around this:
Under the edit menu there is a go to line option (there is a default shortcut of Alt+G for this).
There is a display at the bottom right which tells you your current line number / position on the line:
My reason was very foolish. I had dropped the manage.py onto the terminal so it was running using the full path. And I had changed the name of the folder of the project. So now, the program was unable to find the file with the previous data and hence the error.
Make sure you restart the software in such cases.
There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:
for (int i = 0; i < letters.size(); i++) {
letters.set(i, "D");
}
At the end the whole list will have the letter "D"
as its content. It's not a good idea to use an enhanced for
loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.
Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:
A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification
You need to add a reference inside the window tag. Something like:
xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
(When you add xmlns:controls=" intellisense should kick in to make this bit easier)
Then you can add the control with:
<controls:CustomControlClassName ..... />
Knowing how to write a preset dictionary is useful to know as well:
cmap = {'US':'USA','GB':'Great Britain'}
# Explicitly:
# -----------
def cxlate(country):
try:
ret = cmap[country]
except KeyError:
ret = '?'
return ret
present = 'US' # this one is in the dict
missing = 'RU' # this one is not
print cxlate(present) # == USA
print cxlate(missing) # == ?
# or, much more simply as suggested below:
print cmap.get(present,'?') # == USA
print cmap.get(missing,'?') # == ?
# with country codes, you might prefer to return the original on failure:
print cmap.get(present,present) # == USA
print cmap.get(missing,missing) # == RU
A packet is a general term for a formatted unit of data carried by a network. It is not necessarily connected to a specific OSI model layer.
For example, in the Ethernet protocol on the physical layer (layer 1), the unit of data is called an "Ethernet packet", which has an Ethernet frame (layer 2) as its payload. But the unit of data of the Network layer (layer 3) is also called a "packet".
A frame is also a unit of data transmission. In computer networking the term is only used in the context of the Data link layer (layer 2).
Another semantical difference between packet and frame is that a frame envelops your payload with a header and a trailer, just like a painting in a frame, while a packet usually only has a header.
But in the end they mean roughly the same thing and the distinction is used to avoid confusion and repetition when talking about the different layers.
Dean Toader Just excellent! I'd modify your code a little, to show all constraints in the table and to make possible to use regexp mask in table name.
CREATE OR REPLACE FUNCTION public.generate_create_table_statement(p_table_name character varying)
RETURNS SETOF text AS
$BODY$
DECLARE
v_table_ddl text;
column_record record;
table_rec record;
constraint_rec record;
firstrec boolean;
BEGIN
FOR table_rec IN
SELECT c.relname FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE relkind = 'r'
AND relname~ ('^('||p_table_name||')$')
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY c.relname
LOOP
FOR column_record IN
SELECT
b.nspname as schema_name,
b.relname as table_name,
a.attname as column_name,
pg_catalog.format_type(a.atttypid, a.atttypmod) as column_type,
CASE WHEN
(SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
FROM pg_catalog.pg_attrdef d
WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) IS NOT NULL THEN
'DEFAULT '|| (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
FROM pg_catalog.pg_attrdef d
WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)
ELSE
''
END as column_default_value,
CASE WHEN a.attnotnull = true THEN
'NOT NULL'
ELSE
'NULL'
END as column_not_null,
a.attnum as attnum,
e.max_attnum as max_attnum
FROM
pg_catalog.pg_attribute a
INNER JOIN
(SELECT c.oid,
n.nspname,
c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname = table_rec.relname
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 2, 3) b
ON a.attrelid = b.oid
INNER JOIN
(SELECT
a.attrelid,
max(a.attnum) as max_attnum
FROM pg_catalog.pg_attribute a
WHERE a.attnum > 0
AND NOT a.attisdropped
GROUP BY a.attrelid) e
ON a.attrelid=e.attrelid
WHERE a.attnum > 0
AND NOT a.attisdropped
ORDER BY a.attnum
LOOP
IF column_record.attnum = 1 THEN
v_table_ddl:='CREATE TABLE '||column_record.schema_name||'.'||column_record.table_name||' (';
ELSE
v_table_ddl:=v_table_ddl||',';
END IF;
IF column_record.attnum <= column_record.max_attnum THEN
v_table_ddl:=v_table_ddl||chr(10)||
' '||column_record.column_name||' '||column_record.column_type||' '||column_record.column_default_value||' '||column_record.column_not_null;
END IF;
END LOOP;
firstrec := TRUE;
FOR constraint_rec IN
SELECT conname, pg_get_constraintdef(c.oid) as constrainddef
FROM pg_constraint c
WHERE conrelid=(
SELECT attrelid FROM pg_attribute
WHERE attrelid = (
SELECT oid FROM pg_class WHERE relname = table_rec.relname
) AND attname='tableoid'
)
LOOP
v_table_ddl:=v_table_ddl||','||chr(10);
v_table_ddl:=v_table_ddl||'CONSTRAINT '||constraint_rec.conname;
v_table_ddl:=v_table_ddl||chr(10)||' '||constraint_rec.constrainddef;
firstrec := FALSE;
END LOOP;
v_table_ddl:=v_table_ddl||');';
RETURN NEXT v_table_ddl;
END LOOP;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION public.generate_create_table_statement(character varying)
OWNER TO postgres;
Now you can, for example, make the following query
SELECT * FROM generate_create_table_statement('.*');
which results like this:
CREATE TABLE public.answer (
id integer DEFAULT nextval('answer_id_seq'::regclass) NOT NULL,
questionid integer NOT NULL,
title character varying NOT NULL,
defaultvalue character varying NULL,
valuetype integer NOT NULL,
isdefault boolean NULL,
minval double precision NULL,
maxval double precision NULL,
followminmax integer DEFAULT 0 NOT NULL,
CONSTRAINT answer_pkey
PRIMARY KEY (id),
CONSTRAINT answer_questionid_fkey
FOREIGN KEY (questionid) REFERENCES question(id) ON UPDATE RESTRICT ON DELETE RESTRICT,
CONSTRAINT answer_valuetype_fkey
FOREIGN KEY (valuetype) REFERENCES answervaluetype(id) ON UPDATE RESTRICT ON DELETE RESTRICT);
for each user table.