DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
if (dr["Column_Name"] == DBNull.Value)
{
//Do something
}
else
{
//Do something
}
}
Just to add some additional information. In IE 11, using merely
window.open()
causes
window.document
to be undefined. To resolve this, use
window.open( null, '_blank' )
This will also work correctly in Chrome, Firefox and Safari.
I don't have enough reputation to comment, so had to create an answer.
It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to 4.0.0.0. The new in-process side-by-side feature should not change this.
My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.
Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.
Using implode()
, you can turn the array into a string.
$str = implode(',', $array); // 33160,33280,33180,...
The solution I've come up with is:
isinstance(y, (np.ndarray, np.generic) )
However, it's not 100% clear that all numpy types are guaranteed to be either np.ndarray
or np.generic
, and this probably isn't version robust.
This is a very round-about way of doing it but if you want to make a histogram where you already know the bin values but dont have the source data, you can use the np.random.randint
function to generate the correct number of values within the range of each bin for the hist function to graph, for example:
import numpy as np
import matplotlib.pyplot as plt
data = [np.random.randint(0, 9, *desired y value*), np.random.randint(10, 19, *desired y value*), etc..]
plt.hist(data, histtype='stepfilled', bins=[0, 10, etc..])
as for labels you can align x ticks with bins to get something like this:
#The following will align labels to the center of each bar with bin intervals of 10
plt.xticks([5, 15, etc.. ], ['Label 1', 'Label 2', etc.. ])
You can keep note of below possibilities:
null
.However with multiple null
keys and values it will only take a null key value pair once.
Map<String, String> codes = new HashMap<String, String>();
codes.put(null, null);
codes.put(null,null);
codes.put("C1", "Acathan");
for(String key:codes.keySet()){
System.out.println(key);
System.out.println(codes.get(key));
}
output will be :
null //key of the 1st entry
null //value of 1st entry
C1
Acathan
null
only onceoptions.put(null, null);
Person person = sample.searchPerson(null);
It depends on the implementation of your searchPerson
method
if you want multiple values to be null
, you can implement accordingly
Map<String, String> codes = new HashMap<String, String>();
codes.put(null, null);
codes.put("X1",null);
codes.put("C1", "Acathan");
codes.put("S1",null);
for(String key:codes.keySet()){
System.out.println(key);
System.out.println(codes.get(key));
}
output:
null
null
X1
null
S1
null
C1
Acathan
setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").
From the command line, you can type
python setup.py --help
...to get a list of commands. What you are looking to do is...
python setup.py install
There should be no semicolon here:
class WordGame;
...but there should be one at the end of your class definition:
...
private:
string theWord;
}; // <-- Semicolon should be at the end of your class definition
Wanted to add numexpr into the mix:
import numpy as np
import numexpr as ne
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
# array([3, 4, 5], dtype=int64)
Would only make sense for larger arrays with millions... or if you hitting a memory limits.
Solved by setting a password for the user first.
In terminal
sudo -u <username> psql
ALTER USER <username> PASSWORD 'SetPassword';
# ALTER ROLE
\q
In pgAdmin
**Connection**
Host name/address: 127.0.0.1
Port: 5432
Maintenance database: postgres
username: postgres
password: XXXXXX
You should check logs If you see like below "stacktrace": ["java.lang.IllegalStateException: Received message from unsupported version: [6.4.3] minimal compatible version is: [6.8.0]"
You can check this link https://discuss.elastic.co/t/java-client-or-spring-boot-for-elasticsearch-7-3-1/199778 You have to explicit declare es version.
The correct config key is retention.ms
$ bin/kafka-topics.sh --zookeeper zk.prod.yoursite.com --alter --topic as-access --config retention.ms=86400000
Updated config for topic "my-topic".
Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve
How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).
The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:
EXPORTS main=_main
Borland compilers add an underscore to function names, and this exports the main()
function the way a VST host expects it. For more information about .def files, see the C++Builder help files.
This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:
In the constructor of your effect class, write
_control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
That should do the trick.
Here are some more useful sites:
http://www.steinberg.net/en/company/developer.html
how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial
Switch to the branch from which you created the pull request:
$ git checkout pull-request-branch
Overwrite the modified file(s) with the file in another branch, let's consider it's master:
git checkout origin/master -- src/main/java/HelloWorld.java
Commit and push it to the remote:
git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch
Here's the version like the ggplot2 one I gave only in base R. I copied some from @nullglob.
generate the data
carrots <- rnorm(100000,5,2)
cukes <- rnorm(50000,7,2.5)
You don't need to put it into a data frame like with ggplot2. The drawback of this method is that you have to write out a lot more of the details of the plot. The advantage is that you have control over more details of the plot.
## calculate the density - don't plot yet
densCarrot <- density(carrots)
densCuke <- density(cukes)
## calculate the range of the graph
xlim <- range(densCuke$x,densCarrot$x)
ylim <- range(0,densCuke$y, densCarrot$y)
#pick the colours
carrotCol <- rgb(1,0,0,0.2)
cukeCol <- rgb(0,0,1,0.2)
## plot the carrots and set up most of the plot parameters
plot(densCarrot, xlim = xlim, ylim = ylim, xlab = 'Lengths',
main = 'Distribution of carrots and cucumbers',
panel.first = grid())
#put our density plots in
polygon(densCarrot, density = -1, col = carrotCol)
polygon(densCuke, density = -1, col = cukeCol)
## add a legend in the corner
legend('topleft',c('Carrots','Cucumbers'),
fill = c(carrotCol, cukeCol), bty = 'n',
border = NA)
Most likely, the userdata()
function is returning an object, not a string. Look into the documentation (or var_dump the return value) to find out which value you need to use.
I found this https://typescriptbcl.codeplex.com/SourceControl/latest
here is the Guid version they have in case the link does not work later.
module System {
export class Guid {
constructor (public guid: string) {
this._guid = guid;
}
private _guid: string;
public ToString(): string {
return this.guid;
}
// Static member
static MakeNew(): Guid {
var result: string;
var i: string;
var j: number;
result = "";
for (j = 0; j < 32; j++) {
if (j == 8 || j == 12 || j == 16 || j == 20)
result = result + '-';
i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
result = result + i;
}
return new Guid(result);
}
}
}
Good Example can be when incase of writing it after the end of your query if you have joins or where close :
select 'idPago','fecha','lead','idAlumno','idTipoPago','idGpo'
union all
(select id_control_pagos, fecha, lead, id_alumno, id_concepto_pago, id_Gpo,id_Taller,
id_docente, Pagoimporte, NoFactura, FacturaImporte, Mensualidad_No, FormaPago,
Observaciones from control_pagos
into outfile 'c:\\data.csv'
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n');
Original answer:
I too tried to change the support library to "23". When I changed the targetSdkVersion
to 23, Android Studio reported the following error:
This support library should not use a lower version (22) than the
targetSdkVersion
(23)
I simply changed:
compile 'com.android.support:appcompat-v7:23.0.0'
to
compile 'com.android.support:appcompat-v7:+'
Although this fixed my issue, you should not use dynamic versions. After a few hours the new support repository was available and it is currently 23.0.1
.
Pro tip:
You can use double quotes and create a ${supportLibVersion}
variable for simplicity. Example:
ext {
supportLibVersion = '23.1.1'
}
compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:palette-v7:${supportLibVersion}"
compile "com.android.support:customtabs:${supportLibVersion}"
compile "com.android.support:gridlayout-v7:${supportLibVersion}"
source: https://twitter.com/manidesto/status/669195097947377664
It is basically a header file that also includes every standard library and STL include file. The only purpose I can see for it would be for testing and education.
Se e.g. GCC 4.8.0 /bits/stdc++.h source.
Using it would include a lot of unnecessary stuff and increases compilation time.
Edit: As Neil says, it's an implementation for precompiled headers. If you set it up for precompilation correctly it could, in fact, speed up compilation time depending on your project. (https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html)
I would, however, suggest that you take time to learn about each of the sl/stl headers and include them separately instead, and not use "super headers" except for precompilation purposes.
Put your class name on the mat-form-field element. This works for all inputs.
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
You can simply run
$(document).keyup(function(e) {
console.log(e.keyCode);
});
to see the codes of pressed keys in the browser console.
Or you can find key codes here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#Numpad_keys
To be clear: The option "Value for Edit Top Rows command" has nothing to do with the fact if a result set is editable or not. It is just a way to limit the result set.
Editing the result set of a query based on one and only one table is obviously always possible.
The result set of a query based on more than one table is under following condition possible: You can edit the fields in the result set at once if they belong to one and only one based table in the query! If the fields are Primary Key, then you have to fulfill refresh/"Execute SQL" (Ctrl+R) after each row update, in order to be able to edit a row next time. If the fields are not Primary Key, then you do not need to fulfill refresh/"Execute SQL" (Ctrl+R).
I have tested it on SQL Server 2008 - 2016!
This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!
randomFill()
to the current location of the array.Note: Your array is double
, but you are returning int
s from randomFill
. So there's something you need to fix there.
If you use the Oracle native data provider rather than the Microsoft driver then you can get at all field types
Dim cn As New Oracle.DataAccess.Client.OracleConnection
Dim cm As New Oracle.DataAccess.Client.OracleCommand
Dim dr As Oracle.DataAccess.Client.OracleDataReader
The connection string does not require a Provider value so you would use something like:
"Data Source=myOracle;UserID=Me;Password=secret"
Open the connection:
cn.ConnectionString = "Data Source=myOracle;UserID=Me;Password=secret"
cn.Open()
Attach the command and set the Sql statement
cm.Connection = cn
cm.CommandText = strCommand
Set the Fetch size. I use 4000 because it's as big as a varchar can be
cm.InitialLONGFetchSize = 4000
Start the reader and loop through the records/columns
dr = cm.ExecuteReader
Do while dr.read()
strMyLongString = dr(i)
Loop
You can be more specific with the read, eg dr.GetOracleString(i) dr.GetOracleClob(i) etc. if you first identify the data type in the column. If you're reading a LONG datatype then the simple dr(i)
or dr.GetOracleString(i)
works fine. The key is to ensure that the InitialLONGFetchSize is big enough for the datatype. Note also that the native driver does not support CommandBehavior.SequentialAccess
for the data reader but you don't need it and also, the LONG field does not even have to be the last field in the select statement.
i got result from this in LibreOffice Calc :
=DATE(1970,1,1)+Column_id_here/60/60/24
Something like this:
JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(songs.get(key));
}
Follow these steps to create CSR (Code Signing Identity):
On your Mac, go to the folder 'Applications' ? 'Utilities' and open 'Keychain Access.'
Go to 'Keychain Access' ? Certificate Assistant ? Request a Certificate from a Certificate Authority. ?
Fill out the information in the Certificate Information window as specified below and click "Continue."
• In the User Email Address field, enter the email address to identify with this certificate
• In the Common Name field, enter your name
• In the Request group, click the "Saved to disk" option
?
Save the file to your hard drive.
Use this CSR (.certSigningRequest) file to create project/application certificates and profiles, in Apple developer account.
Simple & Best way:
onclick="parentNode.remove()"
Deletes the complete parent from html
Why not use @media-queries? These are designed for that exact purpose. You can also do this with jQuery, but that's a last resort in my book.
var s = document.createElement("script");
//Check if viewport is smaller than 768 pixels
if(window.innerWidth < 768) {
s.type = "text/javascript";
s.src = "http://www.example.com/public/assets/css1";
}else { //Else we have a larger screen
s.type = "text/javascript";
s.src = "http://www.example.com/public/assets/css2";
}
$(function(){
$("head").append(s); //Inject stylesheet
})
Sometimes when I get stuck on this I hard code a path to project in the wsgi file like:
import os
import sys
sys.path.append("/var/www/html/myproject")
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
application = get_wsgi_application()
Probably the mymobileNO.titleLabel.text value doesn't include the scheme tel://
Your code should look like this:
NSString *phoneNumber = [@"tel://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
While the built-in libs for XML parsing are quite good I am partial to lxml.
But for parsing RSS feeds, I'd recommend Universal Feed Parser, which can also parse Atom. Its main advantage is that it can digest even most malformed feeds.
Python 2.6 already includes a JSON parser, but a newer version with improved speed is available as simplejson.
With these tools building your app shouldn't be that difficult.
The following simplified code, based on the accepted answer above, worked for me:
public class GetSync {
public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
private static final TimeZone utc = TimeZone.getTimeZone("UTC");
private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
static {
isoFormatter.setTimeZone(utc);
}
public static String now() {
return isoFormatter.format(new Date()).toString();
}
}
I hope this helps somebody.
If you just want to change the legend title, you can do the following:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.lmplot(
x="total_bill",
y="tip",
hue="smoker",
data=tips,
legend=True
)
g._legend.set_title("New Title")
I would do it this way:
import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <database>" % (argv[0],))
return 1
if not os.path.exists(argv[1]):
sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
This allows main()
to be imported into other modules if desired, and simplifies debugging because you can choose what argv
should be.
First, give all your links a unique id and make a css class called active:
<ul>
<li><a id="link1" href="#/...">link 1</a></li>
<li><a id="link2" href="#/...">link 2</a></li>
</ul>
CSS:
.active {
font-weight: bold;
}
Jquery version:
function setActiveLink(setActive){
if ($("a").hasClass('active'))
$("a").removeClass('active');
if (setActive)
$("#"+setActive).addClass('active');
}
$(function() {
$("a").click(function() {
setActiveLink(this.id);
});
});
Vanilla javascript version:
In order to prevent selecting too many links with document.querySelectorAll
, give the parent element an id called menuLinks. Add an onClick handler on the links.
<ul id="menuLinks">
<li><a id="link1" href="#/..." onClick="setActiveLink(this.id);">link 1</a></li>
<li><a id="link2" href="#/..." onClick="setActiveLink(this.id);">link 2</a></li>
</ul>
Code:
function setActiveLink(setActive){
var links = document.querySelectorAll("#menuLinks a");
Array.prototype.map.call(links, function(e) {
e.className = "";
if (e.id == setActive)
e.className = "active";
})
}
Another option is to ensure the file is not open anywhere else on your machine.
I would like to add to Justin and Power's answer that -
repartition
will ignore existing partitions and create new ones. So you can use it to fix data skew. You can mention partition keys to define the distribution. Data skew is one of the biggest problems in the 'big data' problem space.
coalesce
will work with existing partitions and shuffle a subset of them. It can't fix the data skew as much as repartition
does. Therefore even if it is less expensive it might not be the thing you need.
There is already a library in Python called yahoo_finance so you'll need to download the library first using the following command line:
sudo pip install yahoo_finance
Then once you've installed the yahoo_finance library, here's a sample code that will download the data you need from Yahoo Finance:
#!/usr/bin/python
import yahoo_finance
import pandas as pd
symbol = yahoo_finance.Share("GOOG")
google_data = symbol.get_historical("1999-01-01", "2016-06-30")
google_df = pd.DataFrame(google_data)
# Output data into CSV
google_df.to_csv("/home/username/google_stock_data.csv")
This should do it. Let me know if it works.
UPDATE: The yahoo_finance library is no longer supported.
I had the exact same error (on windows 7) and the cause was different. I solved it in a different way so I thought I'd add the cause and solution here for others.
Even though the error seemed to point to heroku really the error was saying "Heroku can't get to the git repository"
. I swore I had the same keys on all the servers because I created it and uploaded it to one after the other at the same time.
After spending almost a day on this I realized that because git was only showing me the fingerprint and not the actual key. I couldn't verify that it's key matched the one on my HD or heroku. I looked in the known hosts file and guess what... it shows the keys for each server and I was able to clearly see that the git and heroku public keys did not match.
1) I deleted all the files in my key folder, the key from github using their website, and the key from heroku using git bash and the command heroku keys:clear
2) Followed github's instructions here to generate a new key pair and upload the public key to git
3) using git bash-
heroku keys:add
to upload the same key to heroku.
Now git push heroku master
works.
what a nightmare, hope this helped somebody.
Bryan
Just loop...
foreach(var table in DataSet1.Tables) {
foreach(var col in table.Columns) {
...
}
foreach(var row in table.Rows) {
object[] values = row.ItemArray;
...
}
}
Very easy, trial and error. Go to the cell you want the month in. Type the Month, go to the next cell and type the year, something weird will come up but then go to your number section click on the little arrow in the right bottom and highlight text and it will change to the year you originally typed
Try
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();
_x000D_
If you want to download binary data look here
2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here
From all I have read you cannot do exactly what you want without javascript. If you float left before text
<div style="float:left;">widget</div> here is some CONTENT, etc.
Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content
here is some CONTENT, etc. <div style="float:left;">widget</div>
Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:
here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>
In your question you are using bootstrap which just adds row-fluid::after { content: ""}
which resolves the border/background issue.
Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/
<div class="container-fluid">
<div class="row-fluid">
<div class="offset1 span8 pull-right">
... Widget 1...
</div>
.... a lot of content ....
<div class="span8" style="margin-left: 0;">
... Widget 2...
</div>
</div>
</div><!--/.fluid-container-->
I'm currently working on such a statement and figured out another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement. For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (constraints allow it) or fail.
In visual studio 2017 we can change the port number from LaunchSetting.json
In Properties-> LaunchSettings.json.
Open LaunchSettings.json and change the Port Number.
Change the port Number in json file
check this Twig Reference.
You can do it that simple:
{% if (a or b) %}
...
{% endif %}
# coding: utf-8
from __future__ import unicode_literals
import base64
import os
import six
from Crypto import Random
from Crypto.PublicKey import RSA
class PublicKeyFileExists(Exception): pass
class RSAEncryption(object):
PRIVATE_KEY_FILE_PATH = None
PUBLIC_KEY_FILE_PATH = None
def encrypt(self, message):
public_key = self._get_public_key()
public_key_object = RSA.importKey(public_key)
random_phrase = 'M'
encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
# use base64 for save encrypted_message in database without problems with encoding
return base64.b64encode(encrypted_message)
def decrypt(self, encoded_encrypted_message):
encrypted_message = base64.b64decode(encoded_encrypted_message)
private_key = self._get_private_key()
private_key_object = RSA.importKey(private_key)
decrypted_message = private_key_object.decrypt(encrypted_message)
return six.text_type(decrypted_message, encoding='utf8')
def generate_keys(self):
"""Be careful rewrite your keys"""
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
private, public = key.exportKey(), key.publickey().exportKey()
if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
raise PublicKeyFileExists('???? ? ????????? ?????? ??????????. ??????? ????')
self.create_directories()
with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
private_file.write(private)
with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
public_file.write(public)
return private, public
def create_directories(self, for_private_key=True):
public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
if not os.path.exists(public_key_path):
os.makedirs(public_key_path)
if for_private_key:
private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
if not os.path.exists(private_key_path):
os.makedirs(private_key_path)
def _get_public_key(self):
"""run generate_keys() before get keys """
with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
return _file.read()
def _get_private_key(self):
"""run generate_keys() before get keys """
with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
return _file.read()
def _to_format_for_encrypt(value):
if isinstance(value, int):
return six.binary_type(value)
for str_type in six.string_types:
if isinstance(value, str_type):
return value.encode('utf8')
if isinstance(value, six.binary_type):
return value
And use
KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS
class TestingEncryption(RSAEncryption):
PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'
# django/flask
from django.core.files import File
class ProductionEncryption(RSAEncryption):
PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'
def _get_private_key(self):
"""run generate_keys() before get keys """
from corportal.utils import global_elements
private_key = global_elements.request.FILES.get('private_key')
if private_key:
private_key_file = File(private_key)
return private_key_file.read()
message = 'Hello ??? friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)
I use Windows Explorer, navigate to C:\Windows\assembly , find the one I need. From the Properties you can copy the PublicKeyToken.
This doesn't rely on Visual Studio or any other utilities being installed.
Is it possible to add onclick to a div and have it occur if any area of the div is clicked.
Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work
If yes then why is the onclick method not going through to my div.
You are assigning a string where a function is expected.
divTag.onclick = printWorking;
There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.
That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener
Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.
And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.
Final Solution for this problem is below :
First make changes in applicationHost config file. replace below string setProfileEnvironment="false" TO setProfileEnvironment="true"
In your database connection string add below attribute : Integrated Security = SSPI
I asked myself the same questions when we came to implement Subversion here -- about 20 developers spread across 4 - 6 projects. I didn't find any one good source with ''the answer''. Here are some parts of how our answer has developed over the last 3 years:
-- commit as often as is useful; our rule of thumb is commit whenever you have done sufficient work that it would be a problem having to re-do it if the modifications got lost; sometimes I commit every 15 minutes or so, other times it might be days (yes, sometimes it takes me a day to write 1 line of code)
-- we use branches, as one of your earlier answers suggested, for different development paths; right now for one of our programs we have 3 active branches: 1 for the main development, 1 for the as-yet-unfinished effort to parallelise the program, and 1 for the effort to revise it to use XML input and output files;
-- we scarcely use tags, though we think we ought to use them to identify releases to production;
Think of development proceeding along a single path. At some time or state of development marketing decide to release the first version of the product, so you plant a flag in the path labelled '1' (or '1.0' or what have you). At some other time some bright spark decides to parallelise the program, but decides that that will take weeks and that people want to keep going down the main path in the meantime. So you build a fork in the path and different people wander off down the different forks.
The flags in the road are called 'tags' ,and the forks in the road are where 'branches' divide. Occasionally, also, branches come back together.
-- we put all material necessary to build an executable (or system) into the repository; That means at least source code and make file (or project files for Visual Studio). But when we have icons and config files and all that other stuff, that goes into the repository. Some documentation finds its way into the repo; certainly any documentation such as help files which might be integral to the program does, and it's a useful place to put developer documentation.
We even put Windows executables for our production releases in there, to provide a single location for people looking for software -- our Linux releases go to a server so don't need to be stored.
-- we don't require that the repository at all times be capable of delivering a latest version which builds and executes; some projects work that way, some don't; the decision rests with the project manager and depends on many factors but I think it breaks down when making major changes to a program.
If anyone is strugling with the same problem I solved it by adding @EntityScan
in my main class. Just add your model package to the basePackages property.
This guy created a class to get line-height (without using CoreText, as MTLabel library) : https://github.com/LemonCake/MSLabel
It works fine for me: http://jsfiddle.net/qwertynl/htb9h/
My javascript:
var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
$scope.telephone = []; // << remember to set this
}]);
You might need to build an inverted index for your database. It is assured to be pretty fast.
You can change configuration file schema back to DotNetConfig.xsd
via properties of the app.config
file. To find destination of needed schema, you can search it by name or create a WinForms application, add to project the configuration file and in it's properties, you'll find full path to file.
Git 1.7.0 has “sparse checkouts”. See “core.sparseCheckout” in the git config manpage, “Sparse checkout” in the git read-tree manpage, and “Skip-worktree bit” in the git update-index manpage.
The interface is not as convenient as SVN’s (e.g. there is no way to make a sparse checkout at the time of an initial clone), but the base functionality upon which simpler interfaces could be built is now available.
Convert JavaScript object to json data
$("form").submit(function(event){
event.preventDefault();
var formData = $("form").serializeArray(); // Create array of object
var jsonConvertedData = JSON.stringify(formData); // Convert to json
consol.log(jsonConvertedData);
});
You can validate json data using http://jsonlint.com
You don't have any error in either of your queries. My guess is the following:
You aren't building your formula right.
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = "=SUM(H5:H" & var1a & ")"
This does the same as the following lines do:
Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"
which is what you are trying to do.
Also, you want to have the =
at the beginning of the formala.
This solved my problem once in Windows:
subst X: "C:\Program files\MySQL\MySQL Server 5.5"
gem install mysql2 -v 0.x.x --platform=ruby -- --with-mysql-dir=X: --with-mysql-lib=X:\lib\opt
subst X: /D
This one seems to imply that 030 and 031 are up and down triangles.
(As bobince pointed out, this doesn't seem to be an ASCII standard)
S3 now expects the rules to be in Array Json format.
You can find this in s3 bucket -> Permissions then -> scroll below -> () Cross-origin resource sharing (CORS)
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"HEAD"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 3000
}
]
When you want to ignore warnings only in functions you can do the following.
import warnings
from functools import wraps
def ignore_warnings(f):
@wraps(f)
def inner(*args, **kwargs):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("ignore")
response = f(*args, **kwargs)
return response
return inner
@ignore_warnings
def foo(arg1, arg2):
...
write your code here without warnings
...
@ignore_warnings
def foo2(arg1, arg2, arg3):
...
write your code here without warnings
...
Just add the @ignore_warnings decorator on the function you want to ignore all warnings
Another occurrence of a NullPointerException
occurs when one declares an object array, then immediately tries to dereference elements inside of it.
String[] phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
This particular NPE can be avoided if the comparison order is reversed; namely, use .equals
on a guaranteed non-null object.
All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null
.
You must initialize the elements in the array before accessing or dereferencing them.
String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
Exec can be messy on windows. There is a more "nodie" solution. Fundamentally, you have a recursive call to see if a directory exists and dive into the child (if it does exist) or create it. Here is a function that will create the children and call a function when finished:
fs = require('fs');
makedirs = function(path, func) {
var pth = path.replace(/['\\]+/g, '/');
var els = pth.split('/');
var all = "";
(function insertOne() {
var el = els.splice(0, 1)[0];
if (!fs.existsSync(all + el)) {
fs.mkdirSync(all + el);
}
all += el + "/";
if (els.length == 0) {
func();
} else {
insertOne();
}
})();
}
You need to install the APK on the emulator. You can do this with the adb
command line tool that is included in the Android SDK.
adb -e install -r yourapp.apk
Once you've done that you should be able to run the app.
The -e
and -r
flags might not be necessary. They just specify that you are using an emulator (if you also have a device connected) and that you want to replace the app if it already exists.
Maybe you can try this
var str = "'SELECT___100E___7',24";
var res = str.split(',').pop();
Use your jquery like this
$('.home').css({'background-image':'url(images/tabs3.png)'});
If I may expand on user987361's answer:
From the offline access portion of the OAuth2.0 docs:
When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the
approval_prompt
parameter in the authorization code request, and set the value toforce
.
So, when you have already granted access, subsequent requests for a grant_type
of authorization_code
will not return the refresh_token
, even if access_type
was set to offline
in the query string of the consent page.
As stated in the quote above, in order to obtain a new refresh_token
after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt
to force
.
Cheers,
PS This change was announced in a blog post as well.
You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
(Original Code from: http://www.w3schools.com/html/html_forms.asp)
So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)
Slightly modified version of Sebastian's answer using find
instead of du
(to exclude file-size-related overhead that du
has to perform and that is never used):
find ./ -mindepth 2 -type f | cut -d/ -f2 | sort | uniq -c | sort -nr
-mindepth 2
parameter is used to exclude files in current directory. If you remove it, you'll see a bunch of lines like the following:
234 dir1
123 dir2
1 file1
1 file2
1 file3
...
1 fileN
(much like the du
-based variant does)
If you do need to count the files in current directory as well, use this enhanced version:
{ find ./ -mindepth 2 -type f | cut -d/ -f2 | sort && find ./ -maxdepth 1 -type f | cut -d/ -f1; } | uniq -c | sort -nr
The output will be like the following:
234 dir1
123 dir2
42 .
Deleting the package-lock.json did it for me. I'd suggest you not push package-lock.json to your repo as I wasted hours trying to npm install with the package-lock.json in the folder which gave me helluva errors.
with open('file.txt', 'r') as searchfile:
for line in searchfile:
if 'searchphrase' in line:
print line
With apologies to senderle who I blatantly copied.
You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo
#one
{
background-color: #EEE;
margin: 62px 258px;
padding: 5px;
width: 200px;
position: relative;
}
#two
{
background-color: #F00;
display: inline-block;
height: 30px;
position: absolute;
width: 100px;
top:10px;
}?
For Each is much faster than for I=1 to X, for some reason. Just try to go through the same dictionary,
once with for each Dkey in dDict,
and once with for Dkey = lbound(dDict.keys) to ubound(dDict.keys)
=>You will notice a huge difference, even though you are going through the same construct.
For no particular reason, arrays cannot be assigned to one another. Use std::copy
instead:
#include <algorithm>
// ...
int a[8] = {2, 3, 5, 7, 11, 13, 17, 19};
int b[8];
std::copy(a + 0, a + 8, b);
This is more flexible than what true array assignment could provide because it is possible to copy slices of larger arrays into smaller arrays.
std::copy
is usually specialized for primitive types to give maximum performance. It is unlikely that std::memcpy
performs better. If in doubt, measure.
Although you cannot assign arrays directly, you can assign structs and classes which contain array members. That is because array members are copied memberwise by the assignment operator which is provided as a default by the compiler. If you define the assignment operator manually for your own struct or class types, you must fall back to manual copying for the array members.
Arrays cannot be passed by value. You can either pass them by pointer or by reference.
Since arrays themselves cannot be passed by value, usually a pointer to their first element is passed by value instead. This is often called "pass by pointer". Since the size of the array is not retrievable via that pointer, you have to pass a second parameter indicating the size of the array (the classic C solution) or a second pointer pointing after the last element of the array (the C++ iterator solution):
#include <numeric>
#include <cstddef>
int sum(const int* p, std::size_t n)
{
return std::accumulate(p, p + n, 0);
}
int sum(const int* p, const int* q)
{
return std::accumulate(p, q, 0);
}
As a syntactic alternative, you can also declare parameters as T p[]
, and it means the exact same thing as T* p
in the context of parameter lists only:
int sum(const int p[], std::size_t n)
{
return std::accumulate(p, p + n, 0);
}
You can think of the compiler as rewriting T p[]
to T *p
in the context of parameter lists only. This special rule is partly responsible for the whole confusion about arrays and pointers. In every other context, declaring something as an array or as a pointer makes a huge difference.
Unfortunately, you can also provide a size in an array parameter which is silently ignored by the compiler. That is, the following three signatures are exactly equivalent, as indicated by the compiler errors:
int sum(const int* p, std::size_t n)
// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[], std::size_t n)
// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[8], std::size_t n) // the 8 has no meaning here
Arrays can also be passed by reference:
int sum(const int (&a)[8])
{
return std::accumulate(a + 0, a + 8, 0);
}
In this case, the array size is significant. Since writing a function that only accepts arrays of exactly 8 elements is of little use, programmers usually write such functions as templates:
template <std::size_t n>
int sum(const int (&a)[n])
{
return std::accumulate(a + 0, a + n, 0);
}
Note that you can only call such a function template with an actual array of integers, not with a pointer to an integer. The size of the array is automatically inferred, and for every size n
, a different function is instantiated from the template. You can also write quite useful function templates that abstract from both the element type and from the size.
It is configured to use localhost:25
for the mail server.
The error message says that it can't connect to localhost:25
.
Therefore you have two options:
Got a solution to above problem in a different way where in although i would read entire csv file, but would tweek the display part to show only the content which is desired.
import pandas as pd
df = pd.read_csv('data.csv', skipinitialspace=True)
print df[['star_name', 'ra']]
This one could help in some of the scenario's in learning basics and filtering data on the basis of columns in dataframe.
Below are a few extra steps on a fresh Mac that some people might need. This adds a little to @jnovack's excellent answer.
Update: A few other notes when setting this up:
Make sure your admin user has a password. A blank password won't work when trying to enable a root user.
System Preferences > Users and Groups > (select user) > Change password
Then to enable root, run dsenableroot
in a terminal:
$ dsenableroot
username = mac_admin_user
user password:
root password:
verify root password:
dsenableroot:: ***Successfully enabled root user.
Type in the admin user's password, then the new enabled root password twice.
Next type:
sudo gcc
or
sudo make
It will respond with something like the following:
WARNING: Improper use of the sudo command could lead to data loss
or the deletion of important system files. Please double-check your
typing when using sudo. Type "man sudo" for more information.
To proceed, enter your password, or type Ctrl-C to abort.
Password:
You have not agreed to the Xcode license agreements. You must agree to
both license agreements below in order to use Xcode.
Press enter when it prompts to show you the license agreement.
Hit the Enter key to view the license agreements at
'/Applications/Xcode.app/Contents/Resources/English.lproj/License.rtf'
IMPORTANT: BY USING THIS SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE
FOLLOWING APPLE TERMS:
//...
Press q
to exit the license agreement view.
By typing 'agree' you are agreeing to the terms of the software license
agreements. Type 'print' to print them or anything else to cancel,
[agree, print, cancel]
Type agree
. And then it will end with:
clang: error: no input files
Which basically means that you didn't give make
or gcc
any input files.
Here is what the check looked like:
$ xcode-select -p
/Applications/Xcode.app/Contents/Developer
With Mavericks, it is a little different now.
When the tools were NOT found, this is what the command pkgutil
command returned:
$ pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
To install the command line tools, this works nicely from the Terminal, with a nice gui and everything.
$ xcode-select --install
http://macops.ca/installing-command-line-tools-automatically-on-mavericks/
When they were found, this is what the pkgutil
command returned:
$ pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
package-id: com.apple.pkg.CLTools_Executables
version: 5.0.1.0.1.1382131676
volume: /
location: /
install-time: 1384149984
groups: com.apple.FindSystemFiles.pkg-group com.apple.DevToolsBoth.pkg-group com.apple.DevToolsNonRelocatableShared.pkg-group
This command returned the same before and after the install.
$ pkgutil --pkg-info=com.apple.pkg.DeveloperToolsCLI
No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.
Also I had the component for the CLT selected and installed in xcode's downloads section before, but it seems like it didn't make it to the terminal...
Hope that helps.
Given a staging table with 70 columns and only 4 representing duplicates, this code will return the offending columns:
SELECT
COUNT(*)
,LTRIM(RTRIM(S.TransactionDate))
,LTRIM(RTRIM(S.TransactionTime))
,LTRIM(RTRIM(S.TransactionTicketNumber))
,LTRIM(RTRIM(GrossCost))
FROM Staging.dbo.Stage S
GROUP BY
LTRIM(RTRIM(S.TransactionDate))
,LTRIM(RTRIM(S.TransactionTime))
,LTRIM(RTRIM(S.TransactionTicketNumber))
,LTRIM(RTRIM(GrossCost))
HAVING COUNT(*) > 1
.
You can use
$now = new DateTime();
$date = $now->modify('+1 day')->format('Y-m-d H:i:s');
I use a css class like so to target the modal-dialog class:
.app-modal-window .modal-dialog {
width: 500px;
}
Then in the controller calling the modal window, set the windowClass:
$scope.modalButtonClick = function () {
var modalInstance = $modal.open({
templateUrl: 'App/Views/modalView.html',
controller: 'modalController',
windowClass: 'app-modal-window'
});
modalInstance.result.then(
//close
function (result) {
var a = result;
},
//dismiss
function (result) {
var a = result;
});
};
Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.
You've got a couple of choices;
Calling the intent to add an event on the calendar
This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=DAILY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
Or the more complicated one:
Get a reference to the calendar with this method
(It is highly recommended not to use this method, because it could break on newer Android versions):
private String getCalendarUriBase(Activity act) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
and add an event and a reminder this way:
// get calendar
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
ContentResolver cr = getContentResolver();
// event insert
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", "Reminder Title");
values.put("allDay", 0);
values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
values.put("description", "Reminder description");
values.put("visibility", 0);
values.put("hasAlarm", 1);
Uri event = cr.insert(EVENTS_URI, values);
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
values.put( "method", 1 );
values.put( "minutes", 10 );
cr.insert( REMINDERS_URI, values );
You'll also need to add these permissions to your manifest for this method:
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
Update: ICS Issues
The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.
More infos about this can be found at this blog post.
You can compile with either Cygwin's g++
or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll
(and others) PATH to the system Windows PATH, before any cygwin style paths.
Thus add: ;C:\cygwin64\bin
to the end of your Windows system PATH
variable.
Also, to compile for use in CMD or PowerShell, you may need to use:
x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe
(This invokes the cross-compiler, if installed.)
Are you sure you want to use __getattribute__
? What are you actually trying to achieve?
The easiest way to do what you ask is:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
test = 0
or:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
@property
def test(self):
return 0
Edit:
Note that an instance of D
would have different values of test
in each case. In the first case d.test
would be 20, in the second it would be 0. I'll leave it to you to work out why.
Edit2:
Greg pointed out that example 2 will fail because the property is read only and the __init__
method tried to set it to 20. A more complete example for that would be:
class D(object):
def __init__(self):
self.test = 20
self.test2 = 21
_test = 0
def get_test(self):
return self._test
def set_test(self, value):
self._test = value
test = property(get_test, set_test)
Obviously, as a class this is almost entirely useless, but it gives you an idea to move on from.
I believe I have a valid use case for using typeid(), the same way it is valid to use sizeof(). For a template function, I need to special case the code based on the template variable, so that I offer maximum functionality and flexibility.
It is much more compact and maintainable than using polymorphism, to create one instance of the function for each type supported. Even in that case I might use this trick to write the body of the function only once:
Note that because the code uses templates, the switch statement below should resolve statically into only one code block, optimizing away all the false cases, AFAIK.
Consider this example, where we may need to handle a conversion if T is one type vs another. I use it for class specialization to access hardware where the hardware will use either myClassA or myClassB type. On a mismatch, I need to spend time converting the data.
switch ((typeid(T)) {
case typeid(myClassA):
// handle that case
break;
case typeid(myClassB):
// handle that case
break;
case typeid(uint32_t):
// handle that case
break;
default:
// handle that case
}
ColumnNames
is a property of type List<String>
so when you are setting up you need to pass a List<String>
in the Returns
call as an argument (or a func which return a List<String>
)
But with this line you are trying to return just a string
input.SetupGet(x => x.ColumnNames).Returns(temp[0]);
which is causing the exception.
Change it to return whole list:
input.SetupGet(x => x.ColumnNames).Returns(temp);
JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.
It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:
[bits 32]
.
.
and [ebp-4], 0
@Singleton
@AccessTimeout(value=120000)
public class StatusSingletonBean {
private String status;
@Lock(LockType.WRITE)
public void setStatus(String new Status) {
status = newStatus;
}
@Lock(LockType.WRITE)
@AccessTimeout(value=360000)
public void doTediousOperation {
//...
}
}
//The following singleton has a default access timeout value of 60 seconds, specified //using the TimeUnit.SECONDS constant:
@Singleton
@AccessTimeout(value=60, timeUnit=SECONDS)
public class StatusSingletonBean {
//...
}
//The Java EE 6 Tutorial
//https://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html
If you uninstalled then re-installed, and running 'python' in CLI, make sure to open a new CMD after your installation for 'python' to be recognized. 'py' will probably be recognized with an old CLI because its not tied to any version.
Try this to Change content of div using jQuery.
See more @ Change content of div using jQuery
$(document).ready(function(){
$("#Textarea").keyup(function(){
// Getting the current value of textarea
var currentText = $(this).val();
// Setting the Div content
$(".output").text(currentText);
});
});
Unfortunately, this cannot be done efficiently (better than O(n)) in any of the Standard Library set containers.
This is odd, since it is very easy to add a randomized pick function to hash sets as well as binary sets. In a not to sparse hash set, you can try random entries, until you get a hit. For a binary tree, you can choose randomly between the left or right subtree, with a maximum of O(log2) steps. I've implemented a demo of the later below:
import random
class Node:
def __init__(self, object):
self.object = object
self.value = hash(object)
self.size = 1
self.a = self.b = None
class RandomSet:
def __init__(self):
self.top = None
def add(self, object):
""" Add any hashable object to the set.
Notice: In this simple implementation you shouldn't add two
identical items. """
new = Node(object)
if not self.top: self.top = new
else: self._recursiveAdd(self.top, new)
def _recursiveAdd(self, top, new):
top.size += 1
if new.value < top.value:
if not top.a: top.a = new
else: self._recursiveAdd(top.a, new)
else:
if not top.b: top.b = new
else: self._recursiveAdd(top.b, new)
def pickRandom(self):
""" Pick a random item in O(log2) time.
Does a maximum of O(log2) calls to random as well. """
return self._recursivePickRandom(self.top)
def _recursivePickRandom(self, top):
r = random.randrange(top.size)
if r == 0: return top.object
elif top.a and r <= top.a.size: return self._recursivePickRandom(top.a)
return self._recursivePickRandom(top.b)
if __name__ == '__main__':
s = RandomSet()
for i in [5,3,7,1,4,6,9,2,8,0]:
s.add(i)
dists = [0]*10
for i in xrange(10000):
dists[s.pickRandom()] += 1
print dists
I got [995, 975, 971, 995, 1057, 1004, 966, 1052, 984, 1001] as output, so the distribution seams good.
I've struggled with the same problem for myself, and I haven't yet decided weather the performance gain of this more efficient pick is worth the overhead of using a python based collection. I could of course refine it and translate it to C, but that is too much work for me today :)
If you are working with heavy queries, you better move the request for the latest row in the where clause. It is a lot faster and looks cleaner.
SELECT c.*,
FROM client AS c
LEFT JOIN client_calling_history AS cch ON cch.client_id = c.client_id
WHERE
cch.cchid = (
SELECT MAX(cchid)
FROM client_calling_history
WHERE client_id = c.client_id AND cal_event_id = c.cal_event_id
)
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block
The correct php way is to use parse_url()
http://php.net/manual/en/function.parse-url.php
(from php manual)
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.
Use next
:
(1..10).each do |a|
next if a.even?
puts a
end
prints:
1
3
5
7
9
For additional coolness check out also redo
and retry
.
Works also for friends like times
, upto
, downto
, each_with_index
, select
, map
and other iterators (and more generally blocks).
For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.
import java.io.IOException;
class Super {
protected Super getClassName(Super s) throws IOException {
System.out.println(this.getClass().getSimpleName() + " - I'm parent");
return null;
}
}
class SubOne extends Super {
@Override
protected Super getClassName(Super s) {
System.out.println(this.getClass().getSimpleName() + " - I'm Perfect Overriding");
return null;
}
}
class SubTwo extends Super {
@Override
protected Super getClassName(Super s) throws NullPointerException {
System.out.println(this.getClass().getSimpleName() + " - I'm Overriding and Throwing Runtime Exception");
return null;
}
}
class SubThree extends Super {
@Override
protected SubThree getClassName(Super s) {
System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and Returning SubClass Type");
return null;
}
}
class SubFour extends Super {
@Override
protected Super getClassName(Super s) throws IOException {
System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and Throwing Narrower Exception ");
return null;
}
}
class SubFive extends Super {
@Override
public Super getClassName(Super s) {
System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and have broader Access ");
return null;
}
}
class SubSix extends Super {
public Super getClassName(Super s, String ol) {
System.out.println(this.getClass().getSimpleName()+ " - I'm Perfect Overloading ");
return null;
}
}
class SubSeven extends Super {
public Super getClassName(SubSeven s) {
System.out.println(this.getClass().getSimpleName()+ " - I'm Perfect Overloading because Method signature (Argument) changed.");
return null;
}
}
public class Test{
public static void main(String[] args) throws Exception {
System.out.println("Overriding\n");
Super s1 = new SubOne(); s1.getClassName(null);
Super s2 = new SubTwo(); s2.getClassName(null);
Super s3 = new SubThree(); s3.getClassName(null);
Super s4 = new SubFour(); s4.getClassName(null);
Super s5 = new SubFive(); s5.getClassName(null);
System.out.println("Overloading\n");
SubSix s6 = new SubSix(); s6.getClassName(null, null);
s6 = new SubSix(); s6.getClassName(null);
SubSeven s7 = new SubSeven(); s7.getClassName(s7);
s7 = new SubSeven(); s7.getClassName(new Super());
}
}
The Major Difference between a Service
and an IntentService
is described as follows:
Service :
1.A Service
by default, runs on the application's main thread.(here no default worker thread is available).So the user needs to create a separate thread and do the required work in that thread.
2.Allows Multiple requests at a time.(Multi Threading)
IntentService :
1.Now, coming to IntentService
, here a default worker thread is available to perform any operation. Note that - You need to implement onHandleIntent()
method ,which receives the intent for each start request, where you can do the background work.
2.But it allows only one request at a time.
For Windows 10 it is:
Control Panel > User Accounts > Manage your Credentials > Windows Credentials, search for the git credentials and edit
This is the way it worked for me:
$.post("/Controller/Action", $("#form").serialize(), function(json) {
// handle response
}, "json");
[HttpPost]
public ActionResult TV(MyModel id)
{
return Json(new { success = true });
}
I suppose that you want to show your enum values to the user, therefore, you want them to have some friendly name.
Here's my suggestion:
Use an enum type pattern. Although it takes some effort to implement, it is really worth it.
public class MyEnum
{
public static readonly MyEnum Enum1=new MyEnum("This will work",1);
public static readonly MyEnum Enum2=new MyEnum("This.will.work.either",2);
public static readonly MyEnum[] All=new []{Enum1,Enum2};
private MyEnum(string name,int value)
{
Name=name;
Value=value;
}
public string Name{get;set;}
public int Value{get;set;}
public override string ToString()
{
return Name;
}
}
file * | grep directory
Output (on my machine) --
[root@rhel6 ~]# file * | grep directory
mongo-example-master: directory
nostarch: directory
scriptzz: directory
splunk: directory
testdir: directory
The above output can be refined more by using cut:
file * | grep directory | cut -d':' -f1
mongo-example-master
nostarch
scriptzz
splunk
testdir
* could be replaced with any path that's permitted
file - determine file type
grep - searches for string named directory
-d - to specify a field delimiter
-f1 - denotes field 1
<?php
$string = "1,2,3";
$ids = explode(',', $string );
array_walk( $ids, function ( &$id )
{
$id = (int) $id;
});
var_dump( $ids );
Can be done like this -
frontend http-in
bind *:80
mode http
redirect scheme https code 301
Any traffic hitting http will redirect to https
As pointed out by other answers, in python they return floats probably because of historical reasons to prevent overflow problems. However, they return integers in python 3.
>>> import math
>>> type(math.floor(3.1))
<class 'int'>
>>> type(math.ceil(3.1))
<class 'int'>
You can find more information in PEP 3141.
Well, You can do it like this.
https://developer.android.com/reference/android/view/View#post(java.lang.Runnable)
A simple approach
currentTime.post(new Runnable(){
@Override
public void run() {
currentTime.setText(time);
}
}
it also provides delay
https://developer.android.com/reference/android/view/View#postDelayed(java.lang.Runnable,%20long)
Actually… there is! Sort of. box-shadow
defaults to color
, just like border
does.
According to http://dev.w3.org/.../#the-box-shadow
The color is the color of the shadow. If the color is absent, the used color is taken from the ‘color’ property.
In practice, you have to change the color
property and leave box-shadow
without a color:
box-shadow: 1px 2px 3px;
color: #a00;
box-shadow
at all) div {_x000D_
box-shadow: 0 0 50px;_x000D_
transition: 0.3s color;_x000D_
}_x000D_
.green {_x000D_
color: green;_x000D_
}_x000D_
.red {_x000D_
color: red;_x000D_
}_x000D_
div:hover {_x000D_
color: yellow;_x000D_
}_x000D_
_x000D_
/*demo style*/_x000D_
body {_x000D_
text-align: center;_x000D_
}_x000D_
div {_x000D_
display: inline-block;_x000D_
background: white;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
margin: 30px;_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<div class="green"></div>_x000D_
<div class="red"></div>
_x000D_
The bug mentioned in the comment below has since been fixed :)
Eek, don't do anything that complicated : )
Just filter()
your tags. bool()
returns False
for empty strings, so instead of
new_tag_list = f1.striplist(tag_string.split(",") + selected_tags)
you should write
new_tag_list = filter(bool, f1.striplist(tag_string.split(",") + selected_tags))
or better yet, put this logic inside striplist()
so that it doesn't return empty strings in the first place.
For SQL Server use exec sp_help
USE db_name;
exec sp_help 'dbo.table_name'
For MySQL, use describe
DESCRIBE table_name;
Yes, it is sufficient. The way injection type attacks work, is by somehow getting an interpreter (The database) to evaluate something, that should have been data, as if it was code. This is only possible if you mix code and data in the same medium (Eg. when you construct a query as a string).
Parameterised queries work by sending the code and the data separately, so it would never be possible to find a hole in that.
You can still be vulnerable to other injection-type attacks though. For example, if you use the data in a HTML-page, you could be subject to XSS type attacks.
This is not a new question. I addresed it in comments in one SO post, and posted my alternative implementations in another post. The comments in the first post actually elucidate the performance differences between the different implementations.
Basically, which works fastest depends on what database object you use with it.
You have to use absolute path in this case. But if you set the CopyToOutputDirectory = CopyAlways
, it will work as you are doing it.
in my fish shell
function gsap
git stash list | grep ": $argv" | tr -dc '0-9' | xargs git stash apply
end
use
gsap name_of_stash
I resolved this by deleting the contents of the bin and obj folders for the project, and the contents of the bin folder on the remote server, then redeploying.
Here's a generalizable base R function:
pad_left <- function(x, len = 1 + max(nchar(x)), char = '0'){
unlist(lapply(x, function(x) {
paste0(
paste(rep(char, len - nchar(x)), collapse = ''),
x
)
}))
}
pad_left(1:100)
I like sprintf
but it comes with caveats like:
however the actual implementation will follow the C99 standard and fine details (especially the behaviour under user error) may depend on the platform
I made custom messagebox using jquery UI
component. Here is demo http://jsfiddle.net/eraj2587/Pm5Fr/14/
You have to pass just the parameters like caption name, message, button's text. You can specify trigger function on any button click. This will helpful for you.
You are trying to run bash
, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d
, but you can do this by adding -it
to the command line, which ensures that the container has a valid tty associated with it and that stdin
remains connected:
docker run -it -d -p 52022:22 basickarl/docker-git-test
You would more commonly run some sort of long-lived non-interactive process (like sshd
, or a web server, or a database server, or a process manager like systemd
or supervisor
) when starting detached containers.
If you are trying to run a service like sshd
, you cannot simply run service ssh start
. This will -- depending on the distribution you're running inside your container -- do one of two things:
It will try to contact a process manager like systemd
or upstart
to start the service. Because there is no service manager running, this will fail.
It will actually start sshd
, but it will be started in the background. This means that (a) the service sshd start
command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.
If you want to run just ssh in a container, consider an example like this.
If you want to run sshd
and other processes inside the container, you will need to investigate some sort of process supervisor.
The prompt command will echo text to the output:
prompt A useful comment.
select(*) from TableA;
Will be displayed as:
SQL> A useful comment.
SQL>
COUNT(*)
----------
0
std::iterator
with random_access_iterator_tag
.These base classes define all type definitions required by STL and do other work.To avoid code duplication iterator class should be a template class and be parametrized by "value type", "pointer type", "reference type" or all of them (depends on implementation). For example:
// iterator class is parametrized by pointer type
template <typename PointerType> class MyIterator {
// iterator class definition goes here
};
typedef MyIterator<int*> iterator_type;
typedef MyIterator<const int*> const_iterator_type;
Notice iterator_type
and const_iterator_type
type definitions: they are types for your non-const and const iterators.
See Also: standard library reference
EDIT: std::iterator
is deprecated since C++17. See a relating discussion here.
You should not use the viewport meta tag at all if your design is not responsive. Misusing this tag may lead to broken layouts. You may read this article for documentation about why you should'n use this tag unless you know what you're doing. http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho
"user-scalable=no" also helps to prevent the zoom-in effect on iOS input boxes.
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
Move your javascript into a function and then bind that function to window resize.
$(document).ready(function () {
updateContainer();
$(window).resize(function() {
updateContainer();
});
});
function updateContainer() {
var $containerHeight = $(window).height();
if ($containerHeight <= 818) {
$('.footer').css({
position: 'static',
bottom: 'auto',
left: 'auto'
});
}
if ($containerHeight > 819) {
$('.footer').css({
position: 'absolute',
bottom: '3px',
left: '0px'
});
}
}
Use os.chdir
. Here's a full example:
https://colab.research.google.com/notebook#fileId=1CSPBdmY0TxU038aKscL8YJ3ELgCiGGju
Compactly:
!mkdir abc
!echo "file" > abc/123.txt
import os
os.chdir('abc')
# Now the directory 'abc' is the current working directory.
# and will show 123.txt.
!ls
In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.
It turned out to be the anti forgery token.
$.ajax({
url: "/Cart/AddProduct/",
data: {
__RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
productId: $(this).data("productcode")
},
The problem was that the .Net controller wasn't set up correctly.
I needed to add the attributes to the controller:
[AllowAnonymous]
[IgnoreAntiforgeryToken]
[DisableCors]
[HttpPost]
public async Task<JsonResult> AddProduct(int productId)
{
The code needs review but for now at least I know what was causing it. 400 error not helpful at all.
Here's how I do it:
Code:
let fs = require('fs');
let path = require('path');
let myController = (req, res) => {
let filename = 'myFile.ext';
let absPath = path.join(__dirname, '/my_files/', filename);
let relPath = path.join('./my_files', filename); // path relative to server root
fs.writeFile(relPath, 'File content', (err) => {
if (err) {
console.log(err);
}
res.download(absPath, (err) => {
if (err) {
console.log(err);
}
fs.unlink(relPath, (err) => {
if (err) {
console.log(err);
}
console.log('FILE [' + filename + '] REMOVED!');
});
});
});
};
CHECK YOUR PROJECT PATH. It should have no irregular character like comma and space
for example this is incorrect path: d:\my applications\Project1
and this is true path d:\my_applications\Project1
The visual studio cannot build the project when there is a non alphabetic and numeric character in its path in disk and it show no message for this fault!
Also some installation tools have same problem when they start installation and can not be extracted.
This worked for me in IE 9 and AngularJS v1.0.7:
<a href="javascript:void(0)" ng-click="logout()">Logout</a>
Thanks to duckeggs' comment for the working solution!
Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:
All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.
This restriction accomplishes four functions, 1st and 3rd are important in this particular case:
And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.
One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.
There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:
If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.
Hope this will helps you to find the proper solution!
This example is a Sum for Date time and Time Zone(String Values)
String DateVal = "2015-03-26 12:00:00";
String TimeVal = "02:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
Date reslt = sdf.parse( DateVal );
Date timeZ = sdf2.parse( TimeVal );
//Increase Date Time
reslt.setHours( reslt.getHours() + timeZ.getHours());
reslt.setMinutes( reslt.getMinutes() + timeZ.getMinutes());
reslt.setSeconds( reslt.getSeconds() + timeZ.getSeconds());
System.printLn.out( sdf.format(reslt) );//Result(+2 Hours): 2015-03-26 14:00:00
Thanks :)
List<Map<String, Object>> List = getJdbcTemplate().queryForList(SELECT_ALL_CONVERSATIONS_SQL_FULL, new Object[] {userId, dateFrom, dateTo});
for (Map<String, Object> rowMap : resultList) {
DTO dTO = new DTO();
dTO.setrarchyID((Long) (rowMap.get("ID")));
}
Asset.objects.filter( project__name__contains="Foo" )
You may also want to look at rsync if you're doing a lot of files.
If you're going to making a lot of changes and want to keep your directories and files in sync, you may want to use a version control system like Subversion or Git. See http://xoa.petdance.com/How_to:_Keep_your_home_directory_in_Subversion
It looks like your error is coming from the outer index.js file, not this one. Are you importing this one as './app/containers'
? because it should just be './containers'
.
Short answer is: No, it's not possible to prevent CSS inheritance. You can only override the styles that are set on the parents. See the spec:
Every element in an HTML document will inherit all inheritable properties from its parent except the root element (
html
), which doesn’t have a parent. -W3C
Apart from overriding every single inherited property. You can also use initial
keyword, e.g. color: initial;
. It also can be used together with all
, e.g. all: initial;
, that will reset all properties at once. Example:
.container {_x000D_
color: blue;_x000D_
font-style: italic;_x000D_
}_x000D_
.initial {_x000D_
all: initial;_x000D_
}
_x000D_
<div class="container">_x000D_
The quick brown <span class="initial">fox</span> jumps over the lazy dog_x000D_
</div>
_x000D_
Browser support tables according to Can I use...
all
(Currently no support in both IE and Edge, others are good)initial
(Currently no support in IE, others are good)You may find it useful by using direct children selector >
in some cases. Example:
.list > li {_x000D_
border: 1px solid red;_x000D_
color: blue;_x000D_
}
_x000D_
<ul class="list">_x000D_
<li>_x000D_
<span>HEADING 1</span>_x000D_
<ul>_x000D_
<li>sub-heading A</li>_x000D_
<li>sub-heading B</li>_x000D_
</ul>_x000D_
</li>_x000D_
<li>_x000D_
<span>HEADING 2</span>_x000D_
<ul>_x000D_
<li>sub-heading A</li>_x000D_
<li>sub-heading B</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>
_x000D_
The border style has been applied only to the direct children <li>
s, as border
is an non-inherited property. But text color has been applied to all the children, as color
is an inherited property.
Therefore, >
selector would be only useful with non-inherited properties, when it comes to preventing inheritance.
The following code is used in Visual Basic when prompting a user to exit the application:
Dim D As String
D = MsgBox("Are you sure you want to exit?", vbYesNo+vbQuestion,"Thanking You")
If D = vbYes Then
Unload Me
Else
Exit Sub
End If
End
End Sub
It's not possible to clear user history without plugins. And also it's not an issue at developer's perspective, it's the burden of the user to clear his history.
For information refer to How to clear browsers (IE, Firefox, Opera, Chrome) history using JavaScript or Java except from browser itself?
Change
$(".test").click(function(){
To
$(".test").live('click', function(){
If you can't use basename as suggested in other posts, you can always use sed. Here is an (ugly) example. It isn't the greatest, but it works by extracting the wanted string and replacing the input with the wanted string.
echo '/foo/fizzbuzz.bar' | sed 's|.*\/\([^\.]*\)\(\..*\)$|\1|g'
Which will get you the output
fizzbuzz
write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.
The first column has a scrollbar on the cell right below the headers
<table>
<thead>
<th> Header 1</th>
<th> Header 2</th>
<th> Header 3</th>
</thead>
<tbody>
<tr>
<td>
<div style="width: 50; height:30; overflow-y: scroll">
Tklasdjf alksjf asjdfk jsadfl kajsdl fjasdk fljsaldk
fjlksa djflkasjdflkjsadlkf jsakldjfasdjfklasjdflkjasdlkfjaslkdfjasdf
</div>
</td>
<td>
Hello world
</td>
<td> Hello world2
</tr>
</tbody>
</table>
Two's complement subtracts off (1<<bits)
if the highest bit is 1. Taking 8 bits for example, this gives a range of 127 to -128.
A function for two's complement of an int...
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val # return positive value as is
Going from a binary string is particularly easy...
binary_string = '1111' # or whatever... no '0b' prefix
out = twos_comp(int(binary_string,2), len(binary_string))
A bit more useful to me is going from hex values (32 bits in this example)...
hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matter
out = twos_comp(int(hex_string,16), 32)
It can also be used as below:
from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)
It seems necessary to state ones degree here: B.A. in Political Science and B.ed in Computer Science.
To the point:
Is this going to put people off coming to Scala?
Scala is difficult, because its underlying programming paradigm is difficult. Functional programming scares a lot of people. It is possible to build closures in PHP but people rarely do. So no, not this signature but all the rest will put people off, if they do not have the specific education to make them value the power of the underlying paradigm.
If this education is available, everyone can do it. Last year I build a chess computer with a bunch of school kids in SCALA! They had their problems but they did fine in the end.
If you're using Scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?
I would not be worried.
It must be at least 64 bits. Other than that it's implementation defined.
Strictly speaking, unsigned long long
isn't standard in C++ until the C++0x standard. unsigned long long
is a 'simple-type-specifier' for the type unsigned long long int
(so they're synonyms).
The long long
set of types is also in C99 and was a common extension to C++ compilers even before being standardized.
Use this to obtain only the filename.
Path.GetFileName(files[0]);
Consider the below sample code snippet which demonstrates how to dismiss a dialog fragment safely:
DialogFragment dialogFragment = new DialogFragment();
/**
* do something
*/
// Now you want to dismiss the dialog fragment
if (dialogFragment.getDialog() != null && dialogFragment.getDialog().isShowing())
{
// Dismiss the dialog
dialogFragment.dismiss();
}
Happy Coding!
I get the best looking results by using a 9 patch graphic.
You can simply create an individual 9 patch graphic by using the following editor: http://inloop.github.io/shadow4android/
Example:
The 9 patch graphic:
The result:
The source:
<LinearLayout
android:layout_width="200dp"
android:layout_height="200dp"
android:orientation="vertical"
android:background="@drawable/my_nine_patch"
You could also use promises in this way:
some_3secs_function(this.some_value).then(function(){
some_5secs_function(this.some_other_value).then(function(){
some_8secs_function(this.some_other_other_value);
});
});
You would have to make some_value
global in order to access it from inside the .then
Alternatively, from the outer function you could return the value the inner function would use, like so:
one(some_value).then(function(return_of_one){
two(return_of_one).then(function(return_of_two){
three(return_of_two);
});
});
Since async/await is widely available now, this is the way to accomplish the same:
async function run(){
await $('#art1').animate({'width':'1000px'},1000,'linear').promise()
await $('#art2').animate({'width':'1000px'},1000,'linear').promise()
await $('#art3').animate({'width':'1000px'},1000,'linear').promise()
}
Which is basically "promisifying" your functions (if they're not already asynchronous), and then awaiting them
There are two differences between ==
and ===
in PHP arrays and objects that I think didn't mention here; two arrays with different key sorts, and objects.
If you have an array with a key sort and another array with a different key sort, they are strictly different (i.e. using ===
). That may cause if you key-sort an array, and try to compare the sorted array with the original one.
For instance, consider an empty array. First, we try to push some new indexes to the array without any special sort. A good example would be an array with strings as keys. Now deep into an example:
// Define an array
$arr = [];
// Adding unsorted keys
$arr["I"] = "we";
$arr["you"] = "you";
$arr["he"] = "they";
Now, we have a not-sorted-keys array (e.g., 'he' came after 'you'). Consider the same array, but we sorted its keys alphabetically:
// Declare array
$alphabetArr = [];
// Adding alphabetical-sorted keys
$alphabetArr["I"] = "we";
$alphabetArr["he"] = "they";
$alphabetArr["you"] = "you";
Tip: You can sort an array by key using ksort() function.
Now you have another array with a different key sort from the first one. So, we're going to compare them:
$arr == $alphabetArr; // true
$arr === $alphabetArr; // false
Note: It may be obvious, but comparing two different arrays using strict comparison always results false
. However, two arbitrary arrays may be equal using ===
or not.
You would say: "This difference is negligible". Then I say it's a difference and should be considered and may happen anytime. As mentioned above, sorting keys in an array is a good example of that.
Keep in mind, two different objects are never strict-equal. These examples would help:
$stdClass1 = new stdClass();
$stdClass2 = new stdClass();
$clonedStdClass1 = clone $stdClass1;
// Comparing
$stdClass1 == $stdClass2; // true
$stdClass1 === $stdClass2; // false
$stdClass1 == $clonedStdClass1; // true
$stdClass1 === $clonedStdClass1; // false
Note: Assigning an object to another variable does not create a copy - rather, it creates a reference to the same memory location as the object. See here.
Note: As of PHP7, anonymous classes was added. From the results, there is no difference between new class {}
and new stdClass()
in the tests above.
I added two separate pushurl to the remote "origin" in the .git congfig file. When I run git push origin "branchName"
Then it will run through and push to each url. Not sure if there is an easier way to accomplish this but this works for myself to push to Github source code and to push to My.visualStudio source code at the same time.
[remote "origin"]
url = "Main Repo URL"
fetch = +refs/heads/*:refs/remotes/origin/*
pushurl = "repo1 URL"
pushurl = "reop2 URl"
If you don't do anything in your bash script than run the php one, you could simply run the php script from cron with a command like /usr/bin/php /path/to/your/file.php.
std::map::find
returns an iterator to the found element (or to the end()
if the element was not found). So long as the map
is not const, you can modify the element pointed to by the iterator:
std::map<char, int> m;
m.insert(std::make_pair('c', 0)); // c is for cookie
std::map<char, int>::iterator it = m.find('c');
if (it != m.end())
it->second = 42;
What you have will find a space anywhere in the string, not just between words.
If you want to find any kind of whitespace, you can use this, which uses a regular expression:
if (/\s/.test(str)) {
// It has any kind of whitespace
}
\s
means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.
According to MDN, \s
is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000]
.
For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...
If you mean literally spaces, a regex can do it:
if (/^ *$/.test(str)) {
// It has only spaces, or is empty
}
That says: Match the beginning of the string (^
) followed by zero or more space characters followed by the end of the string ($
). Change the *
to a +
if you don't want to match an empty string.
If you mean whitespace as a general concept:
if (/^\s*$/.test(str)) {
// It has only whitespace
}
That uses \s
(whitespace) rather than the space, but is otherwise the same. (And again, change *
to +
if you don't want to match an empty string.)
As described in Cast Functions and Operators:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Therefore, you should use:
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT
You can do:
super.alphaMethod1();
Note, that super
is a reference to the parent, but super() is it's constructor.
Something like this would do:
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
you can iterate over the results with a while
like this:
while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}
There are many other great tutorial out there like these to list a few:
As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance();
see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver")
as its not necessary to initiate it yourself
References:
Sort and print:
var items = from pair in players_Dic
orderby pair.Value descending
select pair;
// Display results.
foreach (KeyValuePair<string, int> pair in items)
{
Debug.Log(pair.Key + " - " + pair.Value);
}
Change descending to acending to change sort order
Simply try this, some of the answers here are not handling unicode data and data that has comma for example date.
function downloadUnicodeCSV(filename, datasource) {
var content = '', newLine = '\r\n';
for (var _i = 0, datasource_1 = datasource; _i < datasource_1.length; _i++) {
var line = datasource_1[_i];
var i = 0;
for (var _a = 0, line_1 = line; _a < line_1.length; _a++) {
var item = line_1[_a];
var it = item.replace(/"/g, '""');
if (it.search(/("|,|\n)/g) >= 0) {
it = '"' + it + '"';
}
content += (i > 0 ? ',' : '') + it;
++i;
}
content += newLine;
}
var link = document.createElement('a');
link.setAttribute('href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(content));
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
PIL pixels are tuples, and tuples are immutable. You need to construct a new tuple. So, instead of the for loop, do:
pixels = [(pixel[0] + 20, pixel[1], pixel[2]) for pixel in pixels]
image.putdata(pixels)
Also, if the pixel is already too red, adding 20 will overflow the value. You probably want something like min(pixel[0] + 20, 255)
or int(255 * (pixel[0] / 255.) ** 0.9)
instead of pixel[0] + 20
.
And, to be able to handle images in lots of different formats, do image = image.convert("RGB")
after opening the image. The convert method will ensure that the pixels are always (r, g, b) tuples.
If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let
, etc...) so you can live within the limits of what older browsers support.
Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.
Here's a version of your code written in ES5 syntax with the Bluebird promise library:
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
<script>
'use strict';
var promise = new Promise(function(resolve) {
setTimeout(function() {
resolve("result");
}, 1000);
});
promise.then(function(result) {
alert("Fulfilled: " + result);
}, function(error) {
alert("Rejected: " + error);
});
</script>
You can also write it like this:
let elem: any;
elem = $("div.printArea");
elem.printArea();
If values are numeric you may also use Counter
from collections.
from collections import Counter
x = {'hello': 1, 'python': 5, 'world': 3}
c = Counter(x)
print(c.most_common())
>> [('python', 5), ('world', 3), ('hello', 1)]
In my case div position was fixed , adding left position was not enough it started working only after adding display block
left:0;
display:block;
It looks like psexec -h
is the way to do this:
-h If the target system is Windows Vista or higher, has the process
run with the account's elevated token, if available.
Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.
But it works on my machine.
if you want to be able to convert integer
back to corresponding enum
with selected value see Constants.forValue(...)
in below auto generated code but if not the answer of BlairHippo is best way to do it.
public enum Constants
{
SIGN_CREATE(0),
SIGN_CREATE(1),
HOME_SCREEN(2),
REGISTER_SCREEN(3);
public static final int SIZE = java.lang.Integer.SIZE;
private int intValue;
private static java.util.HashMap<Integer, Constants> mappings;
private static java.util.HashMap<Integer, Constants> getMappings()
{
if (mappings == null)
{
synchronized (Constants.class)
{
if (mappings == null)
{
mappings = new java.util.HashMap<Integer, Constants>();
}
}
}
return mappings;
}
private Constants(int value)
{
intValue = value;
getMappings().put(value, this);
}
public int getValue()
{
return intValue;
}
public static Constants forValue(int value)
{
return getMappings().get(value);
}
}
You are mixing razor and aspx syntax,if your view engine is razor just do this:
<button class="btn btn-info" type="button" id="addressSearch"
onclick="location.href='@Url.Action("List", "Search")'">
In PyCharm the parameters are added in the Script Parameters
as you did but, they are enclosed in double quotes ""
and without specifying the Interpreter flags like -s
. Those flags are specified in the Interpreter options
box.
Script Parameters box contents:
"file1.txt" "file2.txt"
Interpeter flags:
-s
Or, visually:
Then, with a simple test file to evaluate:
if __name__ == "__main__":
import sys
print(sys.argv)
We get the parameters we provided (with sys.argv[0]
holding the script name of course):
['/Path/to/current/folder/test.py', 'file1.txt', 'file2.txt']
Your code works when run in an script because Python encodes the output to whatever encoding your terminal application is using. If you are piping you must encode it yourself.
A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send.
# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')
Another didactic example is a Python program to convert between ISO-8859-1 and UTF-8, making everything uppercase in between.
import sys
for line in sys.stdin:
# Decode what you receive:
line = line.decode('iso8859-1')
# Work with Unicode internally:
line = line.upper()
# Encode what you send:
line = line.encode('utf-8')
sys.stdout.write(line)
Setting the system default encoding is a bad idea, because some modules and libraries you use can rely on the fact it is ASCII. Don't do it.
You can use the "recursive" setting within glob module to search through subdirectories
For example:
import glob
glob.glob('//Mypath/folder/**/*',recursive = True)
The second line would return all files within subdirectories for that folder location (Note, you need the '**/*' string at the end of your folder string to do this.)
If you specifically wanted to find text files deep within your subdirectories, you can use
glob.glob('//Mypath/folder/**/*.txt',recursive = True)
This is correct.
A[] a = new A[4];
...creates 4 A
references, similar to doing this:
A a1;
A a2;
A a3;
A a4;
Now you couldn't do a1.someMethod()
without allocating a1
like this:
a1 = new A();
Similarly, with the array you need to do this:
a[0] = new A();
...before using it.
None of the above mentioned solution worked. The one that seemed to work only provide the functionality for just one cell
Recently I had to enter a lot of names and without suggestions, it was a huge pain. I was fortunate enough to have this excel autocomplete add-in to enable the autocompletion. The down side is that you need to enable macro (but you can always turn it off later)
Make sure the hamcrest jar is higher on the import order than your JUnit jar.
JUnit comes with its own org.hamcrest.Matcher
class that is probably being used instead.
You can also download and use the junit-dep-4.10.jar instead which is JUnit without the hamcrest classes.
mockito also has the hamcrest classes in it as well, so you may need to move\reorder it as well
Using one of the subsets method in this question
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 0),
new KeyValuePair<string, int>("C", 0),
new KeyValuePair<string, int>("D", 2),
new KeyValuePair<string, int>("E", 8),
};
int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);
EDIT
a full console application:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 2),
new KeyValuePair<string, int>("C", 3),
new KeyValuePair<string, int>("D", 4),
new KeyValuePair<string, int>("E", 5),
new KeyValuePair<string, int>("F", 6),
};
int input = 12;
var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);
foreach (var res in alternatives)
{
Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
}
Console.WriteLine("END");
Console.ReadLine();
}
}
public static class Extenions
{
public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
{
List<T> list = enumerable.ToList();
ulong upper = (ulong)1 << list.Count;
for (ulong i = 0; i < upper; i++)
{
List<T> l = new List<T>(list.Count);
for (int j = 0; j < sizeof(ulong) * 8; j++)
{
if (((ulong)1 << j) >= upper) break;
if (((i >> j) & 1) == 1)
{
l.Add(list[j]);
}
}
yield return l;
}
}
}
}
Use a DateFormat
implementation; e.g. SimpleDateFormat
.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String data = df.format(new Date());
Ultimately was able to figure it out , i just hope it will help someone like me.
Following is how the web pack config file should look like
check the dist dir and output file specified. I was missing the way to specify the path of dist directory
const webpack = require('webpack');
const path = require('path');
var config = {
entry: './main.js',
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
resolveLoader: {
modules: [path.join(__dirname, 'node_modules')]
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
}
module.exports = config;
Then the package json file
{
"name": "reactapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack --progress",
"production": "webpack -p --progress"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2",
"webpack": "^2.2.1"
},
"devDependencies": {
"babel-core": "^6.0.20",
"babel-loader": "^6.0.1",
"babel-preset-es2015": "^6.0.15",
"babel-preset-react": "^6.0.15",
"babel-preset-stage-0": "^6.0.15",
"express": "^4.13.3",
"webpack": "^1.9.6",
"webpack-devserver": "0.0.6"
}
}
Notice the script section and production section, production section is what gives you the final deployable index.js file ( name can be anything )
Rest fot the things will depend upon your code and components
Execute following sequence of commands
npm install
this should get you all the dependency (node modules)
then
npm run production
this should get you the final index.js
file which will contain all the code bundled
Once done place index.html
and index.js
files under www/html or the web app root directory and that's all.
void Error(const char* format, ...)
{
va_list argptr;
va_start(argptr, format);
vfprintf(stderr, format, argptr);
va_end(argptr);
}
If you want to manipulate the string before you display it and really do need it stored in a buffer first, use vsnprintf
instead of vsprintf
. vsnprintf
will prevent an accidental buffer overflow error.
You cannot use a variable in a create table statement. The best thing I can suggest is to write the entire query as a string and exec that.
Try something like this:
declare @query varchar(max);
set @query = 'create database TEST...';
exec (@query);
After some search, I've found a cleaner solution wich use the %
operator.
In your YAML file :
key : 'This is the foobar var : %{foobar}'
In your ruby code :
require 'yaml'
file = YAML.load_file('your_file.yml')
foobar = 'Hello World !'
content = file['key']
modified_content = content % { :foobar => foobar }
puts modified_content
And the output is :
This is the foobar var : Hello World !
As @jschorr said in the comment, you can also add multiple variable to the value in the Yaml file :
Yaml :
key : 'The foo var is %{foo} and the bar var is %{bar} !'
Ruby :
# ...
foo = 'FOO'
bar = 'BAR'
# ...
modified_content = content % { :foo => foo, :bar => bar }
Output :
The foo var is FOO and the bar var is BAR !
First we need to find a Button
:
Button mButton = (Button) findViewById(R.id.my_button);
After that, you must implement View.OnClickListener
and there you should find the TextView
and execute the method setText
:
mButton.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
mTextView.setText("Some Text");
}
});
Though not explicitly stated in the question, the purpose is to connect to a specific schema/database.
Another option is to directly connect to the schema. Example:
sudo -u postgres psql -d my_database_name
Source from man psql
:
-d dbname
--dbname=dbname
Specifies the name of the database to connect to. This is equivalent to specifying dbname as the first non-option argument on the command line.
If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string. See Section 31.1.1, “Connection Strings”, in the
documentation for more information.
The answer provided by Joe Stefanelli is already correct.
SELECT name FROM (SELECT name FROM agentinformation) as a
We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.
Statements that include a subquery usually take one of these forms:
Check for more subquery rules and subquery types.
More examples of Nested Subqueries.
IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.
ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The
e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.
e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.
val() should handle both cases
<option value="1">it's me</option>
$('select').val('1'); // selects "it's me"
$('select').val("it's me"); // also selects "it's me"
In MATLAB R2015a or newer, it is no longer necessary (or advisable from a performance standpoint) to use fspecial
followed by imfilter
since there is a new function called imgaussfilt
that performs this operation in one step and more efficiently.
The basic syntax:
B = imgaussfilt(A,sigma)
filters imageA
with a 2-D Gaussian smoothing kernel with standard deviation specified bysigma
.
The size of the filter for a given Gaussian standard deviation (sigam
) is chosen automatically, but can also be specified manually:
B = imgaussfilt(A,sigma,'FilterSize',[3 3]);
The default is 2*ceil(2*sigma)+1
.
Additional features of imgaussfilter
are ability to operate on gpuArray
s, filtering in frequency or spacial domain, and advanced image padding options. It looks a lot like IPP... hmmm. Plus, there's a 3D version called imgaussfilt3
.
CHAR is a fixed length field; VARCHAR is a variable length field. If you are storing strings with a wildly variable length such as names, then use a VARCHAR, if the length is always the same, then use a CHAR because it is slightly more size-efficient, and also slightly faster.
Try using absolute positioning, rather than relative positioning
this should get you close - you can adjust by tweaking margins or top/left positions
#play_button {
position:absolute;
transition: .5s ease;
top: 50%;
left: 50%;
}
[ ].has(obj)
assuming .indexOf()
is implemented
Object.defineProperty( Array.prototype,'has',
{
value:function(o, flag){
if (flag === undefined) {
return this.indexOf(o) !== -1;
} else { // only for raw js object
for(var v in this) {
if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
}
return false;
},
// writable:false,
// enumerable:false
})
!!! do not make Array.prototype.has=function(){...
because you'll add an enumerable element in every array and js is broken.
//use like
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") // true
[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false
the use of 2nd arg (flag) forces comparation by value instead of reference
comparing raw objects
[o1].has(o2,true) // true if every level value is same
you should use a /d before path as below :
cd /d e:\
I want a code from ground 0 so i did this to read the content of dictionary's word line by line.
char temp_str[20]; // you can change the buffer size according to your requirements And A single line's length in a File.
Note I've initialized the buffer With Null character each time I read line.This function can be Automated But Since I need A proof of Concept and want to design a programme Byte By Byte
#include<stdio.h>
int main()
{
int i;
char temp_ch;
FILE *fp=fopen("data.txt","r");
while(temp_ch!=EOF)
{
i=0;
char temp_str[20]={'\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0'};
while(temp_ch!='\n')
{
temp_ch=fgetc(fp);
temp_str[i]=temp_ch;
i++;
}
if(temp_ch=='\n')
{
temp_ch=fgetc(fp);
temp_str[i]=temp_ch;
}
printf("%s",temp_str);
}
return 0;
}
ClusterIP: Services are reachable by pods/services in the Cluster
If I make a service called myservice in the default namespace of type: ClusterIP then the following predictable static DNS address for the service will be created:
myservice.default.svc.cluster.local (or just myservice.default, or by pods in the default namespace just "myservice" will work)
And that DNS name can only be resolved by pods and services inside the cluster.
NodePort: Services are reachable by clients on the same LAN/clients who can ping the K8s Host Nodes (and pods/services in the cluster) (Note for security your k8s host nodes should be on a private subnet, thus clients on the internet won't be able to reach this service)
If I make a service called mynodeportservice in the mynamespace namespace of type: NodePort on a 3 Node Kubernetes Cluster. Then a Service of type: ClusterIP will be created and it'll be reachable by clients inside the cluster at the following predictable static DNS address:
mynodeportservice.mynamespace.svc.cluster.local (or just mynodeportservice.mynamespace)
For each port that mynodeportservice listens on a nodeport in the range of 30000 - 32767 will be randomly chosen. So that External clients that are outside the cluster can hit that ClusterIP service that exists inside the cluster.
Lets say that our 3 K8s host nodes have IPs 10.10.10.1, 10.10.10.2, 10.10.10.3, the Kubernetes service is listening on port 80, and the Nodeport picked at random was 31852.
A client that exists outside of the cluster could visit 10.10.10.1:31852, 10.10.10.2:31852, or 10.10.10.3:31852 (as NodePort is listened for by every Kubernetes Host Node) Kubeproxy will forward the request to mynodeportservice's port 80.
LoadBalancer: Services are reachable by everyone connected to the internet* (Common architecture is L4 LB is publicly accessible on the internet by putting it in a DMZ or giving it both a private and public IP and k8s host nodes are on a private subnet)
(Note: This is the only service type that doesn't work in 100% of Kubernetes implementations, like bare metal Kubernetes, it works when Kubernetes has cloud provider integrations.)
If you make mylbservice, then a L4 LB VM will be spawned (a cluster IP service, and a NodePort Service will be implicitly spawned as well). This time our NodePort is 30222. the idea is that the L4 LB will have a public IP of 1.2.3.4 and it will load balance and forward traffic to the 3 K8s host nodes that have private IP addresses. (10.10.10.1:30222, 10.10.10.2:30222, 10.10.10.3:30222) and then Kube Proxy will forward it to the service of type ClusterIP that exists inside the cluster.
You also asked:
Does the NodePort service type still use the ClusterIP? Yes*
Or is the NodeIP actually the IP found when you run kubectl get nodes? Also Yes*
Lets draw a parrallel between Fundamentals:
A container is inside a pod. a pod is inside a replicaset. a replicaset is inside a deployment.
Well similarly:
A ClusterIP Service is part of a NodePort Service. A NodePort Service is Part of a Load Balancer Service.
In that diagram you showed, the Client would be a pod inside the cluster.
If the compiler supports Named Return Value Optimization (http://msdn.microsoft.com/en-us/library/ms364057(v=vs.80).aspx), you can directly return the vector provide that there is no:
NRVO optimizes out the redundant copy constructor and destructor calls and thus improves overall performance.
There should be no real diff in your example.
As for your last question, here's the problem illustrated with a simple example:
Let's say that your list contains 5 elements: list = [1, 2, 3, 4, 5]
and your list of items to remove (i.e. the indices) is indices_to_remove = [0, 2, 4]
. In the first iteration of the loop you remove the item at index 0, so your list becomes list = [2, 3, 4, 5]
. In the second iteration, you remove the item at index 2, so your list becomes list = [2, 3, 5]
(as you can see, this removes the wrong element). Finally, in the third iteration, you try to remove the element at index 4, but the list only contains three elements, so you get an out of bounds exception.
Now that you see what the problem is, hopefully you will be able to come up with a solution. Good luck!
__getattr__()
getattr
is a really nice way to make generic classes, which is especially useful if you're writing an API. For example, in the FogBugz Python API, getattr
is used to pass method calls on to the web service seamlessly:
class FogBugz:
...
def __getattr__(self, name):
# Let's leave the private stuff to Python
if name.startswith("__"):
raise AttributeError("No such attribute '%s'" % name)
if not self.__handlerCache.has_key(name):
def handler(**kwargs):
return self.__makerequest(name, **kwargs)
self.__handlerCache[name] = handler
return self.__handlerCache[name]
...
When someone calls FogBugz.search(q='bug')
, they don't get actually call a search
method. Instead, getattr
handles the call by creating a new function that wraps the makerequest
method, which crafts the appropriate HTTP request to the web API. Any errors will be dispatched by the web service and passed back to the user.
Remove the file: C:/Sites/folder/Pids/Server.pids
Explanation In UNIX land at least we usually track the process id (pid) in a file like server.pid. I think this is doing the same thing here. That file was probably left over from a crash.