just use following code
c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Then it will give you
you can check shape and dimension of matrix by using following code
c.shape
c.ndim
Here is just another option you couold apply for ASP NET MVC.
Normally you shoud use BaseController
class for each Controller
class.
So inside of it's constructor method do following.
public class BaseController : Controller
{
public BaseController()
{
// get the previous url and store it with view model
ViewBag.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
}
}
And now in ANY view you can do like
<button class="btn btn-success mr-auto" onclick=" window.location.href = '@ViewBag.PreviousUrl'; " style="width:2.5em;"><i class="fa fa-angle-left"></i></button>
Enjoy!
check your build.gradle
file and make sure that use apply plugin: 'com.android.application'
istead of
apply plugin: 'com.android.library'
it worked for me
In SQL Server Denali, you will be able to do something that approaches what you're looking for. But you still can't just pass any arbitrarily defined wacky date string and expect SQL Server to accommodate. Here is one example using something you posted in your own answer. The FORMAT() function and can also accept locales as an optional argument - it is based on .Net's format, so most if not all of the token formats you'd expect to see will be there.
DECLARE @d DATETIME = '2008-10-13 18:45:19';
-- returns Oct-13/2008 18:45:19:
SELECT FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss');
-- returns NULL if the conversion fails:
SELECT TRY_PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);
-- returns an error if the conversion fails:
SELECT PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);
I strongly encourage you to take more control and sanitize your date inputs. The days of letting people type dates using whatever format they want into a freetext form field should be way behind us by now. If someone enters 8/9/2011 is that August 9th or September 8th? If you make them pick a date on a calendar control, then the app can control the format. No matter how much you try to predict your users' behavior, they'll always figure out a dumber way to enter a date that you didn't plan for.
Until Denali, though, I think that @Ovidiu has the best advice so far... this can be made fairly trivial by implementing your own CLR function. Then you can write a case/switch for as many wacky non-standard formats as you want.
UPDATE for @dhergert:
SELECT TRY_PARSE('10/15/2008 10:06:32 PM' AS DATETIME USING 'en-us');
SELECT TRY_PARSE('15/10/2008 10:06:32 PM' AS DATETIME USING 'en-gb');
Results:
2008-10-15 22:06:32.000
2008-10-15 22:06:32.000
You still need to have that other crucial piece of information first. You can't use native T-SQL to determine whether 6/9/2012
is June 9th or September 6th.
You can pass it as an environment variable like this. Generally Node
is the host that it is running in. The hostname is defaulted to the host name of the node when it is created.
docker service create -e 'FOO={{.Node.Hostname}}' nginx
Then you can do docker ps
to get the process ID and look at the env
$ docker exec -it c81640b6d1f1 env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=c81640b6d1f1
TERM=xterm
FOO=docker-desktop
NGINX_VERSION=1.17.4
NJS_VERSION=0.3.5
PKG_RELEASE=1~buster
HOME=/root
An example of usage would be with metricbeats so you know which node is having system issues which I put in https://github.com/trajano/elk-swarm:
metricbeat:
image: docker.elastic.co/beats/metricbeat:7.4.0
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- /sys/fs/cgroup:/hostfs/sys/fs/cgroup:ro
- /proc:/hostfs/proc:ro
- /:/hostfs:ro
user: root
hostname: "{{.Node.Hostname}}"
command:
- -E
- |
metricbeat.modules=[
{
module:docker,
hosts:[unix:///var/run/docker.sock],
period:10s,
enabled:true
}
]
- -E
- processors={1:{add_docker_metadata:{host:unix:///var/run/docker.sock}}}
- -E
- output.elasticsearch.enabled=false
- -E
- output.logstash.enabled=true
- -E
- output.logstash.hosts=["logstash:5044"]
deploy:
mode: global
Here's a shorter one:
(Get-ChildItem C:\MYDIRECTORY -Recurse).fullname > filename.txt
It might be, because your span element sets is side as width as its content. if you have a div with 500px width and text-align center, and you enter a span tag it should be aligned in the center. So your problem might be a CSS one. Install Firebug at Firefox and check the style attributes your span or div object has.
You can avoid the repetition with an attribute test instead:
a/b/*[local-name()='c' or local-name()='d' or local-name()='e']
Contrary to Dimitre's antagonistic opinion, the above is not incorrect in a vacuum where the OP has not specified the interaction with namespaces. The self::
axis is namespace restrictive, local-name()
is not. If the OP's intention is to capture c|d|e
regardless of namespace (which I'd suggest is even a likely scenario given the OR nature of the problem) then it is "another answer that still has some positive votes" which is incorrect.
You can't be definitive without definition, though I'm quite happy to delete my answer as genuinely incorrect if the OP clarifies his question such that I am incorrect.
The latter is preferred, because it will handle subclasses properly. In fact, your example can be written even more easily because isinstance()
's second parameter may be a tuple:
if isinstance(b, (str, unicode)):
do_something_else()
or, using the basestring
abstract class:
if isinstance(b, basestring):
do_something_else()
Since you're using SQL 2008:
UPDATE
table_Name
SET
column_A
= CASE
WHEN @flag = '1' THEN @new_value
ELSE 0
END + column_A,
column_B
= CASE
WHEN @flag = '0' THEN @new_value
ELSE 0
END + column_B
WHERE
ID = @ID
If you were using SQL 2012:
UPDATE
table_Name
SET
column_A = column_A + IIF(@flag = '1', @new_value, 0),
column_B = column_B + IIF(@flag = '0', @new_value, 0)
WHERE
ID = @ID
Typically for dynamic lists of items, you use a std::vector
.
Generally I use memset or a loop for raw memory dynamic allocation, depending on how variable I anticipate that area of code to be in the future.
HTML:
<div class="form-group">
<label for="pt_date" class="col-2 col-form-label">Date</label>
<input class="form-control" type="date" value=<?php echo date("Y-m-d") ;?> id="pt_date" name="pt_date">
</div>
SQL
$pt_date = $_POST['pt_date'];
$sql = "INSERT INTO `table` ( `pt_date`) VALUES ( '$pt_date')";
Try this:
@Repository
@Qualifier("birthdayRepository")
public interface BirthdayRepository extends MongoRepository<BirthDay,String> {
public BirthDay findByFirstName(String firstName);
}
And when injecting the bean:
@Autowired
@Qualifier("birthdayRepository")
private BirthdayRepository repository;
If not, check your CoponentScan in your config.
When making join(t)
function for both non-daemon thread and daemon thread, the main thread (or main process) should wait t
seconds, then can go further to work on its own process. During the t
seconds waiting time, both of the children threads should do what they can do, such as printing out some text. After the t
seconds, if non-daemon thread still didn't finish its job, and it still can finish it after the main process finishes its job, but for daemon thread, it just missed its opportunity window. However, it will eventually die after the python program exits. Please correct me if there is something wrong.
OK - so this issue has been driving me crazy - v 6.3.6 on Ubuntu Linux. None of the above solutions worked for me. Connecting to localhost mysql server previously always worked fine. Connecting to remote server always timed out - after about 60 seconds, sometimes after less time, sometimes more.
What finally worked for me was upgrading Workbench to 6.3.9 - no more dropped connections.
npm init
to create the package.json file and then you use
ls node_modules/ | xargs npm install --save
to fill in the modules you have in the node_modules folder.
Edit: @paldepind pointed out that the second command is redundant because npm init
now automatically adds what you have in your node_modules/ folder. I don't know if this has always been the case, but now at least, it works without the second command.
first of all you need to go in your ssh directory
for this type following command in your terminal in mac or whatever you use in window
cd ~/.ssh
now it is in the ssh
here you can find all you ssh key/files related to your all projects. now, type the following command to show you if any ssh key available
ls
this will show you all available ssh, in my case there were two
now, you will need to start an agent to add a ssh in it. For this type following command
eval "$(ssh-agent -s)"
now last but not least you will add a ssh in this agent type following command
ssh-add ~/.ssh/your-ssh
replace
replace your-ssh with your ssh file name which you got a list form second step
ls command
to add parameter to post urls (to perma-links), i use this:
add_filter( 'post_type_link', 'append_query_string', 10, 2 );
function append_query_string( $url, $post )
{
return add_query_arg('my_pid',$post->ID, $url);
}
output:
http://yoursite.com/pagename?my_pid=12345678
Don't do it inside the loop. Make a list, then combine them outside the loop.
datalist = list()
for (i in 1:5) {
# ... make some data
dat <- data.frame(x = rnorm(10), y = runif(10))
dat$i <- i # maybe you want to keep track of which iteration produced it?
datalist[[i]] <- dat # add it to your list
}
big_data = do.call(rbind, datalist)
# or big_data <- dplyr::bind_rows(datalist)
# or big_data <- data.table::rbindlist(datalist)
This is a much more R-like way to do things. It can also be substantially faster, especially if you use dplyr::bind_rows
or data.table::rbindlist
for the final combining of data frames.
Just tried the stored procedure script. Seems the problem is the '
marks around the delimiters. The MySQL Docs show that delimiter characters do not need the single quotes.
So you want:
delimiter //
Instead of:
delimiter '//'
Works for me :)
Description OF Solution : Eclipse IDE can be used for this by creating a sample java project and add all jars in the Project Build path
STEPS below:
Create a sample Eclipse Java project.
All all the jars you have in its Build Path
CTRL+SHIFT+T and Type the full class name .
Results will be displayed in the window with all the jars having that class. See attached picture .
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function
, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList
not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join()
, I prefer list comprehensions and generators over map()
so I would probably use the following:
print '\n'.join(str(p) for p in myList)
If you are in a domain environment, you can also use:
winrs -r:PCNAME cmd
This will open a remote command shell.
If you are using node.js, console.log() takes format string as a first parameter:
console.log('count: %d', count);
Apart from syntactic sugar, a reference is a const
pointer (not pointer to a const
). You must establish what it refers to when you declare the reference variable, and you cannot change it later.
Update: now that I think about it some more, there is an important difference.
A const pointer's target can be replaced by taking its address and using a const cast.
A reference's target cannot be replaced in any way short of UB.
This should permit the compiler to do more optimization on a reference.
One issue is that reindex
will fail if there are duplicate values. Say we're working with timestamped data, which we want to index by date:
df = pd.DataFrame({
'timestamps': pd.to_datetime(
['2016-11-15 1:00','2016-11-16 2:00','2016-11-16 3:00','2016-11-18 4:00']),
'values':['a','b','c','d']})
df.index = pd.DatetimeIndex(df['timestamps']).floor('D')
df
yields
timestamps values
2016-11-15 "2016-11-15 01:00:00" a
2016-11-16 "2016-11-16 02:00:00" b
2016-11-16 "2016-11-16 03:00:00" c
2016-11-18 "2016-11-18 04:00:00" d
Due to the duplicate 2016-11-16
date, an attempt to reindex:
all_days = pd.date_range(df.index.min(), df.index.max(), freq='D')
df.reindex(all_days)
fails with:
...
ValueError: cannot reindex from a duplicate axis
(by this it means the index has duplicates, not that it is itself a dup)
Instead, we can use .loc
to look up entries for all dates in range:
df.loc[all_days]
yields
timestamps values
2016-11-15 "2016-11-15 01:00:00" a
2016-11-16 "2016-11-16 02:00:00" b
2016-11-16 "2016-11-16 03:00:00" c
2016-11-17 NaN NaN
2016-11-18 "2016-11-18 04:00:00" d
fillna
can be used on the column series to fill blanks if needed.
To expand on BalusC's answer, any scenario where the sender continues to write after the peer has stopped reading and closed its socket will produce this exception, as will the peer closing while it still had unread data in its own socket receive buffer. In other words, an application protocol error. For example, if you write something to the peer that the peer doesn't understand, and then it closes its socket in protest, and you then continue to write, the peer's TCP stack will issue an RST, which results in this exception and message at the sender.
The syntax is
EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );
To add on to what Egon said, simply create your blob called "folder/1.txt", and it will work. No need to create a directory.
get ID of ImageView as
ImageView imgFp = (ImageView) findViewById(R.id.imgFp);
then Use
imgFp.setImageResource(R.drawable.fpscan);
to set source image programatically instead from XML.
Simple and elegant solution for BootStrap 3.x. The same modal can be reused in this way.
$("#myModal").modal("hide");
$('#myModal').on('hidden.bs.modal', function (e) {
$("#myModal").html(data);
$("#myModal").modal();
// do something more...
});
First execute this
sudo apt-get install gcc binutils make linux-source
Then run again
/usr/bin/vmware-config-tools.pl
This is all you need to do. Now your system has the gcc make and the linux kernel sources.
If you add the following you can set the background colour or image (your css)
html {
background-image: url('http://yoursite/i/tile.jpg');
background-repeat: repeat;
}
.body {
background-color: transparent;
}
This is because BS applies a css rule for background colour and also for the .container
class.
Simple way to catch all scroll events (touch and wheel)
window.onscroll = function(e) {
// print "false" if direction is down and "true" if up
console.log(this.oldScroll > this.scrollY);
this.oldScroll = this.scrollY;
}
If your server have a http service you can compress your directory and download the compressed file.
Compress:
tar -zcvf archive-name.tar.gz -C directory-name .
Download throught your browser:
If you don't have direct access to the server ip, do a ssh tunnel throught putty, and forward the 80 port in some local port, and you can download the file.
The accepted answer gave two locations:
here
C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache
and possibly here
C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache
Did you try those?
Edited to add
On my Windows Vista machine, it's located in
%Temp%\VWDWebCache
and in
%LocalAppData%\Microsoft\WebsiteCache
From your additional information (regarding team edition) this comes from Clear Client TFS Cache:
Clear Client TFS Cache
Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.
To solve it..
For Windows Vista delete contents of this folder
%LocalAppData%\Microsoft\Team Foundation\1.0\Cache
I ran into this using networkx
and bokeh
This works for me in Windows 7 (taken from here):
To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:
$ jupyter notebook --generate-config
Open the file and search for c.NotebookApp.iopub_data_rate_limit
Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000
and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000
This unforgiving default config is popping up in a lot of places. See git issues:
It looks like it might get resolved with the 5.1 release
Jupyter notebook is now on release 5.2.2
. This problem should have been resolved. Upgrade using conda or pip.
begin()
returns the first pair, (precisely, an iterator to the first pair, and you can access the key/value as ->first
and ->second
of that iterator)
For TF2.x
, you can do like this.
import tensorflow as tf
with tf.compat.v1.Session() as sess:
hello = tf.constant('hello world')
print(sess.run(hello))
>>> b'hello world
It can done simply by using the Builder's setView(). You can create any view of your choice and feed into the builder. This works good. I use a custom TextView that is rendered by the dialog builder. I dont set the message and this space is utilized to render my custome textview.
Create a table layout panel with two columns in your form and name it tlpFields
.
Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).
tlpFields.RowStyles.Clear(); //first you must clear rowStyles
for (int ii = 0; ii < 5; ii++)
{
Label l1= new Label();
TextBox t1 = new TextBox();
l1.Text = "field : ";
tlpFields.Controls.Add(l1, 0, ii); // add label in column0
tlpFields.Controls.Add(t1, 1, ii); // add textbox in column1
tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}
Finally, run the code.
Use the Python set type. That would be the most Pythonic. :)
Also, since it's native, it should be the most optimized method too.
See:
http://docs.python.org/library/stdtypes.html#set
http://docs.python.org/library/sets.htm (for older python)
# Using Python 2.7 set literal format.
# Otherwise, use: l1 = set([1,2,6,8])
#
l1 = {1,2,6,8}
l2 = {2,3,5,8}
l3 = l1 - l2
Use following command instead of npm install
npm ci
python -c "from datetime import datetime; print str(datetime.now())[:-3]"
2017-02-09 10:06:37.006
If you want to execute multiple commands in a for loop, you can save the result of find
with mapfile
(bash >= 4) as an variable and go through the array with ${dirlist[@]}
. It also works with directories containing spaces.
The find
command is based on the answer by Boldewyn. Further information about the find
command can be found there.
IFS=""
mapfile -t dirlist < <( find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n' )
for dir in ${dirlist[@]}; do
echo ">${dir}<"
# more commands can go here ...
done
This was my workaround:
$('#vcGoButton').click(function () {
var buttonStatus = $('#vcChangeLocation').prop('checked');
console.log("Status is " + buttonStatus);
if (buttonStatus) {
var address = $('#vcNewLocation').val();
var cabNumber = $('#vcVehicleNumber').val();
$.get('postCabLocation.php',
{address: address, cabNumber: cabNumber},
function(data) {
console.log("Changed vehicle " + cabNumber + " location to " + address );
});
}
else {
console.log("VC go button clicked, but no location action");
}
});
A few years ago it was said that update()
and digest()
were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:
var crypto = require('crypto');
var text = 'I love cupcakes';
var secret = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1'; //consider using sha256
var hash, hmac;
// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);
hmac.write(text); // write in to the stream
hmac.end(); // can't read from the stream until you call end()
hash = hmac.read().toString('hex'); // read out hmac digest
console.log("Method 1: ", hash);
// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);
Tested on node v6.2.2 and v7.7.2
See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.
In C, a string, as you know, is a character pointer (char *). If you want to swap two strings, you're swapping two char pointers, i.e. just two addresses. In order to do any swap in a function, you need to give it the addresses of the two things you're swapping. So in the case of swapping two pointers, you need a pointer to a pointer. Much like to swap an int, you just need a pointer to an int.
The reason your last code snippet doesn't work is because you're expecting it to swap two char pointers -- it's actually written to swap two characters!
Edit: In your example above, you're trying to swap two int pointers incorrectly, as R. Martinho Fernandes points out. That will swap the two ints, if you had:
int a, b;
intSwap(&a, &b);
Use LocalDate
from java.time, the modern Java date and time API, for a date
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("June 27, 2007", dateFormatter);
System.out.println(date);
Output:
2007-06-27
As others have said already, remember to specify an English-speaking locale when your string is in English. A LocalDate
is a date without time of day, so a lot better suitable for the date from your string than the old Date
class. Despite its name a Date
does not represent a date but a point in time that falls on at least two different dates in different time zones of the world.
Only if you need an old-fashioned Date
for an API that you cannot afford to upgrade to java.time just now, convert like this:
Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = Date.from(startOfDay);
System.out.println(oldfashionedDate);
Output in my time zone:
Wed Jun 27 00:00:00 CEST 2007
Oracle tutorial: Date Time explaining how to use java.time.
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MyDb.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE_FRIDGE_ITEM = "create table FridgeItem(id integer primary key autoincrement,f_id text not null,food_item text not null,quantity text not null,measurement text not null,expiration_date text not null,current_date text not null,flag text not null,location text not null);";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_FRIDGE_ITEM);
}
// Method is called during an upgrade of the database,
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
Log.w(MyDatabaseHelper.class.getName(),"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS FridgeItem");
onCreate(database);
}
}
public class CommentsDataSource {
private MyDatabaseHelper dbHelper;
private SQLiteDatabase database;
public String stringArray[];
public final static String FOOD_TABLE = "FridgeItem"; // name of table
public final static String FOOD_ITEMS_DETAILS = "FoodDetails"; // name of table
public final static String P_ID = "id"; // pid
public final static String FOOD_ID = "f_id"; // id value for food item
public final static String FOOD_NAME = "food_item"; // name of food
public final static String FOOD_QUANTITY = "quantity"; // quantity of food item
public final static String FOOD_MEASUREMENT = "measurement"; // measurement of food item
public final static String FOOD_EXPIRATION = "expiration_date"; // expiration date of food item
public final static String FOOD_CURRENTDATE = "current_date"; // date of food item added
public final static String FLAG = "flag";
public final static String LOCATION = "location";
/**
*
* @param context
*/
public CommentsDataSource(Context context) {
dbHelper = new MyDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
}
public long insertFoodItem(String id, String name,String quantity, String measurement, String currrentDate,String expiration,String flag,String location) {
ContentValues values = new ContentValues();
values.put(FOOD_ID, id);
values.put(FOOD_NAME, name);
values.put(FOOD_QUANTITY, quantity);
values.put(FOOD_MEASUREMENT, measurement);
values.put(FOOD_CURRENTDATE, currrentDate);
values.put(FOOD_EXPIRATION, expiration);
values.put(FLAG, flag);
values.put(LOCATION, location);
return database.insert(FOOD_TABLE, null, values);
}
public long insertFoodItemsDetails(String id, String name,String quantity, String measurement, String currrentDate,String expiration) {
ContentValues values = new ContentValues();
values.put(FOOD_ID, id);
values.put(FOOD_NAME, name);
values.put(FOOD_QUANTITY, quantity);
values.put(FOOD_MEASUREMENT, measurement);
values.put(FOOD_CURRENTDATE, currrentDate);
values.put(FOOD_EXPIRATION, expiration);
return database.insert(FOOD_ITEMS_DETAILS, null, values);
}
public Cursor selectRecords(String id) {
String[] cols = new String[] { FOOD_ID, FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION,FLAG,LOCATION,P_ID};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, P_ID+"=?", new String[]{id}, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
public Cursor selectAllName() {
String[] cols = new String[] { FOOD_NAME};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, null, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
public Cursor selectAllRecords(String loc) {
String[] cols = new String[] { FOOD_ID, FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION,FLAG,LOCATION,P_ID};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, LOCATION+"=?", new String[]{loc}, null, null, null, null);
int size=mCursor.getCount();
stringArray = new String[size];
int i=0;
if (mCursor != null) {
mCursor.moveToFirst();
FoodInfo.arrayList.clear();
while (!mCursor.isAfterLast()) {
String name=mCursor.getString(1);
stringArray[i]=name;
String quant=mCursor.getString(2);
String measure=mCursor.getString(3);
String expir=mCursor.getString(4);
String id=mCursor.getString(7);
FoodInfo fooditem=new FoodInfo();
fooditem.setName(name);
fooditem.setQuantity(quant);
fooditem.setMesure(measure);
fooditem.setExpirationDate(expir);
fooditem.setid(id);
FoodInfo.arrayList.add(fooditem);
mCursor.moveToNext();
i++;
}
}
return mCursor; // iterate to get each value.
}
public Cursor selectExpDate() {
String[] cols = new String[] {FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, null, null, null, null, FOOD_EXPIRATION, null);
int size=mCursor.getCount();
stringArray = new String[size];
if (mCursor != null) {
mCursor.moveToFirst();
FoodInfo.arrayList.clear();
while (!mCursor.isAfterLast()) {
String name=mCursor.getString(0);
String quant=mCursor.getString(1);
String measure=mCursor.getString(2);
String expir=mCursor.getString(3);
FoodInfo fooditem=new FoodInfo();
fooditem.setName(name);
fooditem.setQuantity(quant);
fooditem.setMesure(measure);
fooditem.setExpirationDate(expir);
FoodInfo.arrayList.add(fooditem);
mCursor.moveToNext();
}
}
return mCursor; // iterate to get each value.
}
public int UpdateFoodItem(String id, String quantity, String expiration){
ContentValues values=new ContentValues();
values.put(FOOD_QUANTITY, quantity);
values.put(FOOD_EXPIRATION, expiration);
return database.update(FOOD_TABLE, values, P_ID+"=?", new String[]{id});
}
public void deleteComment(String id) {
System.out.println("Comment deleted with id: " + id);
database.delete(FOOD_TABLE, P_ID+"=?", new String[]{id});
}
}
If you have deleted multiple files locally but not committed, you can force checkout
$ git checkout -f HEAD
Remove ~
character in location
so
path="~/Admin/SomePage.aspx"
becomes
path="Admin/SomePage.aspx"
For business data, if the data is private I would use a secured connection, otherwise a forms authentication is sufficient.
If you do decide to use a secured connection, please note that I do not have experience with securing websites, I am just recanting off what I encountered during my own personal experience. If I am wrong in anyway, please feel free to correct me.
What should I do to prepare my website for https. (Do I need to alter the code / Config)
In order to enable SSL (Secure Sockets Layer) for your website, you would need to set-up a certificate, code or config is not altered.
I have enabled SSL for an internal web-server, by using OpenSSL and ActivePerl from this online tutorial. If this is used for a larger audience (my audience was less than 10 people) and is in the public domain, I suggest seeking professional alternatives.
Is SSL and https one and the same...
Not exactly, but they go hand in hand! SSL ensures that data is encrypted and decrypted back and forth while you are viewing the website, https
is the URI that is need to access the secure website. You will notice when you try to access http://secure.mydomain.com
it displays an error message.
Do I need to apply with someone to get some license or something.
You would not need to obtain a license, but rather a certificate. You can look into companies that offer professional services with securing websites, such as VeriSign as an example.
Do I need to make all my pages secured or only the login page...
Once your certificate is enabled for mydomain.com
every page that falls under *.mydomain.com
will be secured.
SELECT LAST(row_name) FROM table_name
You are importing the module datetime, which doesn't have a strptime
function.
That module does have a datetime
object with that method though:
import datetime
dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")
Alternatively you can import the datetime
object from the module:
from datetime import datetime
dtDate = datetime.strptime(sDate, "%m/%d/%Y")
Note that the strptime
method was added in python 2.5; if you are using an older version use the following code instead:
import datetime, time
dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])
Check this fiddle:
It shows how to manually indent ul and ol using CSS.
HTML
<head>
<title>Lines</title>
</head>
<body>
<ol type="1" style="list-style-position:inside;">
<li>Text</li>
<li>Text</li>
<li >longer Text, longer Text, longer Text, longer Text second line of longer Text </li>
</ol>
<br/>
<ul>
<li>Text</li>
<li>Text</li>
<li>longer Text, longer Text, longer Text, longer Text second line of longer Text </li>
</ul>
</body>
CSS
ol
{
margin:0px;
padding-left:15px;
}
ol li
{
margin: 0px;
padding: 0px;
text-indent: -1em;
margin-left: 1em;
}
ul
{
margin:0;
padding-left:30px;
}
ul li
{
margin: 0px;
padding: 0px;
text-indent: 0.5em;
margin-left: -0.5em;
}
Also I edited your fiddle
Make a note of it.
$this->db->where_in('id', ['20','15','22','42','86']);
Reference: where_in
I created 2 servers, listening on same port 8081, running from same code, while learning
1st server creation shud have worked 2nd server creation failed with EADDRINUSE
node.js callback delays might be reason behind neither worked, or 2nd server creation had exception, and program exited, so 1st server is also closed
2 server issue hint, I got from: How to fix Error: listen EADDRINUSE while using nodejs?
The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).
If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:
Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.
You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).
As an aside, the login properties for sa
would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.
I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM
account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):
And some other resources:
Edited and fixed (thanks to Shredder)
If you mean you want to open a new tab, try the below:
protected void Page_Load(object sender, EventArgs e)
{
this.Form.Target = "_blank";
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Otherpage.aspx");
}
This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.
-J
Obligatory Twisted example:
twistd -n ftp
And probably useful:
twistd ftp --help
Usage: twistd [options] ftp [options].
WARNING: This FTP server is probably INSECURE do not use it.
Options:
-p, --port= set the port number [default: 2121]
-r, --root= define the root of the ftp-site. [default:
/usr/local/ftp]
--userAnonymous= Name of the anonymous user. [default: anonymous]
--password-file= username:password-style credentials database
--version
--help Display this help and exit.
You can also use the following command:
echo toto; history -d $(history | sed -n '$s/\s*\([0-9]*\)\s*.*$/\1/p')
I think it's a very portable command.
For mysql you have limit, you can fire query as :
SELECT * FROM table limit 100` -- get 1st 100 records
SELECT * FROM table limit 100, 200` -- get 200 records beginning with row 101
For Oracle you can use rownum
See mysql select syntax and usage for limit
here.
For SQLite, you have limit, offset
. I haven't used SQLite but I checked it on SQLite Documentation. Check example for SQLite here.
QEMU has a fantastic utility called qmeu-img that will translate between all manner of disk image formats. An article on this process is at http://thedarkmaster.wordpress.com/2007/03/12/vmware-virtual-machine-to-virtual-box-conversion-how-to/
I recall in my head that I used qemu-img to roll multiple VMDKs into one, but I don't have that computer with me to retest the process. Even if I'm wrong, the article above includes a section that describes how to convert them with your VMWare tools.
Update
Original
var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");
string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding
request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;
var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();
From your stack trace, EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
occurred because dispatch_group_t
was released while it was still locking (waiting for dispatch_group_leave
).
According to what you found, this was what happened :
dispatch_group_t group
was created. group
's retain count = 1.-[self webservice:onCompletion:]
captured the group
. group
's retain count = 2.dispatch_async(...., ^{ dispatch_group_wait(group, ...) ... });
captured the group
again. group
's retain count = 3.group
was released. group
's retain count = 2.dispatch_group_leave
was never called.dispatch_group_wait
was timeout. The dispatch_async
block was completed. group
was released. group
's retain count = 1.-[self webservice:onCompletion:]
was called again, the old onCompletion
block was replaced with the new one. So, the old group
was released. group
's retain count = 0. group
was deallocated. That resulted to EXC_BAD_INSTRUCTION
.To fix this, I suggest you should find out why -[self webservice:onCompletion:]
didn't call onCompletion
block, and fix it. Then make sure the next call to the method will happen after the previous call did finish.
In case you allow the method to be called many times whether the previous calls did finish or not, you might find someone to hold group
for you :
DISPATCH_TIME_FOREVER
or a reasonable amount of time that all -[self webservice:onCompletion]
should call their onCompletion
blocks by the time. So that the block in dispatch_async(...)
will hold it for you.group
into a collection, such as NSMutableArray
.I think it is the best approach to create a dedicate class for this action. When you want to make calls to webservice, you then create an object of the class, call the method on it with the completion block passing to it that will release the object. In the class, there is an ivar of dispatch_group_t
or dispatch_semaphore_t
.
Yes! And another solution. My solution differs in the keys that are being checked.
In all other solutions we only look at the keys in dict_b
. But here we look in the union of both dictionaries.
Do with it as you please
def update_nested(dict_a, dict_b):
set_keys = set(dict_a.keys()).union(set(dict_b.keys()))
for k in set_keys:
v = dict_a.get(k)
if isinstance(v, dict):
new_dict = dict_b.get(k, None)
if new_dict:
update_nested(v, new_dict)
else:
new_value = dict_b.get(k, None)
if new_value:
dict_a[k] = new_value
Based on the previous answers, here is another solution which returns the same result as df2.teams.apply(pd.Series) with a much faster run time:
pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)
Timings:
In [1]:
import pandas as pd
d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
df2 = pd.concat([df2]*1000).reset_index(drop=True)
In [2]: %timeit df2['teams'].apply(pd.Series)
8.27 s ± 2.73 s per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [3]: %timeit pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)
35.4 ms ± 5.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
UIImage* image3 = [UIImage imageNamed:@"back_button.png"];
CGRect frameimg = CGRectMake(15,5, 25,25);
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(Back_btn:)
forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];
UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem =mailbutton;
[someButton release];
///// called event
-(IBAction)Back_btn:(id)sender
{
//Your code here
}
SWIFT:
var image3 = UIImage(named: "back_button.png")
var frameimg = CGRect(x: 15, y: 5, width: 25, height: 25)
var someButton = UIButton(frame: frameimg)
someButton.setBackgroundImage(image3, for: .normal)
someButton.addTarget(self, action: Selector("Back_btn:"), for: .touchUpInside)
someButton.showsTouchWhenHighlighted = true
var mailbutton = UIBarButtonItem(customView: someButton)
navigationItem?.leftBarButtonItem = mailbutton
func back_btn(_ sender: Any) {
//Your code here
}
#!/bin/bash
START_TIME=$(date +%s)
sleep 4
echo "Total time elapsed: $(date -ud "@$(($(date +%s) - $START_TIME))" +%T) (HH:MM:SS)"
$ ./total_time_elapsed.sh
Total time elapsed: 00:00:04 (HH:MM:SS)
Use the following: Shift + Alt+(? or ?)
You simply forgot to supply an argument to -i
. Just change -i
to -i ''
.
Of course that means you don't want your files to be backed up; otherwise supply your extension of choice, like -i .bak
.
For NetBeans to be able to interact with tomcat, it needs the user as setup in netbeans to be properly configured in the tomcat-users.xml
file. NetBeans can do so automatically.
That is, within the tomcat-users.xml
, which you can find in ${CATALINA_HOME}/conf
, or ${CATALINA_BASE}/conf
,
script-manager
roleExample, change
<user password="tomcat" roles="manager,admin" username="tomcat"/>
To
<user password="tomcat" roles="manager-script,manager,admin" username="tomcat"/>
manager-script
role is declaredAdd
<role rolename="manager-script"/>
Actually the netbeans online-help incorrectly states:
Username - Specifies the user name that the IDE uses to log into the server's manager application. The user must be associated with the manager role. The first time the IDE started the Tomcat Web Server, such as through the Start/Stop menu action or by executing a web component from the IDE, the IDE adds an admin user with a randomly-generated password to the
tomcat-base-path/conf/tomcat-users.xml
file. (Right-click the Tomcat Web server instance node in the Services window and select Properties. In the Properties dialog box, the Base Directory property points to thebase-dir
directory.) The admin user entry in thetomcat-users.xml
file looks similar to the following:<user username="idea" password="woiehh" roles="manager"/>
The role should be manager-script
, and not manager
.
For a more complete tomcat-users.xml
file:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<role rolename="manager-gui"/>
<user password="tomcat" roles="manager-script" username="tomcat"/>
<user password="pass" roles="manager-gui" username="me"/>
</tomcat-users>
There is another nice posting on why am I getting the deployment error?
Depending on your needs, you may also want to check out the classes CountDownLatch and CyclicBarrier in the java.util.concurrent package. They can be useful if you want your threads to wait for each other, or if you want more fine-grained control over the way your threads execute (e.g., waiting in their internal execution for another thread to set some state). You could also use a CountDownLatch to signal all of your threads to start at the same time, instead of starting them one by one as you iterate through your loop. The standard API docs have an example of this, plus using another CountDownLatch to wait for all threads to complete their execution.
public void frankTest() {
int pageId= -1;
List<Book> users= null;
try {
//Does Not Compile: Object page=DatabaseConnection.getSpringConnection().queryForObject("SELECT * FROM bookmark_page", (rw, n) -> new Portal(rw.getInt("id"), "", users.parallelStream().filter(uu -> uu.getVbid() == rw.getString("user_id")).findFirst().get(), rw.getString("name")));
//Compiles:
Object page= DatabaseConnection.getSpringConnection().queryForObject("SELECT * FROM bookmark_page", (rw, n) -> {
try {
final Book bk= users.stream().filter(bp -> {
String name= null;
try {
name = rw.getString("name");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bp.getTitle().equals(name);
}).limit(1).collect(Collectors.toList()).get(0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new Portal(rw.getInt("id"), "", users.get(0), rw.getString("name"));
} );
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The request header contains some POST data. No matter what you do, when you reload the page, the rquest would be sent again.
The simple solution is to redirect to a new (if not the same) page. This pattern is very common in web applications, and is called Post/Redirect/Get. It's typical for all forms to do a POST, then if successful, you should do a redirect.
Try as much as possible to always separate (in different files) your view script (html mostly) from your controller script (business logic and stuff). In this way, you would always post data to a seperate controller script and then redirect back to a view script which when rendered, will contain no POST data in the request header.
You can use this method:
function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
delimiter = string.split(stringtodelimite,pattern)
All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS.
But, with the first two non-template examples, are there any other subtle differences in the standard?
(1) In addition to the examples of alias templates, which has already been mentioned in the original post.
As governed by [dcl.typedef]/2 [extract, emphasis mine]
[dcl.typedef]/2 A typedef-name can also be introduced by an alias-declaration. The identifier following the
using
keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. Such a typedef-name has the same semantics as if it were introduced by thetypedef
specifier. [...]
a typedef-name introduced by an alias-declaration has the same semantics as if it were introduced by the typedef
declaration.
However, this does not imply that the two variations have the same restrictions with regard to the contexts in which they may be used. And indeed, albeit a corner case, a typedef declaration is an init-statement and may thus be used in contexts which allow initialization statements
// C++11 (C++03) (init. statement in for loop iteration statements).
for(typedef int Foo; Foo{} != 0;) {}
// C++17 (if and switch initialization statements).
if (typedef int Foo; true) { (void)Foo{}; }
// ^^^^^^^^^^^^^^^ init-statement
switch(typedef int Foo; 0) { case 0: (void)Foo{}; }
// ^^^^^^^^^^^^^^^ init-statement
// C++20 (range-based for loop initialization statements).
std::vector<int> v{1, 2, 3};
for(typedef int Foo; Foo f : v) { (void)f; }
// ^^^^^^^^^^^^^^^ init-statement
for(typedef struct { int x; int y;} P;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ init-statement
auto [x, y] : {P{1, 1}, {1, 2}, {3, 5}}) { (void)x; (void)y; }
whereas an alias-declaration is not an init-statement, and thus may not be used in contexts which allows initialization statements
// C++ 11.
for(using Foo = int; Foo{} != 0;) {}
// ^^^^^^^^^^^^^^^ error: expected expression
// C++17 (initialization expressions in switch and if statements).
if (using Foo = int; true) { (void)Foo{}; }
// ^^^^^^^^^^^^^^^ error: expected expression
switch(using Foo = int; 0) { case 0: (void)Foo{}; }
// ^^^^^^^^^^^^^^^ error: expected expression
// C++20 (range-based for loop initialization statements).
std::vector<int> v{1, 2, 3};
for(using Foo = int; Foo f : v) { (void)f; }
// ^^^^^^^^^^^^^^^ error: expected expression
If you want to do it without any extra includes:
vector<IComponent*> myComponents; //assume it has items in it already.
void RemoveComponent(IComponent* componentToRemove)
{
IComponent* juggler;
if (componentToRemove != NULL)
{
for (int currComponentIndex = 0; currComponentIndex < myComponents.size(); currComponentIndex++)
{
if (componentToRemove == myComponents[currComponentIndex])
{
//Since we don't care about order, swap with the last element, then delete it.
juggler = myComponents[currComponentIndex];
myComponents[currComponentIndex] = myComponents[myComponents.size() - 1];
myComponents[myComponents.size() - 1] = juggler;
//Remove it from memory and let the vector know too.
myComponents.pop_back();
delete juggler;
}
}
}
}
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
For SDK 29 :
String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}
public static void createTextFile(String sBody, String FileName, String Where) {
try {
File gpxfile = new File(Where, FileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then you can save your file like this :
createTextFile("This is Content","file.txt",str1);
Use get_the_category()
like this:
<?php
foreach((get_the_category()) as $category) {
echo $category->cat_name . ' ';
}
?>
It returns a list because a post can have more than one category.
The documentation also explains how to do this from outside the loop.
Those GCD functions provided by Commons-Math and Guava have some differences.
ArithematicException.class
only for Integer.MIN_VALUE
or Long.MIN_VALUE
.
IllegalArgumentException.class
for any negative values.Take a look at the GeckoFX control.
GeckoFX is an open-source component which makes it easy to embed Mozilla Gecko (Firefox) into any .NET Windows Forms application. Written in clean, fully commented C#, GeckoFX is the perfect replacement for the default Internet Explorer-based WebBrowser control.
Sample application using Vue. Requires a backend server running on localhost to process the request:
var app = new Vue({
el: "#app",
data: {
file: ''
},
methods: {
submitFile() {
let formData = new FormData();
formData.append('file', this.file);
console.log('>> formData >> ', formData);
// You should have a server side REST API
axios.post('http://localhost:8080/restapi/fileupload',
formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function () {
console.log('SUCCESS!!');
})
.catch(function () {
console.log('FAILURE!!');
});
},
handleFileUpload() {
this.file = this.$refs.file.files[0];
console.log('>>>> 1st element in files array >>>> ', this.file);
}
}
});
I just had the same issue and could only install tomcat7 as a serivce using the "32-bit/64-bit Windows Service Installer" version of tomcat:
///UPDATED DEMO 2 WATCH SOLUTION////
I hope that is the solution you're looking for! DEMO1 DEMO2
With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!
You can do that with that code here:
<div class="navTop">
<h1>Title</h1>
<nav>Dynamic menu</nav>
</div>
<div class="container">
<section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
Footer
</footer>
With that css:
.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}
And a bit of jquery:
$(document).ready(function() {
function setHeight() {
var top = $('.navTop').outerHeight();
var bottom = $('footer').outerHeight();
var totHeight = $(window).height();
$('section').css({
'height': totHeight - top - bottom + 'px'
});
}
$(window).on('resize', function() { setHeight(); });
setHeight();
});
DEMO 1
If you don't want jquery
<div class="row">
<h1>Title</h1>
<nav>NAV</nav>
</div>
<div class="row container">
<div class="content">
<div class="sidebar">
SIDEBAR
</div>
<div class="contents">
CONTENTS
</div>
</div>
<footer>Footer</footer>
</div>
CSS
*{
margin:0;padding:0;
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%;
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{
position: fixed;
bottom: 0;
left: 0;
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}
DEMO 2
There is no format specifier for bool. You can print it using some of the existing specifiers for printing integral types or do something more fancy:
printf("%s", x?"true":"false");
I found a solution that works for hiding the grid lines in a Line chart.
Set the gridLines
color to be the same as the div's background color.
var options = {
scales: {
xAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}],
yAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}]
}
}
or use
var options = {
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}]
}
}
if you are using webstorm just make sure your default port is not 3000 from file -> settings -> Build, Execution, Deployment -> Debugger And there change
Built-in server port
and set it to "63342" or see this answer Change WebStorm LiveEdit Port (63342)
I've had to do a verification of a letsencrypt certificate and I did it like this:
Issue this command:
$ openssl verify -CAfile letsencrypt-root-cert/isrgrootx1.pem.txt -untrusted letsencrypt-intermediate-cert/letsencryptauthorityx3.pem.txt /etc/letsencrypt/live/sitename.tld/cert.pem
/etc/letsencrypt/live/sitename.tld/cert.pem: OK
You can use this approach which truncates the time part:
select * from test
where convert(datetime,'03/19/2014',102) = DATEADD(dd, DATEDIFF(dd, 0, date), 0)
You can use this function to get the time (unfortunately it doesn't say AM or PM):
def gettime():
from datetime import datetime
return ((str(datetime.now())).split(' ')[1]).split('.')[0]
To get the hours, minutes, seconds and milliseconds to merge later, you can use these functions:
Hour:
def gethour():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
Minute:
def getminute():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]
Second:
def getsecond():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]
Millisecond:
def getmillisecond():
from datetime import datetime
return (str(datetime.now())).split('.')[1]
If you also want to get the name of the foreign key column:
SELECT i.TABLE_SCHEMA, i.TABLE_NAME,
i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME,
k.COLUMN_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME
FROM information_schema.TABLE_CONSTRAINTS i
LEFT JOIN information_schema.KEY_COLUMN_USAGE k
ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME
WHERE i.TABLE_SCHEMA = '<TABLE_NAME>' AND i.CONSTRAINT_TYPE = 'FOREIGN KEY'
ORDER BY i.TABLE_NAME;
Open Console/Command line --> Go to your Jenkins installation directory. Execute the following commands respectively:
to stop:
jenkins.exe stop
to start:
jenkins.exe start
to restart:
jenkins.exe restart
You can do this.
git clone https://github.com/sferik/sign-in-with-twitter.git signin
Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.
As pointed out, you can use getElementById
instead, but you can also still achieve the same with a querySelector
:
document.querySelector("[id='22']")
You can define a generic function like this:
@SuppressWarnings("unchecked")
public static <T> List<T> newFixedSizeList(int size) {
return (List<T>)Arrays.asList(new Object[size]);
}
And
List<String> s = newFixedSizeList(3); // All elements are initialized to null
s.set(0, "zero");
s.add("three"); // throws java.lang.UnsupportedOperationException
Try
$('li.current_sub').prev('.par_cat').[do stuff];
I just looked and found cell|all output|clear which worked with:
Server Information: You are using Jupyter notebook.
The version of the notebook server is: 6.1.5 The server is running on this version of Python: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]
Current Kernel Information: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.
In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).
As Peter Mortensen wrote:
In the Visual Studio 2005 menu:
Debug -> New Breakpoint -> New Data Breakpoint
Enter: &myVariable
Additional information:
Obviously, the system must know which address in memory to watch.
So
- set a normal breakpoint to the initialisation of myVariable
(or myClass.m_Variable
)
- run the system and wait till it stops at that breakpoint.
- Now the Menu entry is enabled, and you can watch the variable by entering &myVariable
,
or the instance by entering &myClass.m_Variable
. Now the addresses are well defined.
Sorry when I did things wrong by explaining an already given solution. But I could not add a comment, and there has been some comments regarding this.
The solution given by Ash Clarke for subdomains works great, but please note that you need to include the document.domain = "mydomain.com"; in both the head of the iframe page and the head of the parent page, as stated in the link same origin policy checks
An important extension to the same origin policy implemented for JavaScript DOM access (but not for most of the other flavors of same-origin checks) is that two sites sharing a common top-level domain may opt to communicate despite failing the "same host" check by mutually setting their respective document.domain DOM property to the same qualified, right-hand fragment of their current host name. For example, if http://en.example.com/ and http://fr.example.com/ both set document.domain to "example.com", they would be from that point on considered same-origin for the purpose of DOM manipulation.
Or you can use reject
method
$newColection = $collection->reject(function($element) {
return $item->selected != true;
});
or pull
method
$selected = [];
foreach ($collection as $key => $item) {
if ($item->selected == true) {
$selected[] = $collection->pull($key);
}
}
Starting with parameter:
setup.exe /A
asks for saving included files (including MSI
).
This may depend on the software which created the setup.exe
.
With the release of iOS 7 (September 18th, 2013) apple increased the over-the-air cellular download limit to 100MBs.
Maximum app size remains 2GBs.
Yes. Look at http://jerrywickey.com/test/testJerrysLibrary.php
It gives sample code examples for RSA encryption and decryption in PHP as well as RSA encryption in javascript.
If you want to encrypt text instead of just base 10 numbers, you'll also need a base to base conversion. That is convert text to a very large number. Text is really just writing in base 63. 26 lowercase letters plus 26 uppercase + 10 numerals + space character. The code for that is below also.
The $GETn parameter is a file name that holds keys for the cryption functions. If you don't figure it out, ask. I'll help.
I actually posted this whole encryption library yesterday, but Brad Larson a mod, killed it and said this kind of stuff isn't really what Stack Overflow is about. But you can still find all the code examples and the whole function library to carry out client/server encryption decryption for AJAX at the link above.
function RSAencrypt( $num, $GETn){
if ( file_exists( 'temp/bigprimes'.hash( 'sha256', $GETn).'.php')){
$t= explode( '>,', file_get_contents('temp/bigprimes'.hash( 'sha256', $GETn).'.php'));
return JL_powmod( $num, $t[4], $t[10]);
}else{
return false;
}
}
function RSAdecrypt( $num, $GETn){
if ( file_exists( 'temp/bigprimes'.hash( 'sha256', $GETn).'.php')){
$t= explode( '>,', file_get_contents('temp/bigprimes'.hash( 'sha256', $GETn).'.php'));
return JL_powmod( $num, $t[8], $t[10]);
}else{
return false;
}
}
function JL_powmod( $num, $pow, $mod) {
if ( function_exists('bcpowmod')) {
return bcpowmod( $num, $pow, $mod);
}
$result= '1';
do {
if ( !bccomp( bcmod( $pow, '2'), '1')) {
$result = bcmod( bcmul( $result, $num), $mod);
}
$num = bcmod( bcpow( $num, '2'), $mod);
$pow = bcdiv( $pow, '2');
} while ( bccomp( $pow, '0'));
return $result;
}
function baseToBase ($message, $fromBase, $toBase){
$from= strlen( $fromBase);
$b[$from]= $fromBase;
$to= strlen( $toBase);
$b[$to]= $toBase;
$result= substr( $b[$to], 0, 1);
$f= substr( $b[$to], 1, 1);
$tf= digit( $from, $b[$to]);
for ($i=strlen($message)-1; $i>=0; $i--){
$result= badd( $result, bmul( digit( strpos( $b[$from], substr( $message, $i, 1)), $b[$to]), $f, $b[$to]), $b[$to]);
$f= bmul($f, $tf, $b[$to]);
}
return $result;
}
function digit( $from, $bto){
$to= strlen( $bto);
$b[$to]= $bto;
$t[0]= intval( $from);
$i= 0;
while ( $t[$i] >= intval( $to)){
if ( !isset( $t[$i+1])){
$t[$i+1]= 0;
}
while ( $t[$i] >= intval( $to)){
$t[$i]= $t[$i] - intval( $to);
$t[$i+1]++;
}
$i++;
}
$res= '';
for ( $i=count( $t)-1; $i>=0; $i--){
$res.= substr( $b[$to], $t[$i], 1);
}
return $res;
}
function badd( $n1, $n2, $nbase){
$base= strlen( $nbase);
$b[$base]= $nbase;
while ( strlen( $n1) < strlen( $n2)){
$n1= substr( $b[$base], 0, 1) . $n1;
}
while ( strlen( $n1) > strlen( $n2)){
$n2= substr( $b[$base], 0, 1) . $n2;
}
$n1= substr( $b[$base], 0, 1) . $n1;
$n2= substr( $b[$base], 0, 1) . $n2;
$m1= array();
for ( $i=0; $i<strlen( $n1); $i++){
$m1[$i]= strpos( $b[$base], substr( $n1, (strlen( $n1)-$i-1), 1));
}
$res= array();
$m2= array();
for ($i=0; $i<strlen( $n1); $i++){
$m2[$i]= strpos( $b[$base], substr( $n2, (strlen( $n1)-$i-1), 1));
$res[$i]= 0;
}
for ($i=0; $i<strlen( $n1) ; $i++){
$res[$i]= $m1[$i] + $m2[$i] + $res[$i];
if ($res[$i] >= $base){
$res[$i]= $res[$i] - $base;
$res[$i+1]++;
}
}
$o= '';
for ($i=0; $i<strlen( $n1); $i++){
$o= substr( $b[$base], $res[$i], 1).$o;
}
$t= false;
$o= '';
for ($i=strlen( $n1)-1; $i>=0; $i--){
if ($res[$i] > 0 || $t){
$o.= substr( $b[$base], $res[$i], 1);
$t= true;
}
}
return $o;
}
function bmul( $n1, $n2, $nbase){
$base= strlen( $nbase);
$b[$base]= $nbase;
$m1= array();
for ($i=0; $i<strlen( $n1); $i++){
$m1[$i]= strpos( $b[$base], substr($n1, (strlen( $n1)-$i-1), 1));
}
$m2= array();
for ($i=0; $i<strlen( $n2); $i++){
$m2[$i]= strpos( $b[$base], substr($n2, (strlen( $n2)-$i-1), 1));
}
$res= array();
for ($i=0; $i<strlen( $n1)+strlen( $n2)+2; $i++){
$res[$i]= 0;
}
for ($i=0; $i<strlen( $n1) ; $i++){
for ($j=0; $j<strlen( $n2) ; $j++){
$res[$i+$j]= ($m1[$i] * $m2[$j]) + $res[$i+$j];
while ( $res[$i+$j] >= $base){
$res[$i+$j]= $res[$i+$j] - $base;
$res[$i+$j+1]++;
}
}
}
$t= false;
$o= '';
for ($i=count( $res)-1; $i>=0; $i--){
if ($res[$i]>0 || $t){
$o.= substr( $b[$base], $res[$i], 1);
$t= true;
}
}
return $o;
}
A possible explanation is that the selectlist value that you are binding to is not a string.
So in that example, is the parameter 'PageOptionsDropDown' a string in your model? Because if it isn't then the selected value in the list wouldn't be shown.
The easiest way to do this is with 2 divs, 1 with the background and 1 with the text:
#container {_x000D_
position: relative;_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
}_x000D_
#block {_x000D_
background: #CCC;_x000D_
filter: alpha(opacity=60);_x000D_
/* IE */_x000D_
-moz-opacity: 0.6;_x000D_
/* Mozilla */_x000D_
opacity: 0.6;_x000D_
/* CSS3 */_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
#text {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="block"></div>_x000D_
<div id="text">Test</div>_x000D_
</div>
_x000D_
That isn't the Node.js command prompt window. That is a language shell to run JavaScript commands, also known as a REPL.
In Windows, there should be a Node.js command prompt in your Start menu or start screen:
Which will open a command prompt window that looks like this:
From there you can switch directories using the cd
command.
To suppress output, use redirection to NUL
.
There are two kinds of output that console commands use:
standard output, or stdout
,
standard error, or stderr
.
Of the two, stdout
is used more often, both by internal commands, like copy
, and by console utilities, or external commands, like find
and others, as well as by third-party console programs.
>NUL
suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied.
message of the copy
command. An alternative syntax is 1>NUL
. So,
COPY file1 file2 >NUL
or
COPY file1 file2 1>NUL
or
>NUL COPY file1 file2
or
1>NUL COPY file1 file2
suppresses all of COPY
's standard output.
To suppress error messages, which are typically printed to stderr
, use 2>NUL
instead. So, to suppress a File Not Found
message that DEL
prints when, well, the specified file is not found, just add 2>NUL
either at the beginning or at the end of the command line:
DEL file 2>NUL
or
2>NUL DEL file
Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:
IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
Sorry, not Swift, just a proof of concept in the closest language at hand.
// JavaScript POC. Output:
// Matches: ["GOODBYE","CRUEL","WORLD","IM","LEAVING","U","TODAY"]
let str = `GOODBYE,CRUEL,WORLD,IM,LEAVING,U,TODAY`
let matches = [];
function recurse(str, matches) {
let regex = /^((,?([A-Z]+))+)$/gm
let m
while ((m = regex.exec(str)) !== null) {
matches.unshift(m[3])
return str.replace(m[2], '')
}
return "bzzt!"
}
while ((str = recurse(str, matches)) != "bzzt!") ;
console.log("Matches: ", JSON.stringify(matches))
Note: If you were really going to use this, you would use the position of the match as given by the regex match function, not a string replace.
Change the Encoding of the stream writer. It's a property.
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.encoding.aspx
So:
sw.Encoding = Encoding.GetEncoding(28591);
Prior to writing to the stream.
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
I managed to use soap,wsdl and Node.js
You need to install soap with npm install soap
Create a node server called server.js
that will define soap service to be consumed by a remote client. This soap service computes Body Mass Index based on weight(kg) and height(m).
const soap = require('soap');
const express = require('express');
const app = express();
/**
* this is remote service defined in this file, that can be accessed by clients, who will supply args
* response is returned to the calling client
* our service calculates bmi by dividing weight in kilograms by square of height in metres
*/
const service = {
BMI_Service: {
BMI_Port: {
calculateBMI(args) {
//console.log(Date().getFullYear())
const year = new Date().getFullYear();
const n = args.weight / (args.height * args.height);
console.log(n);
return { bmi: n };
}
}
}
};
// xml data is extracted from wsdl file created
const xml = require('fs').readFileSync('./bmicalculator.wsdl', 'utf8');
//create an express server and pass it to a soap server
const server = app.listen(3030, function() {
const host = '127.0.0.1';
const port = server.address().port;
});
soap.listen(server, '/bmicalculator', service, xml);
Next, create a client.js
file that will consume soap service defined by server.js
. This file will provide arguments for the soap service and call the url with SOAP's service ports and endpoints.
const express = require('express');
const soap = require('soap');
const url = 'http://localhost:3030/bmicalculator?wsdl';
const args = { weight: 65.7, height: 1.63 };
soap.createClient(url, function(err, client) {
if (err) console.error(err);
else {
client.calculateBMI(args, function(err, response) {
if (err) console.error(err);
else {
console.log(response);
res.send(response);
}
});
}
});
Your wsdl file is an xml based protocol for data exchange that defines how to access a remote web service. Call your wsdl file bmicalculator.wsdl
<definitions name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<message name="getBMIRequest">
<part name="weight" type="xsd:float"/>
<part name="height" type="xsd:float"/>
</message>
<message name="getBMIResponse">
<part name="bmi" type="xsd:float"/>
</message>
<portType name="Hello_PortType">
<operation name="calculateBMI">
<input message="tns:getBMIRequest"/>
<output message="tns:getBMIResponse"/>
</operation>
</portType>
<binding name="Hello_Binding" type="tns:Hello_PortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="calculateBMI">
<soap:operation soapAction="calculateBMI"/>
<input>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
</input>
<output>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
</output>
</operation>
</binding>
<service name="BMI_Service">
<documentation>WSDL File for HelloService</documentation>
<port binding="tns:Hello_Binding" name="BMI_Port">
<soap:address location="http://localhost:3030/bmicalculator/" />
</port>
</service>
</definitions>
Hope it helps
You can try this query in any given SQL Server database:
SELECT
name,
create_date,
modify_date
FROM sys.procedures
WHERE create_date = '20120927'
which lists out the name, the creation and the last modification date - unfortunately, it doesn't record who created and/or modified the stored procedure in question.
Assuming (!) the strings are of equal length, why not convert the strings to byte arrays and then XOR the bytes. The resultant byte arrays may be of different lengths too depending on your encoding (e.g. UTF8 will expand to different byte lengths for different characters).
You should be careful to specify the character encoding to ensure consistent/reliable string/byte conversion.
New ways to align items right:
Grid:
.header {
display:grid;
grid-template-columns: 1fr auto;
}
<div class="row">
<div class="col">left</div>
<div class="col">
<div class="float-right">element needs to be right aligned</div>
</div>
</div>
Xamarin.Forms
supports multiple navigation hosts built-in:
NavigationPage
, where the next page slide in,TabbedPage
, the one you don't likeCarouselPage
, that allows for switching left and right to next/prev pages.On top of this, all pages also supports PushModalAsync()
which just push a new page on top of the existing one.
At the very end, if you want to make sure the user can't get back to the previous page (using a gesture or the back hardware button), you can keep the same Page
displayed and replace its Content
.
The suggested options of replacing the root page works as well, but you'll have to handle that differently for each platform.
I feel like the simplest solution is sans javascript and simply putting the link in each cell (provided you don't have massive gullies between your cells or really think border lines). Have your css:
.tableClass td a{
display: block;
}
and then add a link per cell:
<table class="tableClass">
<tr>
<td><a href="#link">Link name</a></td>
<td><a href="#link">Link description</a></td>
<td><a href="#link">Link somthing else</a></td>
</tr>
</table>
boring but clean.
The problem with Java console input is that it's buffered input, and requires an enter key to continue.
There are these two discussions: Detecting and acting on keyboard direction keys in Java and Java keyboard input parsing in a console app
The latter of which used JLine to get his problem solved.
I personally haven't used it.
This is a variation on this answer, currently suggested by gitlab to "migrate" a git repository from one server to another.
Let us assume that your old project is called existing_repo
, stored in a existing_repo
folder.
Create a repo on your new server. We will assume that the url of that new project is git@newserver:newproject.git
Open a command-line interface, and enter the following:
cd existing_repo
git remote rename origin old-origin
git remote add origin git@newserver:newproject.git
git push -u origin --all
git push -u origin --tags
The benefits of this approach is that you do not delete the branch that corresponds to your old server.
Following code might Help you.
I have taken UITableView
with custom prototype cell class named UITableViewCell
inside UIViewController
.
So i have ViewController.h
, ViewController.m
and TableViewCell.h
,TableViewCell.m
Here is the code for that:
ViewController.h
@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tblView;
@end
ViewController.m
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return (YourNumberOfRows);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"cell";
__weak TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (indexPath.row==0) {
[cell setDidTapButtonBlock:^(id sender)
{
// Your code here
}];
}
return cell;
}
Custom cell class :
TableViewCell.h
@interface TableViewCell : UITableViewCell
@property (copy, nonatomic) void (^didTapButtonBlock)(id sender);
@property (strong, nonatomic) IBOutlet UILabel *lblTitle;
@property (strong, nonatomic) IBOutlet UIButton *btnAction;
- (void)setDidTapButtonBlock:(void (^)(id sender))didTapButtonBlock;
@end
and
UITableViewCell.m
@implementation TableViewCell
- (void)awakeFromNib {
// Initialization code
[self.btnAction addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)didTapButton:(id)sender {
if (self.didTapButtonBlock)
{
self.didTapButtonBlock(sender);
}
}
Note: Here I have taken all UIControls
using Storyboard.
Hope that can help you...!!!
For anyone reading this and using Postgres.app, you may need host: localhost
in your database.yml. http://postgresapp.com/documentation#toc_3
EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value
syntax is incorrect.
I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
error message. In 2008, the modified script is still successful.
declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)
Try building your project from the Powershell command line:
dotnet build
Then you can see any errors in the command line output even if Visual Studio is playing hide and seek with build error messages.
Try this:
var hms = '02:04:33'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
console.log(seconds);
replace method of string objects does not accept regular expressions but only fixed strings (see documentation: http://docs.python.org/2/library/stdtypes.html#str.replace).
You have to use re
module:
import re
newline= re.sub("<\/?\[[0-9]+>", "", line)
Not sure if this is helpful for you, but removing the container always helps.
So, if you use docker-compose for your setup, you can simply use docker-compose down && docker-compose up
instead of docker-compose restart
. With a proper setup (make sure to use volume mounts for persistent data), you don't lose any data this way.
Sure, this is more than the OP requested. But there are various situations where the other answers cannot help (if using a remote docker server or working on a Windows machine, accessing the underlying filesystem is proprietary and difficult)
In Vue2 be aware that you can access this.$refs.uniqueName only after mounting the component.
It's easier to use the timestamp for this things since Tweepy gets both
import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))
If you don't use a compacting garbage collector, you can have some sort of a memory leak due to heap fragmentation.
I fixed this issue on machine disabling the loopback check setting:
I found this extension for VS code called Git Merger. It adds Git: Merge from
to the commands.
<% %>
: Executes the ruby code <%= %>
: Prints into Erb file. Or browser <% -%>
: Avoids line break after expression. <%# %>
: ERB commentDepending on your needs, this can be one step or two steps
1. use encode() to convert string to bytes, immutable
2. use bytearray() to convert bytes to bytearray, mutable
s="ABCD"
encoded=s.encode('utf-8')
array=bytearray(encoded)
The following validation is done in Python 3.7
>>> s="ABCD"
>>> encoded=s.encode('utf-8')
>>> encoded
b'ABCD'
>>> array=bytearray(encoded)
>>> array
bytearray(b'ABCD')
hi guys after one day searching on web finally i solve problem with below source code hope to help you
public UploadResult UploadFile(string fileAddress)
{
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("fileToUpload");
form.Add(content, "fileToUpload");
var stream = new FileStream(fileAddress, FileMode.Open);
content = new StreamContent(stream);
var fileName =
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "name",
FileName = Path.GetFileName(fileAddress),
};
form.Add(content);
HttpResponseMessage response = null;
var url = new Uri("http://192.168.10.236:2000/api/Upload2");
response = (client.PostAsync(url, form)).Result;
}
I don't understand what the meaning of ordering with the same column ASC
and DESC
in the same ORDER BY
, but this how you can do it: naam DESC, naam ASC
like so:
ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC
var dt = DateTime.Now;
var unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();
// 1510396991
var dt = DateTimeOffset.FromUnixTimeSeconds(1510396991);
// [11.11.2017 10:43:11 +00:00]
Performance: No impact on performance as byte code is same. though it will lead to some compile overheads.
Compilation: on my personal machine, Compiling a blank class without importing anything takes 100 ms but same class when import java.* takes 170 ms.
To use uint8_t
type alias, you have to include stdint.h
standard header.
I had this problem i.e. works fine when pasted into browser but 505s when done through java. It was simply the spaces that needed to be escaped/encoded.
.sort()
, in pymongo, takes key
and direction
as parameters.
So if you want to sort by, let's say, id
then you should .sort("_id", 1)
For multiple fields:
.sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])
Found another solution:
In Node.js, you can use its native require("assert").deepStrictEqual
. More info:
http://nodejs.org/api/assert.html
For example:
var assert = require("assert");
assert.deepStrictEqual({a:1, b:2}, {a:1, b:3}); // will throw AssertionError
Another example that returns true
/ false
instead of returning errors:
var assert = require("assert");
function deepEqual(a, b) {
try {
assert.deepEqual(a, b);
} catch (error) {
if (error.name === "AssertionError") {
return false;
}
throw error;
}
return true;
};
A timestamp is a point in time. Typically this can be represented by a number of milliseconds past an epoc (the Unix Epoc of Jan 1 1970 12AM UTC). The format of that point in time depends on the time zone. While it is the same point in time, the "hours value" is not the same among time zones and one must take into account the offset from the UTC.
Here's some code to illustrate. A point is time is captured in three different ways.
var moment = require( 'moment' );
var localDate = new Date();
var localMoment = moment();
var utcMoment = moment.utc();
var utcDate = new Date( utcMoment.format() );
//These are all the same
console.log( 'localData unix = ' + localDate.valueOf() );
console.log( 'localMoment unix = ' + localMoment.valueOf() );
console.log( 'utcMoment unix = ' + utcMoment.valueOf() );
//These formats are different
console.log( 'localDate = ' + localDate );
console.log( 'localMoment string = ' + localMoment.format() );
console.log( 'utcMoment string = ' + utcMoment.format() );
console.log( 'utcDate = ' + utcDate );
//One to show conversion
console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() );
console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() );
Which outputs this:
localData unix = 1415806206570
localMoment unix = 1415806206570
utcMoment unix = 1415806206570
localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localMoment string = 2014-11-12T10:30:06-05:00
utcMoment string = 2014-11-12T15:30:06+00:00
utcDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localDate as UTC format = 2014-11-12T15:30:06+00:00
localDate as UTC unix = 1415806206570
In terms of milliseconds, each are the same. It is the exact same point in time (though in some runs, the later millisecond is one higher).
As far as format, each can be represented in a particular timezone. And the formatting of that timezone'd string looks different, for the exact same point in time!
Are you going to compare these time values? Just convert to milliseconds. One value of milliseconds is always less than, equal to or greater than another millisecond value.
Do you want to compare specific 'hour' or 'day' values and worried they "came from" different timezones? Convert to UTC first using moment.utc( existingDate )
, and then do operations. Examples of those conversions, when coming out of the DB, are the last console.log
calls in the example.
I have solved this by manually copying EntityFramework.SqlServer.dll
file to the bin folder
of the main application.
The reason is apk is not signed. Once the apk is signed, the issue will be resolved. http://ionicframework.com/docs/guide/publishing.html Please use the link on instructions to sign the apk.
public Form1()
{
InitializeComponent();
string myHost = System.Net.Dns.GetHostName();
string myIP = null;
for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
{
myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
}
}
}
Declare myIP and myHost in public Variable and use in any function of the form.
You can use this :
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
For more information see documentation https://square.github.io/retrofit/
IN windows open cmd
go to directory where your netbeans downloaded
then run below command JDK path may be different from the path I mentioned
netbeans-8.2-windows.exe --javahome "C:\Program Files\Java\jdk-9.0.1"
if you face issue in existing installed in netbeans you can find details in here
... you can use it on any granularity type i.e.:
DATEPART(YEAR, [date])
DATEPART(MONTH, [date])
DATEPART(DAY, [date])
DATEPART(HOUR, [date])
DATEPART(MINUTE, [date])
(note: I like the [ ] around the date reserved word though. Of course that's in case your column with timestamp is labeled "date")
If you want to display links coming from your state or store in Vue 2.0, you can do like this:
<a v-bind:href="''">
{{ url_link }}
</a>
Most likely, the remote host ip or ip_alias is not in the ~/.ssh/known_hosts file. You can use the following command to add the host name to known_hosts file.
$ssh-keyscan -H -t rsa ip_or_ipalias >> ~/.ssh/known_hosts
Also, I have generated the following script to check if the particular ip or ipalias is in the know_hosts file.
#!/bin/bash
#Jason Xiong: Dec 2013
# The ip or ipalias stored in known_hosts file is hashed and
# is not human readable.This script check if the supplied ip
# or ipalias exists in ~/.ssh/known_hosts file
if [[ $# != 2 ]]; then
echo "Usage: ./search_known_hosts -i ip_or_ipalias"
exit;
fi
ip_or_alias=$2;
known_host_file=/home/user/.ssh/known_hosts
entry=1;
cat $known_host_file | while read -r line;do
if [[ -z "$line" ]]; then
continue;
fi
hash_type=$(echo $line | sed -e 's/|/ /g'| awk '{print $1}');
key=$(echo $line | sed -e 's/|/ /g'| awk '{print $2}');
stored_value=$(echo $line | sed -e 's/|/ /g'| awk '{print $3}');
hex_key=$(echo $key | base64 -d | xxd -p);
if [[ $hash_type = 1 ]]; then
gen_value=$(echo -n $ip_or_alias | openssl sha1 -mac HMAC \
-macopt hexkey:$hex_key | cut -c 10-49 | xxd -r -p | base64);
if [[ $gen_value = $stored_value ]]; then
echo $gen_value;
echo "Found match in known_hosts file : entry#"$entry" !!!!"
fi
else
echo "unknown hash_type"
fi
entry=$((entry + 1));
done
This is being encoded with htmlentities
.
implode( "\t", array_values( get_html_translation_table( HTML_ENTITIES ) ) )
:
" & < >
¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ Œ œ Š š Ÿ ƒ ˆ ˜ ? ? G ? ? ? ? T ? ? ? ? ? ? ? ? ? S ? ? F ? ? O a ß ? d e ? ? ? ? ? ? µ ? ? ? p ? ? s t ? f ? ? ? ? ? ? ? ? ? ? – — ‘ ’ ‚ “ ” „ † ‡ • … ‰ ' " ‹ › ? / € I P R ™ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Ø ? ? ? ? ? ? - * v ? 8 ? ? ? n ? ? ? ~ ? ˜ ? = = = ? ? ? ? ? ? ? ? · ? ? ? ? ? ? ? ? ? ? ?
This is being encoded with htmlspecialchars
.
implode( "\t", array_values( get_html_translation_table( HTML_SPECIALCHARS ) ) )
:
" & < >
You mentioned getting the result list from the Query, since you don't know that there is a UniqueResult (hence the exception) you could use list and check the size?
if (query.list().size() == 1)
Since you're not doing a get() to get your unique object a query will be executed whether you call uniqueResult or list.
This is a nice 5-part tutorial that covers a lot of useful material: http://mobile.tutsplus.com/tutorials/phonegap/phonegap-from-scratch/
(Anyone else noticing a trend forming here??? hehehee )
And this will definitely be of use to all developers:
http://blip.tv/mobiletuts/weinre-demonstration-5922038
=)
Todd
Edit I just finished a nice four part tutorial building an app to write, save, edit, & delete notes using jQuery mobile (only), it was very practical & useful, but it was also only for jQM. So, I looked to see what else they had on DZone.
I'm now going to start sorting through these search results. At a glance, it looks really promising. I remembered this post; so I thought I'd steer people to it. ?
WHERE NULLIF(your_column, '') IS NOT NULL
Nowadays (4.5 years on), to make it easier for a human to read, I would just use
WHERE your_column <> ''
While there is a temptation to make the null check explicit...
WHERE your_column <> ''
AND your_column IS NOT NULL
...as @Martin Smith demonstrates in the accepted answer, it doesn't really add anything (and I personally shun SQL nulls entirely nowadays, so it wouldn't apply to me anyway!).
Since the rules are running in JavaScript, why not disable them using javascript (or in my examples case, jQuery)?
$('#fieldId').attr('disabled', 'disabled'); //Disable
$('#fieldId').removeAttr('disabled'); //Enable
UPDATE
The attr
function is no longer the primary approach to this, as was pointed out in the comments below. This is now done with the prop
function.
$( "input" ).prop( "disabled", true ); //Disable
$( "input" ).prop( "disabled", false ); //Enable
It's easier using Array.filter
:
var unique = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
As short as @jumbo's answer is :-) you can do it even more tersely.
This just returns the Count
property of the array returned by the antecedent sub-expression:
@(Get-Alias).Count
A couple points to note:
You can put an arbitrarily complex expression in place of Get-Alias
, for example:
@(Get-Process | ? { $_.ProcessName -eq "svchost" }).Count
The initial at-sign (@) is necessary for a robust solution. As long as the answer is two or greater you will get an equivalent answer with or without the @, but when the answer is zero or one you will get no output unless you have the @ sign! (It forces the Count
property to exist by forcing the output to be an array.)
2012.01.30 Update
The above is true for PowerShell V2. One of the new features of PowerShell V3 is that you do have a Count
property even for singletons, so the at-sign becomes unimportant for this scenario.
You get and format like this
for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
set dow=%%i
set month=%%j
set day=%%k
set year=%%l
)
set datestr=%month%_%day%_%year%
echo datestr is %datestr%
Note: Above only works on US locale. It assumes the output of echo %date%
looks like this: Thu 02/13/21
. If you have different Windows locale settings, you will need to modify the script based on your configuration.
Here's how you accomplish that:
//View.cshtml
<script type="text/javascript">
var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.Addresses))');
</script>
In my case, it was caused from gms services 4.3.0. So i had to change it to:
com.google.gms:google-services:4.2.0
I have found this by running:
gradlew sync -Pandroid.debug.obsoleteApi=true
in terminal. Go to view -> tool windows -> Terminal in Android Studio.
I am working MacOS 10.10. I have updated gcc to version 4.9 to make it work.
brew update brew install gcc brew reinstall r
One thing I find easy to do is i set an array of empty strings for the size I prefer, for example
Code:
import numpy as np
x= np.zeros(5,str)
print x
Output:
['' '' '' '' '']
Hope this is helpful :)
I had a sub folder named web.config renaming this folder resolved the issue
You have to add a manifest permission entry:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
(of course you should list all other permissions that your app uses).
Then, implement BroadcastReceiver class, it should be simple and fast executable. The best approach is to set an alarm in this receiver to wake up your service (if it's not necessary to keep it running ale the time as Prahast wrote).
public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pi);
}
}
Then, add a Receiver class to your manifest file:
<receiver android:enabled="true" android:name=".receivers.BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
In the past months, I used a "preview" version of Android Studio. I tried to switch back to the "stable" releases for the software updates but it wasn't enough and I got this famous error you talk of.
Uninstalling my Android Studio 2.2.preview and installing latest stable Android Studio (2.1) fixed it for me :)
You can also use linq extensions for DataSets:
var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
{
TextBox1.Text = imgPath;
}
You can use a library I wrote, FormPersistence.js which handles form (de)serialization by saving values to local/session storage. This approach is similar to that linked in another answer but it does not require jQuery and does not save plaintext passwords to web storage.
let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm, true)
The optional second parameter of each FormPersistence
function defines whether to use local storage (false
) or session storage (true
). In your case, session storage is likely more appropriate.
The form data by default will be cleared from storage upon submission, unless you pass false
as the third parameter. If you have special value handling functions (such as inserting an element) then you can pass those as the fourth parameter. See the repository for complete documentation.
If you are in windows you can just run
net user postgres postgres
and login in postgres with postgres/postgres as user/password
Simply the answer according to my reading and understanding to this thread and @remus-rusanu answer is based on this simple scenario:
There are two transactions A and B. Transaction B is reading Table X Transaction A is writing in table X Transaction B is reading again in Table X.
you can use this too
echo substr($_SERVER['HTTP_HOST'], 0, strrpos($_SERVER['HTTP_HOST'], '.', -5));
You could try to create your own color palette using the RColorBrewer
package
my_palette <- colorRampPalette(c("green", "black", "red"))(n = 1000)
and see how this looks like. But I assume in your case only scaling would help if you really want to keep the black in "the middle". You can simply use my_palette
instead of the redgreen()
I recommend that you check out the RColorBrewer package, they have pretty nice in-built palettes, and see interactive website for colorbrewer.
if you are using Eclipse watch your POM dependencies and your Eclipse buildpath dependency on junit
if you select use Junit4 eclipse create TestCase using org.junit package but your POM use by default Junit3 (junit.framework package) that is the cause, like this picture:
Just update your Junit dependency in your POM file to Junit4 or your Eclipse BuildPath to Junit3
GWT in Intellij 12
FWIW, I was getting a similar error with my GWT application during 'Build | Rebuild Project'.
This was caused by Intellij doing a full GWT compile which I didn't like because it is also a very lengthy process.
I disabled GWT compile by turning off the module check boxes under 'Project Structure | Facets | GWT'.
Alternatively there is a 'Compiler maximum heap size' setting in that location as well.
I'll give 4 solutions:
cryptography
libraryHere is a solution using the package cryptography
, that you can install as usual with pip install cryptography
:
import base64
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
def cipherFernet(password):
key = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=b'abcd', iterations=1000, backend=default_backend()).derive(password)
return Fernet(base64.urlsafe_b64encode(key))
def encrypt1(plaintext, password):
return cipherFernet(password).encrypt(plaintext)
def decrypt1(ciphertext, password):
return cipherFernet(password).decrypt(ciphertext)
# Example:
print(encrypt1(b'John Doe', b'mypass'))
# b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg=='
print(decrypt1(b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg==', b'mypass'))
# b'John Doe'
try: # test with a wrong password
print(decrypt1(b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg==', b'wrongpass'))
except InvalidToken:
print('Wrong password')
You can adapt with your own salt, iteration count, etc. This code is not very far from @HCLivess's answer but the goal is here to have ready-to-use encrypt
and decrypt
functions. Source: https://cryptography.io/en/latest/fernet/#using-passwords-with-fernet.
Note: use .encode()
and .decode()
everywhere if you want strings 'John Doe'
instead of bytes like b'John Doe'
.
Crypto
libraryThis works with Python 3:
import base64
from Crypto import Random
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
def cipherAES(password, iv):
key = SHA256.new(password).digest()
return AES.new(key, AES.MODE_CFB, iv)
def encrypt2(plaintext, password):
iv = Random.new().read(AES.block_size)
return base64.b64encode(iv + cipherAES(password, iv).encrypt(plaintext))
def decrypt2(ciphertext, password):
d = base64.b64decode(ciphertext)
iv, ciphertext = d[:AES.block_size], d[AES.block_size:]
return cipherAES(password, iv).decrypt(ciphertext)
# Example:
print(encrypt2(b'John Doe', b'mypass'))
print(decrypt2(b'B/2dGPZTD8V22cIVKfp2gD2tTJG/UfP/', b'mypass'))
print(decrypt2(b'B/2dGPZTD8V22cIVKfp2gD2tTJG/UfP/', b'wrongpass')) # wrong password: no error, but garbled output
Note: you can remove base64.b64encode
and .b64decode
if you don't want text-readable output and/or if you want to save the ciphertext to disk as a binary file anyway.
Crypto
libraryThe solution 2) with AES "CFB mode" is ok, but has two drawbacks: the fact that SHA256(password)
can be easily bruteforced with a lookup table, and that there is no way to test if a wrong password has been entered. This is solved here by the use of AES in "GCM mode", as discussed in AES: how to detect that a bad password has been entered? and Is this method to say “The password you entered is wrong” secure?:
import Crypto.Random, Crypto.Protocol.KDF, Crypto.Cipher.AES
def cipherAES_GCM(pwd, nonce):
key = Crypto.Protocol.KDF.PBKDF2(pwd, nonce, count=100000)
return Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_GCM, nonce=nonce, mac_len=16)
def encrypt3(plaintext, password):
nonce = Crypto.Random.new().read(16)
return nonce + b''.join(cipherAES_GCM(password, nonce).encrypt_and_digest(plaintext)) # you case base64.b64encode it if needed
def decrypt3(ciphertext, password):
nonce, ciphertext, tag = ciphertext[:16], ciphertext[16:len(ciphertext)-16], ciphertext[-16:]
return cipherAES_GCM(password, nonce).decrypt_and_verify(ciphertext, tag)
# Example:
print(encrypt3(b'John Doe', b'mypass'))
print(decrypt3(b'\xbaN_\x90R\xdf\xa9\xc7\xd6\x16/\xbb!\xf5Q\xa9]\xe5\xa5\xaf\x81\xc3\n2e/("I\xb4\xab5\xa6ezu\x8c%\xa50', b'mypass'))
try:
print(decrypt3(b'\xbaN_\x90R\xdf\xa9\xc7\xd6\x16/\xbb!\xf5Q\xa9]\xe5\xa5\xaf\x81\xc3\n2e/("I\xb4\xab5\xa6ezu\x8c%\xa50', b'wrongpass'))
except ValueError:
print("Wrong password")
Adapted from https://github.com/bozhu/RC4-Python/blob/master/rc4.py.
def PRGA(S):
i = 0
j = 0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
yield S[(S[i] + S[j]) % 256]
def encryptRC4(plaintext, key, hexformat=False):
key, plaintext = bytearray(key), bytearray(plaintext) # necessary for py2, not for py3
S = list(range(256))
j = 0
for i in range(256):
j = (j + S[i] + key[i % len(key)]) % 256
S[i], S[j] = S[j], S[i]
keystream = PRGA(S)
return b''.join(b"%02X" % (c ^ next(keystream)) for c in plaintext) if hexformat else bytearray(c ^ next(keystream) for c in plaintext)
print(encryptRC4(b'John Doe', b'mypass')) # b'\x88\xaf\xc1\x04\x8b\x98\x18\x9a'
print(encryptRC4(b'\x88\xaf\xc1\x04\x8b\x98\x18\x9a', b'mypass')) # b'John Doe'
(Outdated since the latest edits, but kept for future reference): I had problems using Windows + Python 3.6 + all the answers involving pycrypto
(not able to pip install pycrypto
on Windows) or pycryptodome
(the answers here with from Crypto.Cipher import XOR
failed because XOR
is not supported by this pycrypto
fork ; and the solutions using ... AES
failed too with TypeError: Object type <class 'str'> cannot be passed to C code
). Also, the library simple-crypt
has pycrypto
as dependency, so it's not an option.
I have the same problem and found that this is the problem of Microsoft vulnerabilities.
It works for me when I install these update patches. You can find these patches on www.microsoft.com .
If your office 2010 version is SP1, you need download and install office SP2 pack first. Update patch name is KB2687455.
Install update patch KB2965240.
This security update resolves vulnerabilities in Microsoft Office that could allow remote code execution if an attacker convinces a user to open or preview a specially crafted Microsoft Excel workbook in an affected version of Office. An attacker who successfully exploited the vulnerabilities could gain the same user rights as the current user.
Install update patch KB2553154.
A security vulnerability exists in Microsoft Office 2010 32-Bit Edition that could allow arbitrary code to run when a maliciously modified file is opened. This update resolves that vulnerability.
You can try more reusable my solution with callback function. In this function you can use POST request or some logic. Used libraries: JQuery 3> and Bootstrap 3>.
https://jsfiddle.net/axnikitenko/gazbyv8v/
Html code for test:
...
<body>
<a href='#' id="remove-btn-a-id" class="btn btn-default">Test Remove Action</a>
</body>
...
Javascript:
$(function () {
function remove() {
alert('Remove Action Start!');
}
// Example of initializing component data
this.cmpModalRemove = new ModalConfirmationComponent('remove-data', remove,
'remove-btn-a-id', {
txtModalHeader: 'Header Text For Remove', txtModalBody: 'Body For Text Remove',
txtBtnConfirm: 'Confirm', txtBtnCancel: 'Cancel'
});
this.cmpModalRemove.initialize();
});
//----------------------------------------------------------------------------------------------------------------------
// COMPONENT SCRIPT
//----------------------------------------------------------------------------------------------------------------------
/**
* Script processing data for confirmation dialog.
* Used libraries: JQuery 3> and Bootstrap 3>.
*
* @param name unique component name at page scope
* @param callback function which processing confirm click
* @param actionBtnId button for open modal dialog
* @param text localization data, structure:
* > txtModalHeader - text at header of modal dialog
* > txtModalBody - text at body of modal dialog
* > txtBtnConfirm - text at button for confirm action
* > txtBtnCancel - text at button for cancel action
*
* @constructor
* @author Aleksey Nikitenko
*/
function ModalConfirmationComponent(name, callback, actionBtnId, text) {
this.name = name;
this.callback = callback;
// Text data
this.txtModalHeader = text.txtModalHeader;
this.txtModalBody = text.txtModalBody;
this.txtBtnConfirm = text.txtBtnConfirm;
this.txtBtnCancel = text.txtBtnCancel;
// Elements
this.elmActionBtn = $('#' + actionBtnId);
this.elmModalDiv = undefined;
this.elmConfirmBtn = undefined;
}
/**
* Initialize needed data for current component object.
* Generate html code and assign actions for needed UI
* elements.
*/
ModalConfirmationComponent.prototype.initialize = function () {
// Generate modal html and assign with action button
$('body').append(this.getHtmlModal());
this.elmActionBtn.attr('data-toggle', 'modal');
this.elmActionBtn.attr('data-target', '#'+this.getModalDivId());
// Initialize needed elements
this.elmModalDiv = $('#'+this.getModalDivId());
this.elmConfirmBtn = $('#'+this.getConfirmBtnId());
// Assign click function for confirm button
var object = this;
this.elmConfirmBtn.click(function() {
object.elmModalDiv.modal('toggle'); // hide modal
object.callback(); // run callback function
});
};
//----------------------------------------------------------------------------------------------------------------------
// HTML GENERATORS
//----------------------------------------------------------------------------------------------------------------------
/**
* Methods needed for get html code of modal div.
*
* @returns {string} html code
*/
ModalConfirmationComponent.prototype.getHtmlModal = function () {
var result = '<div class="modal fade" id="' + this.getModalDivId() + '"';
result +=' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">';
result += '<div class="modal-dialog"><div class="modal-content"><div class="modal-header">';
result += this.txtModalHeader + '</div><div class="modal-body">' + this.txtModalBody + '</div>';
result += '<div class="modal-footer">';
result += '<button type="button" class="btn btn-default" data-dismiss="modal">';
result += this.txtBtnCancel + '</button>';
result += '<button id="'+this.getConfirmBtnId()+'" type="button" class="btn btn-danger">';
result += this.txtBtnConfirm + '</button>';
return result+'</div></div></div></div>';
};
//----------------------------------------------------------------------------------------------------------------------
// UTILITY
//----------------------------------------------------------------------------------------------------------------------
/**
* Get id element with name prefix for this component.
*
* @returns {string} element id
*/
ModalConfirmationComponent.prototype.getModalDivId = function () {
return this.name + '-modal-id';
};
/**
* Get id element with name prefix for this component.
*
* @returns {string} element id
*/
ModalConfirmationComponent.prototype.getConfirmBtnId = function () {
return this.name + '-confirm-btn-id';
};
This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:
// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));
But if you have to use older version - instead of bugged empty()
you could use:
hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan;
or
import static org.hamcrest.Matchers.greaterThan;
)
Example:
// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));
The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.
If your request is sent by HTTPS you will have an extra server variable named 'HTTPS'
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { //HTTPS }
You may also need the following directive to be set before the first "sub_filter" for backend-servers with data compression:
proxy_set_header Accept-Encoding "";
Otherwise it may not work. For your example it will look like:
location /admin/ {
proxy_pass http://localhost:8080/;
proxy_set_header Accept-Encoding "";
sub_filter "http://your_server/" "http://your_server/admin/";
sub_filter_once off;
}
Use this Code: this method works on 4.3+ and also for below versions too.
try {
Process process = null;
if(Build.VERSION.SDK_INT <= 16) {
// shiny APIS
process = Runtime.getRuntime().exec(
"/system/bin/ping -w 1 -c 1 " + url);
}
else
{
process = new ProcessBuilder()
.command("/system/bin/ping", url)
.redirectErrorStream(true)
.start();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
StringBuffer output = new StringBuffer();
String temp;
while ( (temp = reader.readLine()) != null)//.read(buffer)) > 0)
{
output.append(temp);
count++;
}
reader.close();
if(count > 0)
str = output.toString();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("PING Count", ""+count);
Log.i("PING String", str);
Going off of what Surreal Dreams said, it's probably best to style the anchor tag in my experience, but it really does depend on what you are doing. Here's an example:
Html:
<div class="parent-div">
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
</div>
Then the CSS:
.parent-div {
width: 200px;
}
a {
display:block;
background-color: #ccc;
color: #000;
text-decoration:none;
padding:10px;
margin-bottom:1px;
}
a:hover {
background-color: #ddd;
}
Use dict.setdefault()
:
dic.setdefault(key,[]).append(value)
help(dict.setdefault):
setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
Same issue is also occuring for jcenter.
From 13 Jan 2020 onwards, Jcenter is only available at HTTPS.
Projects getting their dependencies using the same will start facing issues. For quick fixes do the following in your build.gradle
instead of
repositories {
jcenter ()
//others
}
use this:
repositories {
jcenter { url "http://jcenter.bintray.com/"}
//others
}
All modal/lightbox javascript-based systems use an overflow when displaying the modal/lightbox, on html tag or body tag.
When lightbox is show, the js push a overflow hidden on html or body tag. When lightbox is hidden, some remove the hidden other push a overflow auto on html or body tag.
Developers who work on Mac, do not see the problem of the scrollbar.
Just replace the hidden by an unset not to see the content slipping under the modal of the removal of the scrollbar.
Lightbox open/show:
<html style="overflow: unset;"></html>
Lightbox close/hide:
<html style="overflow: auto;"></html>
If you've done something like accidentally npm link
generator-webapp after you've changed it, you can fix it by cloning the right generator and linking that.
git clone https://github.com/yeoman/generator-webapp.git;
# for fixing generator-webapp, replace with your required repository
cd generator-webapp;
npm link;
You can use System.out.printf()
like this if you want to get nicely formatted
System.out.printf("%-20s %s\n", Name, Income);
Prints like:
Jaden 100000.0
Angela 70000.0
Bob 10000.0
This format means:
%-20s -> this is the first argument, Name, left justified and padded to 20 spaces.
%s -> this is the second argument, Income, if income is a decimal swap with %f
\n -> new line character
You could also add formatting to the Income argument so that the number is printed as desired
Check out this for a quick reference
I think the easiest is using csvkit:
Gets the 2nd column:
csvcut -c 2 file.csv
However, there's also csvtool, and probably a number of other csv bash tools out there:
sudo apt-get install csvtool
(for Debian-based systems)
This would return a column with the first row having 'ID' in it.
csvtool namedcol ID csv_file.csv
This would return the fourth row:
csvtool col 4 csv_file.csv
If you want to drop the header row:
csvtool col 4 csv_file.csv | sed '1d'
Using pycairo and librsvg I was able to achieve SVG scaling and rendering to a bitmap. Assuming your SVG is not exactly 256x256 pixels, the desired output, you can read in the SVG to a Cairo context using rsvg and then scale it and write to a PNG.
import cairo
import rsvg
width = 256
height = 256
svg = rsvg.Handle('cool.svg')
unscaled_width = svg.props.width
unscaled_height = svg.props.height
svg_surface = cairo.SVGSurface(None, width, height)
svg_context = cairo.Context(svg_surface)
svg_context.save()
svg_context.scale(width/unscaled_width, height/unscaled_height)
svg.render_cairo(svg_context)
svg_context.restore()
svg_surface.write_to_png('cool.png')
From the Cario website with some minor modification. Also a good example of how to call a C-library from Python
from ctypes import CDLL, POINTER, Structure, byref, util
from ctypes import c_bool, c_byte, c_void_p, c_int, c_double, c_uint32, c_char_p
class _PycairoContext(Structure):
_fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__),
("ctx", c_void_p),
("base", c_void_p)]
class _RsvgProps(Structure):
_fields_ = [("width", c_int), ("height", c_int),
("em", c_double), ("ex", c_double)]
class _GError(Structure):
_fields_ = [("domain", c_uint32), ("code", c_int), ("message", c_char_p)]
def _load_rsvg(rsvg_lib_path=None, gobject_lib_path=None):
if rsvg_lib_path is None:
rsvg_lib_path = util.find_library('rsvg-2')
if gobject_lib_path is None:
gobject_lib_path = util.find_library('gobject-2.0')
l = CDLL(rsvg_lib_path)
g = CDLL(gobject_lib_path)
g.g_type_init()
l.rsvg_handle_new_from_file.argtypes = [c_char_p, POINTER(POINTER(_GError))]
l.rsvg_handle_new_from_file.restype = c_void_p
l.rsvg_handle_render_cairo.argtypes = [c_void_p, c_void_p]
l.rsvg_handle_render_cairo.restype = c_bool
l.rsvg_handle_get_dimensions.argtypes = [c_void_p, POINTER(_RsvgProps)]
return l
_librsvg = _load_rsvg()
class Handle(object):
def __init__(self, path):
lib = _librsvg
err = POINTER(_GError)()
self.handle = lib.rsvg_handle_new_from_file(path.encode(), byref(err))
if self.handle is None:
gerr = err.contents
raise Exception(gerr.message)
self.props = _RsvgProps()
lib.rsvg_handle_get_dimensions(self.handle, byref(self.props))
def get_dimension_data(self):
svgDim = self.RsvgDimensionData()
_librsvg.rsvg_handle_get_dimensions(self.handle, byref(svgDim))
return (svgDim.width, svgDim.height)
def render_cairo(self, ctx):
"""Returns True is drawing succeeded."""
z = _PycairoContext.from_address(id(ctx))
return _librsvg.rsvg_handle_render_cairo(self.handle, z.ctx)
You must define Full-Text-Index
on all tables in database where you require to use a query with CONTAINS
which will take sometime.
Instead you can use the LIKE
which will give you instant results without the need to adjust any settings for the tables.
Example:
SELECT * FROM ChartOfAccounts WHERE AccountName LIKE '%Tax%'
The same result obtained with CONTAINS
can be obtained with LIKE
.
With my first view being MenuViewController
I added:
MenuViewController *menuViewController = [[MenuViewController alloc]init];
self.window.rootViewController = menuViewController;
on the App Delegate method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
}
That worked.
The solution using flexbox without justify-content: space-between
.
<div class="title">
<span>Cumulative performance</span>
<span>20/02/2011</span>
</div>
.title {
display: flex;
}
span:first-of-type {
flex: 1;
}
When we use flex:1
on the first <span>
, it takes up the entire remaining space and moves the second <span>
to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/
Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between
and flexbox with flex:1
on the first <span>
.