In general don't expose List<T>
publicly, and don't provide setters for collection properties. Also, you may want to copy the elements of the passed list (as shown below). Otherwise changes to the original list will affect the Human instance.
public class Human
{
public Human()
{
}
public Human(IEnumerable<ContactNumber> contactNumbers)
{
if (contactNumbers == null)
{
throw new ArgumentNullException("contactNumbers");
}
_contactNumbers.AddRange(contactNumbers);
}
public IEnumerable<ContactNumber> ContactNumbers
{
get { return _contactNumbers; }
}
private readonly List<ContactNumber> _contactNumbers = new List<ContactNumber>();
}
Another option is to use the list constructor that takes a collection and remove the field initializer.
I got the same error in this code:
var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
this was the exactly error:
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'
I solved this way:
var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated
NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory
Just in case for data.table
users, the following works for me:
df[, grep("ABC", names(df)), with = FALSE]
That is usually all that you need to do...
Are you sure that after 20 minutes, the reason that the session is being lost is from being idle though...
There are many reasons as to why the session might be cleared. You can enable event logging for IIS and can then use the event viewer to see reasons why the session was cleared...you might find that it is for other reasons perhaps?
You can also read the documentation for event messages and the associated table of events.
Object coalesce(Object... objects)
{
for(Object o : object)
if(o != null)
return o;
return null;
}
First Rename your AndroidManifest.xml file
android:label="Your App Name"
Second
Rename Your Application Name in Pubspec.yaml file
name: Your Application Name
Third Change Your Application logo
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/path/your Application logo.formate"
Fourth Run
flutter pub pub run flutter_launcher_icons:main
To search all jar files in a given directory for a particular class, you can do this:
ls *.jar | xargs grep -F MyClass
or, even simpler,
grep -F MyClass *.jar
Output looks like this:
Binary file foo.jar matches
It's very fast because the -F option means search for Fixed string, so it doesn't load the the regex engine for each grep invocation. If you need to, you can always omit the -F option and use regexes.
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
Your question title mentions Blocking Queues. However, ConcurrentLinkedQueue
is not a blocking queue.
The BlockingQueue
s are ArrayBlockingQueue
, DelayQueue
, LinkedBlockingDeque
, LinkedBlockingQueue
, PriorityBlockingQueue
, and SynchronousQueue
.
Some of these are clearly not fit for your purpose (DelayQueue
, PriorityBlockingQueue
, and SynchronousQueue
). LinkedBlockingQueue
and LinkedBlockingDeque
are identical, except that the latter is a double-ended Queue (it implements the Deque interface).
Since ArrayBlockingQueue
is only useful if you want to limit the number of elements, I'd stick to LinkedBlockingQueue
.
I was trying to connect an old phone that I use to test apps on older API versions. Today adb was not finding it.
After trying pretty much everything here, I figured out that the phone was not even showing the system notification about the USB connection going on.
So I looked around for that issue, and found the solution here (credits to the original source):
- Remove phone from PC and remove battery to shut off phone.
- Plug USB cable into PC.
- Plug USB cable (other end) into phone.
- The PC install new hardware appropriate drivers for a few minutes (phone without battery)
- Unplug USB cable from phone
- Put battery back in and turn on phone
- As the phone boots, hold down Volume up and down. Phone boots into safe mode.
- Plug USB cable into phone.
- I saw notification about USB MTP-connecting on the phone. PC have found my phone!
- After the reboot in normal mode problem was fixed
Not sure step 4. is of any use here on macOS, however I did all the steps and it worked well.
From Dockerfile reference:
The
ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build command using the--build-arg <varname>=<value>
flag.The
ENV
instruction sets the environment variable<key>
to the value<value>
.
The environment variables set usingENV
will persist when a container is run from the resulting image.
So if you need build-time customization, ARG
is your best choice.
If you need run-time customization (to run the same image with different settings), ENV
is well-suited.
If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable
Given the number of combinations involved, using ENV
to set those features at runtime is best here.
But you can combine both by:
ARG
ARG
as an ENV
That is, with a Dockerfile including:
ARG var
ENV var=${var}
You can then either build an image with a specific var
value at build-time (docker build --build-arg var=xxx
), or run a container with a specific runtime value (docker run -e var=yyy
)
You can get a JSON file that maps country codes to phone codes from http://country.io/phone.json:
...
BD: "880",
BE: "32",
BF: "226",
BG: "359",
BA: "387",
...
If you want country names then http://country.io/names.json will give you that:
...
"AL": "Albania",
"AM": "Armenia",
"AO": "Angola",
"AQ": "Antarctica",
"AR": "Argentina",
...
See http://country.io/data for more details.
Brute Force is the only way!
Here is a script that helped me out:
https://code.google.com/p/android-keystore-password-recover/wiki/HowTo
Using a list of 5-10 possible words from memory, it recovered my password in <1 sec.
The following link explains filters in Angular extremely well. It shows how it is possible to define custom sort logic within an ng-repeat. http://toddmotto.com/everything-about-custom-filters-in-angular-js
For sorting object with properties, this is the code I have used: (Note that this sort is the standard JavaScript sort method and not specific to angular) Column Name is the name of the property on which sorting is to be performed.
self.myArray.sort(function(itemA, itemB) {
if (self.sortOrder === "ASC") {
return itemA[columnName] > itemB[columnName];
} else {
return itemA[columnName] < itemB[columnName];
}
});
It's very simple.
If you want to have something like a glyphicon icon and then "Wish List",
<span class="glyphicon-heart"></span> @Html.ActionLink("Wish List (0)", "Index", "Home")
In command window type
php --ini
It will show you the path something like
Configuration File (php.ini) Path: /usr/local/lib
Loaded Configuration File: /usr/local/lib/php.ini
If the above command does not work then use this
echo phpinfo();
Full version:
<? echo date('F Y'); ?>
Short version:
<? echo date('M Y'); ?>
Here is a good reference for the different date options.
update
To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp
parameter for the date() function. Like this:
echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
This will also work (it's typically used to get the last day of the previous month):
echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));
Hope that helps.
I also received this error when the service stopped. Here's another path to start your service...
Note: As Kenan stated, if your services Startup Type is not set to Automatic, then you probably want to double click on the service and set it to Automatic.
The first four functions you list will work on vectors as well, with the exception that lower_wick needs to be adapted. Something like this,
def lower_wick_vec(o, l, c):
min_oc = numpy.where(o > c, c, o)
return min_oc - l
where o, l and c are vectors. You could do it this way instead which just takes the df as input and avoid using numpy, although it will be much slower:
def lower_wick_df(df):
min_oc = df[['Open', 'Close']].min(axis=1)
return min_oc - l
The other three will work on columns or vectors just as they are. Then you can finish off with
def is_hammer(df):
lw = lower_wick_at_least_twice_real_body(df["Open"], df["Low"], df["Close"])
cl = closed_in_top_half_of_range(df["High"], df["Low"], df["Close"])
return cl & lw
Bit operators can perform set logic on boolean vectors, &
for and
, |
for or
etc. This is enough to completely vectorize the sample calculations you gave and should be relatively fast. You could probably speed up even more by temporarily working with the numpy arrays underlying the data while performing these calculations.
For the second part, I would recommend introducing a column indicating the pattern for each row and writing a family of functions which deal with each pattern. Then groupby the pattern and apply the appropriate function to each group.
I installed pip3
using
python3.7 -m pip install pip
But upon using pip3
to install other dependencies, it was using python3.6.
You can check the by typing pip3 --version
Hence, I used pip3
like this (stated in one of the above answers):
python3.7 -m pip install <module>
or use it like this:
python3.7 -m pip install -r requirements.txt
I made a bash alias for later use in ~/.bashrc file as alias pip3='python3.7 -m pip'
. If you use alias, don't forget to source ~/.bashrc
after making the changes and saving it.
Another approach
=CONCATENATE("Age as of ", TEXT(TODAY(),"dd-mmm-yyyy"))
This will return Age as of 06-Aug-2013
The most Pythonic idiom is to clearly document what the function expects and then just try to use whatever gets passed to your function and either let exceptions propagate or just catch attribute errors and raise a TypeError
instead. Type-checking should be avoided as much as possible as it goes against duck-typing. Value testing can be OK – depending on the context.
The only place where validation really makes sense is at system or subsystem entry point, such as web forms, command line arguments, etc. Everywhere else, as long as your functions are properly documented, it's the caller's responsibility to pass appropriate arguments.
Use a BackgroundWorker. It will allow you to get callbacks on completion and allow you to track progress. You can set the Result value on the event arguments to the resulting value.
public void UseBackgroundWorker()
{
var worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerCompleted += WorkDone;
worker.RunWorkerAsync("input");
}
public void DoWork(object sender, DoWorkEventArgs e)
{
e.Result = e.Argument.Equals("input");
Thread.Sleep(1000);
}
public void WorkDone(object sender, RunWorkerCompletedEventArgs e)
{
var result = (bool) e.Result;
}
Specific actions you can do from SQL client and you don't need to restart anything:
SET GLOBAL log = 'ON';
FLUSH LOGS;
if (function_exists('header_remove')) {
header_remove('X-Powered-By'); // PHP 5.3+
} else {
@ini_set('expose_php', 'off');
}
I know I'm late to the party, but try this...
SELECT
`Train`,
`Dest`,
SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;
Src: Group Concat Documentation
Edit: fixed sql syntax
Take a look at LinkedHashSet class
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.).
This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow.
static byte[] toBytes(String s){
byte[] b=new byte[s.length()*2];
ByteBuffer.wrap(b).asCharBuffer().put(s);
return b;
}
I had the same problem. I tried 'yyyy-mm-dd' format i.e. '2013-26-11' and got rid of this problem...
I had also problems with this. After all these steps made correctly and some fixed misunderstandings (there is no extensions_dir but extension_dir, and there is no sessions.save_path but session.save_path) nothing works.
Finally I found this note at php.net:
Note: Note to Win32 Users: In order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.
So I copied ssleay32.dll, libeay32.dll & php_curl.dll From /PHP to Windows/system32 and replaced already existing files (I noticed there were older versions of ssleay32.dll and libeay32.dll). After that I found CURL section in php_info(); and finally everything works.
Good luck!
ArrayList<Integer> a = new ArrayList<Number>();
Does not work because the fact that Number is a super class of Integer does not mean that List<Number>
is a super class of List<Integer>
. Generics are removed during compilation and do not exist on runtime, so parent-child relationship of collections cannot be be implemented: the information about element type is simply removed.
ArrayList<? extends Object> a1 = new ArrayList<Object>();
a1.add(3);
I cannot explain why it does not work. It is really strange but it is a fact. Really syntax <? extends Object>
is mostly used for return values of methods. Even in this example Object o = a1.get(0)
is valid.
ArrayList<?> a = new ArrayList<?>()
This does not work because you cannot instantiate list of unknown type...
With latest ARC for GET request with authentication need to add a raw header named Authorization:authtoken.
Please find the screen shot Get request with authentication and query params
To add Query param click on drop down arrow on left side of URL box.
Its blank because you are writing to file
. you should write to output
using php://output
instead and also send header information to indicate that it's csv.
Example
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
Assuming your time is called st.etime below and stored in seconds, here is what I use. This handles times where the seconds are greater than 86399 seconds (which is 11:59:59 pm)
case when st.etime > 86399 then to_char(to_date(st.etime - 86400,'sssss'),'HH24:MI:SS') else to_char(to_date(st.etime,'sssss'),'HH24:MI:SS') end readable_time
You can use print -p -- in the script to do this example :
#!/bin/ksh
mysql -u username -ppassword -D dbname -ss -n -q |&
print -p -- "select count(*) from some_table;"
read -p get_row_count1
print -p -- "select count(*) from some_other_table;"
read -p get_row_count2
print -p exit ;
#
echo $get_row_count1
echo $get_row_count2
#
exit
They are not different from the point of view of JVM. Immutable objects don't have methods that can change the instance variables. And the instance variables are private; therefore you can't change it after you create it. A famous example would be String. You don't have methods like setString, or setCharAt. And s1 = s1 + "w" will create a new string, with the original one abandoned. That's my understanding.
let obj1 =[
{ id: 1, submenu_name: 'login' },
{ id: 2, submenu_name: 'Profile',},
{ id: 3, submenu_name: 'password', },
{ id: 4, submenu_name: 'reset',}
] ;
let obj2 =[
{ id: 2},
{ id: 3 },
] ;
// Need Similar obj
const result1 = obj1.filter(function(o1){
return obj2.some(function(o2){
return o1.id == o2.id; // id is unnique both array object
});
});
console.log(result1);
// Need differnt obj
const result2 = obj1.filter(function(o1){
return !obj2.some(function(o2){ // for diffrent we use NOT (!) befor obj2 here
return o1.id == o2.id; // id is unnique both array object
});
});
console.log(result2);
_x000D_
with Showcase/Benchmark App and Source on Github. Also check out the Blur framework I'm currently working on: Dali.
After experimenting a lot I can now safely give you some solid recommendations that will make your life easier in Android when using the Android Framework.
Never use a the full size of a Bitmap. The bigger the image the more needs to be blurred and also the higher the blur radius needs to be and usually, the higher the blur radius the longer the algorithm takes.
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap blurTemplate = BitmapFactory.decodeResource(getResources(), R.drawable.myImage, options);
This will load the bitmap with inSampleSize
8, so only 1/64 of the original image. Test what inSampleSize
suits your needs, but keep it 2^n (2,4,8,...) to avoid degrading quality due to scaling. See Google doc for more
Another really big advantage is that bitmap loading will be really fast. In my early blur testing I figured that the longest time during the whole blur process was the image loading. So to load a 1920x1080 image from disk my Nexus 5 needed 500ms while the blurring only took another 250 ms or so.
Renderscript provides ScriptIntrinsicBlur
which is a Gaussian blur filter. It has good visual quality and is just the fastest you realistically get on Android. Google claims to be "typically 2-3x faster than a multithreaded C implementation and often 10x+ faster than a Java implementation". Renderscript is really sophisticated (using the fastest processing device (GPU, ISP, etc.), etc.) and there is also the v8 support library for it making it compatible down to 2.2. Well at least in theory, through my own tests and reports from other devs it seems that it is not possible to use Renderscript blindly, since the hardware/driver fragmentation seems to cause problems with some devices, even with higher sdk lvl (e.g. I had troubles with the 4.1 Nexus S) so be careful and test on a lot of devices. Here's a simple example that will get you started:
//define this only once if blurring multiple times
RenderScript rs = RenderScript.create(context);
(...)
//this will blur the bitmapOriginal with a radius of 8 and save it in bitmapOriginal
final Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); //use this constructor for best performance, because it uses USAGE_SHARED mode which reuses memory
final Allocation output = Allocation.createTyped(rs, input.getType());
final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setRadius(8f);
script.setInput(input);
script.forEach(output);
output.copyTo(bitmapOriginal);
When using the v8 support with Gradle, which is specifically recommended by Google "because they include the latest improvements", you only need to add 2 lines to your build script and use android.support.v8.renderscript
with current build tools (updated syntax for android Gradle plugin v14+)
android {
...
defaultConfig {
...
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
}
Simple benchmark on a Nexus 5 - comparing RenderScript with different other java and Renderscript implementations:
The average runtime per blur on different pic sizes
Megapixels per sec that can be blurred
Each value is the avg of 250 rounds. RS_GAUSS_FAST
is ScriptIntrinsicBlur
(and nearly always the fastest), others that start with RS_
are mostly convolve implementations with simple kernels. The details of the algorithms can be found here. This is not purely blurring, since a good portion is garbage collection that is measured. This can be seen in this here (ScriptIntrinsicBlur
on a 100x100 image with about 500 rounds)
The spikes are gc.
You can check for yourself, the benchmark app is in the playstore: BlurBenchmark
If you need multiple blurs for a live blur or similar and your memory allows it do not load the bitmap from drawables multiple times, but keep it "cached" in a member variable. In this case always try to use the same variables, to keep garbage collecting to a minimum.
Also check out the new inBitmap
option when loading from a file or drawable which will reuse the bitmap memory and save garbage collection time.
The simple and naive method is just to use 2 ImageViews
, one blurred, and alpha fade them. But if you want a more sophisticated look that smoothly fades from sharp to blurry, then check out Roman Nurik's post about how to do it like in his Muzei app.
Basically he explains that he pre-blurs some frames with different blur extents and uses them as keyframes in an animation that looks really smooth.
I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)
<meta name="304workaround" content="2013-10-24 21:17:23">
Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...
This depends on what you mean by "get the range of selection". If you mean getting the range address (like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.
Sub test()
Dim myString As String
myString = Selection.Address
End Sub
function stripHTML(my_string){
var charArr = my_string.split(''),
resultArr = [],
htmlZone = 0,
quoteZone = 0;
for( x=0; x < charArr.length; x++ ){
switch( charArr[x] + htmlZone + quoteZone ){
case "<00" : htmlZone = 1;break;
case ">10" : htmlZone = 0;resultArr.push(' ');break;
case '"10' : quoteZone = 1;break;
case "'10" : quoteZone = 2;break;
case '"11' :
case "'12" : quoteZone = 0;break;
default : if(!htmlZone){ resultArr.push(charArr[x]); }
}
}
return resultArr.join('');
}
Accounts for > inside attributes and <img onerror="javascript">
in newly created dom elements.
usage:
clean_string = stripHTML("string with <html> in it")
demo:
https://jsfiddle.net/gaby_de_wilde/pqayphzd/
demo of top answer doing the terrible things:
I just want to present a more recent alternative. There is an online tool that generates .gitignore
files based on operating systems, IDEs and programming languages that you might be using.
EDIT Disclaimer: Do not copy this file, copy the file generated by the website instead, they do a good job on keeping it updated. This is just an example.
The file generated for IntelliJ
contains the following
# Created by https://www.gitignore.io/api/intellij
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml
# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
# Gradle:
.idea/gradle.xml
.idea/libraries
# Mongo Explorer plugin:
.idea/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
git pull origin master
will pull changes from the origin
remote, master
branch and merge them to the local checked-out branch.
git pull origin/master
will pull changes from the locally stored branch origin/master
and merge that to the local checked-out branch. The origin/master
branch is essentially a "cached copy" of what was last pulled from origin
, which is why it's called a remote branch in git parlance. This might be somewhat confusing.
You can see what branches are available with git branch
and git branch -r
to see the "remote branches".
You need to use the .toFixed()
method
It takes as a parameter the number of digits to show after the decimal point.
$(document).ready(function() {
$('.add').click(function() {
var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
$('#total').text( value.toFixed(2) );
});
})
Make sure that the actual .vim
file is in ~/.vim/plugin/
If chmod not working then you also try
import os
os.system('sh script.sh')
#you can also use bash instead of sh
test by me thanks
There doesn't seem to be a standard way of organizing Go projects but https://golang.org/doc/code.html specifies a best practice for most projects. jdi's answer is good but if you use github or bitbucket and you have additional libraries as well, you should create the following structure:
~/projects/
bin/
pkg/
src/
github.com/
username/
mypack/
foo.go
bar.go
mypack_test.go
mylib/
utillib.go
utillib_test.go
By doing it this way, you can have a separate repository for mylib that can be used for other projects and can be retrieved by "go get". Your mypack project can import your library using "github.com/username/mylib". For more information:
http://www.alexvictorchan.com/2014/11/06/go-project-structure/
i guess you mean System Programs and Application programs
System Programs makes the hardware run , Applications are for specific tasks
an Example for System Programs are Device Drivers
as for the Applications you can say web browsers , word porcessros etc
To fit image in fullscreen try this:
background-repeat: round;
The main difference is that SurfaceView
can be drawn on by background theads but Views
can't.
SurfaceViews
use more resources though so you don't want to use them unless you have to.
You can use file redirection to redirected the sorted output:
sort input-file > output_file
Or you can use the -o
, --output=FILE
option of sort to indicate the same input and output file:
sort -o file file
Without repeating the filename (with bash brace expansion)
sort -o file{,}
?? Note: A common mistake is to try to redirect the output to the same input file
(e.g. sort file > file
). This does not work as the shell is making the redirections (not the sort(1) program) and the input file (as being the output also) will be erased just before giving the sort(1) program the opportunity of reading it.
Assuming you mean the HTML type RGB codes (called Hex codes, such as #FFCC66), use the ColorTranslator class:
System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");
If, however you are using an ARGB hex code, you can use the ColorConverter class from the System.Windows.Media namespace:
Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
//or = (Color) ColorConverter.ConvertFromString("#FFCC66") ;
This isn't too difficult with a little CSS, and is much better than using an image for the bullet since you can scale it and colour it and it will keep sharp at all resolutions.
Find the character code of the glyphicon by opening the Bootstrap docs and inspecting the character you want to use.
Use that character code in the following CSS
li {
display: block;
}
li:before {
/*Using a Bootstrap glyphicon as the bullet point*/
content: "\e080";
font-family: 'Glyphicons Halflings';
font-size: 9px;
float: left;
margin-top: 4px;
margin-left: -17px;
color: #CCCCCC;
}
You may like to tweak the colour and margins to suit your font size and taste.
string nonNormalized = "\r\n\n\r";
string normalized = nonNormalized.Replace("\r", "\n").Replace("\n", "\r\n");
Check the following example:
// First get your image
$imgPath = 'path-to-your-picture/image.jpg';
$img = base64_encode(file_get_contents($imgPath));
echo '<img width="100" height="100" src="data:image/jpg;base64,'. $img .'" />'
This problem is because the machine can't find the the correct ISAM (indexed sequential driver method) registered that Access needs.
It's probably because the machine doesn't have MSACeesss installed? I would make sure you have the latest version of Jet, and if it still doesn't work, find the file Msrd3x40.dll from one of the other machines, copy it somewhere to the Vista machine and call regsvr32 on it (in Admin mode) that should sort it out for you.
in angular4 foreach like that. try this.
selectChildren(data, $event) {
let parentChecked = data.checked;
this.hierarchicalData.forEach(obj => {
obj.forEach(childObj=> {
value.checked = parentChecked;
});
});
}
I found this funny example in terms of loose coupling:
Source: Understanding dependency injection
Any application is composed of many objects that collaborate with each other to perform some useful stuff. Traditionally each object is responsible for obtaining its own references to the dependent objects (dependencies) it collaborate with. This leads to highly coupled classes and hard-to-test code.
For example, consider a Car
object.
A Car
depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the Car
object.
Without Dependency Injection (DI):
class Car{
private Wheel wh = new NepaliRubberWheel();
private Battery bt = new ExcideBattery();
//The rest
}
Here, the Car
object is responsible for creating the dependent objects.
What if we want to change the type of its dependent object - say Wheel
- after the initial NepaliRubberWheel()
punctures?
We need to recreate the Car object with its new dependency say ChineseRubberWheel()
, but only the Car
manufacturer can do that.
Then what does the Dependency Injection
do for us...?
When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time).
So that we can now change the Wheel
whenever we want. Here, the dependency
(wheel
) can be injected into Car
at run time.
After using dependency injection:
Here, we are injecting the dependencies (Wheel and Battery) at runtime. Hence the term : Dependency Injection. We normally rely on DI frameworks such as Spring, Guice, Weld to create the dependencies and inject where needed.
class Car{
private Wheel wh; // Inject an Instance of Wheel (dependency of car) at runtime
private Battery bt; // Inject an Instance of Battery (dependency of car) at runtime
Car(Wheel wh,Battery bt) {
this.wh = wh;
this.bt = bt;
}
//Or we can have setters
void setWheel(Wheel wh) {
this.wh = wh;
}
}
The advantages are:
$("#pageCSS").attr('href', './css/new_css.css');
There are two methods you can use. Both require creating a user and a database.
By default psql connects to the database with the same name as the user. So there is a convention to make that the "user's database". And there is no reason to break that convention if your user only needs one database. We'll be using mydatabase
as the example database name.
Using createuser and createdb, we can be explicit about the database name,
$ sudo -u postgres createuser -s $USER
$ createdb mydatabase
$ psql -d mydatabase
You should probably be omitting that entirely and letting all the commands default to the user's name instead.
$ sudo -u postgres createuser -s $USER
$ createdb
$ psql
Using the SQL administration commands, and connecting with a password over TCP
$ sudo -u postgres psql postgres
And, then in the psql shell
CREATE ROLE myuser LOGIN PASSWORD 'mypass';
CREATE DATABASE mydatabase WITH OWNER = myuser;
Then you can login,
$ psql -h localhost -d mydatabase -U myuser -p <port>
If you don't know the port, you can always get it by running the following, as the postgres
user,
SHOW port;
Or,
$ grep "port =" /etc/postgresql/*/main/postgresql.conf
postgres
userI suggest NOT modifying the postgres
user.
postgres
. You're supposed to have root to get to authenticate as postgres
.postgres
which is the PostgreSQL equivalent of SQL Server's SA
, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.Interesting/funny way to do this using parameter expansion (requires bash 4.4
or newer):
${parameter@operator} - P operator
The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string.
$ show_time() { local format='\D{%Y%m%d%H%M%S}'; echo "${format@P}"; }
$ show_time
20180724003251
Another oh-so-easy mistake, which was the source of the problem for me: I’d written my own shouldComponentUpdate
method, which didn’t check the new state change I’d added.
I can start service through
am startservice com.xxx/.service.XXXService
but i don't know how to stop it yet.
Your form doesn't contain any input tag other than the file so in your controller action you cannot expect to get anything else than the uploaded file (that's all that's being sent to the server). One way to achieve this would be to include a hidden tag containing the id of the model which will allow you to retrieve it from your datastore inside the controller action you are posting to (use this if the user is not supposed to modify the model but simply attach a file):
@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.HiddenFor(x => x.Id)
<input type="file" name="file" id="file" />
<input type="submit" value="submit" />
}
and then in your controller action:
[HttpPost]
public ActionResult Uploadfile(int id, HttpPostedFileBase file)
{
Containers containers = Repository.GetContainers(id);
...
}
On the other hand if you wanted to allow the user to modify this model then you will need to include the proper input fields for each field of your model that you want to be sent to the server:
@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(x => x.Prop1)
@Html.TextBoxFor(x => x.Prop2)
@Html.TextBoxFor(x => x.Prop3)
<input type="file" name="file" id="file" />
<input type="submit" value="submit" />
}
and then you will have the default model binder reconstruct this model from the request:
[HttpPost]
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file)
{
...
}
open cmd as Administrator then try to register in both location
display:table-row;
will also get rid of the indentation but will remove the bullets.
You could use the bootstrap grid system :
<div class="col-md-6 form-group">
<label for="textbox1">Label1</label>
<input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
<label for="textbox2">Label2</label>
<input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">
http://getbootstrap.com/css/#grid
Is that what you want to achieve?
ShreevatsaR's answer won't work for all cases, even if you add "if(m<0) m=-m;", if you account for negative dividends/divisors.
For example, -12 mod -10 will be 8, and it should be -2.
The following implementation will work for both positive and negative dividends / divisors and complies with other implementations (namely, Java, Python, Ruby, Scala, Scheme, Javascript and Google's Calculator):
internal static class IntExtensions
{
internal static int Mod(this int a, int n)
{
if (n == 0)
throw new ArgumentOutOfRangeException("n", "(a mod 0) is undefined.");
//puts a in the [-n+1, n-1] range using the remainder operator
int remainder = a%n;
//if the remainder is less than zero, add n to put it in the [0, n-1] range if n is positive
//if the remainder is greater than zero, add n to put it in the [n-1, 0] range if n is negative
if ((n > 0 && remainder < 0) ||
(n < 0 && remainder > 0))
return remainder + n;
return remainder;
}
}
Test suite using xUnit:
[Theory]
[PropertyData("GetTestData")]
public void Mod_ReturnsCorrectModulo(int dividend, int divisor, int expectedMod)
{
Assert.Equal(expectedMod, dividend.Mod(divisor));
}
[Fact]
public void Mod_ThrowsException_IfDivisorIsZero()
{
Assert.Throws<ArgumentOutOfRangeException>(() => 1.Mod(0));
}
public static IEnumerable<object[]> GetTestData
{
get
{
yield return new object[] {1, 1, 0};
yield return new object[] {0, 1, 0};
yield return new object[] {2, 10, 2};
yield return new object[] {12, 10, 2};
yield return new object[] {22, 10, 2};
yield return new object[] {-2, 10, 8};
yield return new object[] {-12, 10, 8};
yield return new object[] {-22, 10, 8};
yield return new object[] { 2, -10, -8 };
yield return new object[] { 12, -10, -8 };
yield return new object[] { 22, -10, -8 };
yield return new object[] { -2, -10, -2 };
yield return new object[] { -12, -10, -2 };
yield return new object[] { -22, -10, -2 };
}
}
I guess something like this would work:
Add System.ServiceProcess
to your project references (It's on the .NET tab).
using System.ServiceProcess;
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
Edit: There is also a method sc.WaitforStatus()
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first.
Reference: ServiceController object in .NET.
when you paste into Word, the formating/formula of excel still exists. Simply click the clip board and select the option "keep text only."
Don't know exactly what kind of dataset you have, so I provide general answer.
x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
x y
1 1 1
2 2 2
3 NA 3
4 3 NA
5 4 6
6 5 8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
x y
1 1 1
2 2 2
5 4 6
6 5 8
Declare password like DB_PASSWORD="2o0@#5TGR1NG" in .env file
If # sign include in your password then password will declare in between " ".
ROBOCOPY works great for me. Originally suggested my Iman. But instead of moving the files/folders to a temporary directory then deleting the contents of the temporary folder, move the files to the trash!!!
This is is a few lines of my backup batch file for example:
SET FilesToClean1=C:\Users\pauls12\Temp
SET FilesToClean2=C:\Users\pauls12\Desktop\1616 - Champlain\Engineering\CAD\Backups
SET RecycleBin=C:\$Recycle.Bin\S-1-5-21-1480896384-1411656790-2242726676-748474
robocopy "%FilesToClean1%" "%RecycleBin%" /mov /MINLAD:15 /XA:SH /NC /NDL /NJH /NS /NP /NJS
robocopy "%FilesToClean2%" "%RecycleBin%" /mov /MINLAD:30 /XA:SH /NC /NDL /NJH /NS /NP /NJS
It cleans anything older than 15 days out of my 'Temp' folder and 30 days for anything in my AutoCAD backup folder. I use variables because the line can get quite long and I can reuse them for other locations. You just need to find the dos path to your recycle bin associated with your login.
This is on a work computer for me and it works. I understand that some of you may have more restrictive rights but give it a try anyway;) Search Google for explanations on the ROBOCOPY parameters.
Cheers!
Why don't you try this
for(int i=0; i < dt.Rows.Count; i++)
{
// u can use here the i
}
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
Well it depends, if you want to bind datas, there shouldn't be any formatting in it, otherwise you can bind-html
and do description.replace(/\\n/g, '<br>')
not sure it's what you want though.
Use a variable and call clearInterval
to stop it.
var interval;
$(document).on('ready',function()
interval = setInterval(updateDiv,3000);
});
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
$.playSound('oneday.wav');
$('.square').html('<span style="color:red">Connection problems</span>');
// I want to stop it here
clearInterval(interval);
}
});
}
I believe what you want is:
SELECT ItemName, GROUP_CONCAT(DepartmentId) FROM table_name GROUP BY ItemName
If you're using MySQL
Reference
Never and forever are two words that I avoid using due to the unpredictability of life.
The latest time since 1 January 1970
that can be stored using a signed 32-bit
integer is 03:14:07 on Tuesday, 19 January 2038
(231-1 = 2,147,483,647
seconds after 1 January 1970
). This limitation is known as the Year 2038 problem
setCookie("name", "value", strtotime("2038-01-19 03:14:07"));
you can use super while extending Exception
if (pass.length() < minPassLength)
throw new InvalidPassException("The password provided is too short");
} catch (NullPointerException e) {
throw new InvalidPassException("No password provided", e);
}
// A custom business exception
class InvalidPassException extends Exception {
InvalidPassException() {
}
InvalidPassException(String message) {
super(message);
}
InvalidPassException(String message, Throwable cause) {
super(message, cause);
}
}
}
Try setting mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
or
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
depending on your Jackson version.
IEEE 754 defines 1.0 / 0.0
as Infinity and -1.0 / 0.0
as -Infinity and 0.0 / 0.0
as NaN.
By the way, floating point values also have -0.0
and so 1.0/ -0.0
is -Infinity
.
Integer arithmetic doesn't have any of these values and throws an Exception instead.
To check for all possible values (e.g. NaN, 0.0, -0.0) which could produce a non finite number you can do the following.
if (Math.abs(tab[i] = 1 / tab[i]) < Double.POSITIVE_INFINITY)
throw new ArithmeticException("Not finite");
For folks who find this posting through the search engines, another possible cause of this problem is from importing the wrong package version of @Transient
. Make sure that you import javax.persistence.transient
and not some other package.
Easier still: return a pointer to a string that's been malloc'd with strdup.
#include <ncurses.h>
char * getStr(int length)
{
char word[length];
for (int i = 0; i < length; i++)
{
word[i] = getch();
}
word[i] = '\0';
return strdup(&word[0]);
}
int main()
{
char wordd[10];
initscr();
*wordd = getStr(10);
printw("The string is:\n");
printw("%s\n",*wordd);
getch();
endwin();
return 0;
}
In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow
String nullName = null;
String name = Optional.ofNullable(nullName)
.orElseThrow(NullPointerException::new);
// .orElseThrow(CustomException::new);
Good suggestion, however, nt so accurate in all cases. I figure one out. Please you need to make sure you run "enable-migrations" using PM windows in Visual Studio, and Migration folder would be added to you project.
Make sure the two c# class files added to the folder on will contain all your models and their respective properties.
If you have all that build the solution, and publis for deployment.
The logic is that the existing metadata cannot be overwritten because your application has no metadata to replace the current. As a result you are getting this error "The model backing the context has changed since the database was created"
It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.
Even though you are using ASMM, you can set a minimum size for the large pool (MMAN will not shrink it below that value). You can also try pinning some objects and increasing SGA_TARGET.
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
In case you also need to execute some command in the cmd.exe, you can do the following:
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C vol";
p.Start();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
This returns just the output of the command itself:
You can also use StandardInput
instead of StartInfo.Arguments
:
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.Start();
// Read the output stream first and then wait.
p.StandardInput.WriteLine("vol");
p.StandardInput.WriteLine("exit");
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
The result looks like this:
I just had a very similar issues with gradle builds / adding .jar library. I got it working by a combination of :
compile fileTree(dir: 'libs', include: '*.jar')}
BUT more importantly and annoyingly, only hours after I get it working, Android Studio have just released 0.3.7, which claims to have solved a lot of gradle issues such as adding .jar libraries
http://tools.android.com/recent
Hope this helps people!
There's a great example in the AngularJS docs.
It's very well commented and should get you pointed in the right direction.
A simple example, maybe more so what you're looking for is below:
HTML
<div ng-app="myDirective" ng-controller="x">
<input type="text" ng-model="test" my-directive>
</div>
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.ngModel, function (v) {
console.log('value changed, new value is: ' + v);
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
Edit: Same thing, doesn't require ngModel
jsfiddle:
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
scope: {
myDirective: '='
},
link: function (scope, element, attrs) {
// set the initial value of the textbox
element.val(scope.myDirective);
element.data('old-value', scope.myDirective);
// detect outside changes and update our input
scope.$watch('myDirective', function (val) {
element.val(scope.myDirective);
});
// on blur, update the value in scope
element.bind('propertychange keyup paste', function (blurEvent) {
if (element.data('old-value') != element.val()) {
console.log('value changed, new value is: ' + element.val());
scope.$apply(function () {
scope.myDirective = element.val();
element.data('old-value', element.val());
});
}
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
This answer will help in case, If you are working with Data Bases then mostly take the help of try-catch block statement, which will help and guide you with your code. Here i am showing you that how to insert some values in Data Base with a Button Click Event.
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}
A BLOB is a Binary Large OBject. It is used to store large quantities of binary data in a database.
You can use it to store any kind of binary data that you want, includes images, video, or any other kind of binary data that you wish to store.
Different DBMSes treat BLOBs in different ways; you should read the documentation of the databases you are interested in to see how (and if) they handle BLOBs.
TL;DR - Just run this and don't disable your security:
Replace existing certs
# Windows/MacOS/Linux
npm config set cafile "<path to your certificate file>"
# Check the 'cafile'
npm config get cafile
or extend existing certs
Set this environment variable to extend pre-defined certs:
NODE_EXTRA_CA_CERTS
to "<path to certificate file>"
I've had to work with npm, pip, maven etc. behind a corporate firewall under Windows - it's not fun. I'll try and keep this platform agnostic/aware where possible.
HTTP_PROXY
& HTTPS_PROXY
are environment variables used by lots of software to know where your proxy is. Under Windows, lots of software also uses your OS specified proxy which is a totally different thing. That means you can have Chrome (which uses the proxy specified in your Internet Options) connecting to the URL just fine, but npm, pip, maven etc. not working because they use HTTPS_PROXY (except when they use HTTP_PROXY - see later). Normally the environment variable would look something like:
http://proxy.example.com:3128
But you're getting a 403 which suggests you're not being authenticated against your proxy. If it is basic authentication on the proxy, you'll want to set the environment variable to something of the form:
http://user:[email protected]:3128
There is an HTTP status code 407 (proxy authentication required), which is the more correct way of saying it's the proxy rather than the destination server that's rejecting your request. That code plagued me for the longest time until after a lot of time on Google, I learned my proxy used NTLM authentication. HTTP basic authentication wasn't enough to satisfy whatever proxy my corporate overlords had installed. I resorted to using Cntlm on my local machine (unauthenticated), then had it handle the NTLM authentication with the upstream proxy. Then I had to tell all the programs that couldn't do NTLM to use my local machine as the proxy - which is generally as simple as setting HTTP_PROXY
and HTTPS_PROXY
. Otherwise, for npm use (as @Agus suggests):
npm config set proxy http://proxy.example.com:3128
npm config set https-proxy http://proxy.example.com:3128
After this set-up had been humming along (clunkily) for about a year, the corporate overlords decided to change the proxy. Not only that, but it would no longer use NTLM! A brave new world to be sure. But because those writers of malicious software were now delivering malware via HTTPS, the only way they could protect we poor innocent users was to man-in-the-middle every connection to scan for threats before they even reached us. As you can imagine, I was overcome with the feeling of safety.
To cut a long story short, the self-signed certificate needs to be installed into npm to avoid SELF_SIGNED_CERT_IN_CHAIN
:
npm config set cafile "<path to certificate file>"
Alternatively, the NODE_EXTRA_CA_CERTS
environment variable can be set to the certificate file.
I think that's everything I know about getting npm to work behind a proxy/firewall. May someone find it useful.
Edit: It's a really common suggestion to turn off HTTPS for this problem either by using an HTTP registry or setting NODE_TLS_REJECT_UNAUTHORIZED
. These are not good ideas because you're opening yourself up to further man-in-the-middle or redirection attacks. A quick spoof of your DNS records on the machine doing the package installation and you'll find yourself trusting packages from anywhere. It may seem like a lot of work to make HTTPS work, but it is highly recommended. When you're the one responsible for allowing untrusted code into the company, you'll understand why.
Edit 2:
Keep in mind that setting npm config set cafile <path>
causes npm to only use the certs provided in that file, instead of extending the existing ones with it.
If you want to extend the existing certs (e.g. with a company cert) using the environment variable NODE_EXTRA_CA_CERTS
to link to the file is the way to go and can save you a lot of hassle. See how-to-add-custom-certificate-authority-ca-to-nodejs
Place your script
inside the body tag
<body>
// Rest of html
<script>
function hideButton() {
$(".loading").hide();
}
function showButton() {
$(".loading").show();
}
</script>
< /body>
If you check this JSFIDDLE and click on javascript, you will see the load Type body
is selected
I tried all the above solutions.I came up solving the issue.Here I am posting the full solution.
The xml file:
<RelativeLayout
android:id="@+id/header_main_page_clist1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:paddingBottom="10dp"
android:background="#ffffff" >
<ListView
android:id="@+id/lv_msglist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@color/divider_color"
android:dividerHeight="1dp" />
<TextView
android:id="@+id/emptyElement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="NO MESSAGES AVAILABLE!"
android:textColor="#525252"
android:textSize="19.0sp"
android:visibility="gone" />
</RelativeLayout>
The textView ("@+id/emptyElement") is the placeholder for the empty listview.
Here is the code for java page:
lvmessage=(ListView)findViewById(R.id.lv_msglist);
lvmessage.setAdapter(adapter);
lvmessage.setEmptyView(findViewById(R.id.emptyElement));
Remember to place the emptyView after binding the adapter to listview.Mine was not working for first time and after I moved the setEmptyView after the setAdapter it is now working.
Output:
There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.
However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.
Clément's answer is by far the best. Here's a somewhat improved answer, showing different possible alignments, including left-center-right aligned buttons:
label_x000D_
{ padding-right:8px;_x000D_
}_x000D_
_x000D_
.FAligned,.FAlignIn_x000D_
{ display:table;_x000D_
}_x000D_
_x000D_
.FAlignIn_x000D_
{ width:100%;_x000D_
}_x000D_
_x000D_
.FRLeft,.FRRight,.FRCenter_x000D_
{ display:table-row;_x000D_
white-space:nowrap;_x000D_
}_x000D_
_x000D_
.FCLeft,.FCRight,.FCCenter_x000D_
{ display:table-cell;_x000D_
}_x000D_
_x000D_
.FRLeft,.FCLeft,.FILeft_x000D_
{ text-align:left;_x000D_
}_x000D_
_x000D_
.FRRight,.FCRight,.FIRight_x000D_
{ text-align:right;_x000D_
}_x000D_
_x000D_
.FRCenter,.FCCenter,.FICenter_x000D_
{ text-align:center;_x000D_
}
_x000D_
<form class="FAligned">_x000D_
<div class="FRLeft">_x000D_
<p class="FRLeft">_x000D_
<label for="Input0" class="FCLeft">Left:</label>_x000D_
<input id="Input0" type="text" size="30" placeholder="Left Left Left" class="FILeft"/>_x000D_
</p>_x000D_
<p class="FRLeft">_x000D_
<label for="Input1" class="FCRight">Left Right Left:</label>_x000D_
<input id="Input1" type="text" size="30" placeholder="Left Right Left" class="FILeft"/>_x000D_
</p>_x000D_
<p class="FRRight">_x000D_
<label for="Input2" class="FCLeft">Right Left Left:</label>_x000D_
<input id="Input2" type="text" size="30" placeholder="Right Left Left" class="FILeft"/>_x000D_
</p>_x000D_
<p class="FRRight">_x000D_
<label for="Input3" class="FCRight">Right Right Left:</label>_x000D_
<input id="Input3" type="text" size="30" placeholder="Right Right Left" class="FILeft"/>_x000D_
</p>_x000D_
<p class="FRLeft">_x000D_
<label for="Input4" class="FCLeft">Left Left Right:</label>_x000D_
<input id="Input4" type="text" size="30" placeholder="Left Left Right" class="FIRight"/>_x000D_
</p>_x000D_
<p class="FRLeft">_x000D_
<label for="Input5" class="FCRight">Left Right Right:</label>_x000D_
<input id="Input5" type="text" size="30" placeholder="Left Right Right" class="FIRight"/>_x000D_
</p>_x000D_
<p class="FRRight">_x000D_
<label for="Input6" class="FCLeft">Right Left Right:</label>_x000D_
<input id="Input6" type="text" size="30" placeholder="Right Left Right" class="FIRight"/>_x000D_
</p>_x000D_
<p class="FRRight">_x000D_
<label for="Input7" class="FCRight">Right:</label>_x000D_
<input id="Input7" type="text" size="30" placeholder="Right Right Right" class="FIRight"/>_x000D_
</p>_x000D_
<p class="FRCenter">_x000D_
<label for="Input8" class="FCCenter">And centralised is also possible:</label>_x000D_
<input id="Input8" type="text" size="60" placeholder="Center in the centre" class="FICenter"/>_x000D_
</p>_x000D_
</div>_x000D_
<div class="FAlignIn">_x000D_
<div class="FRCenter">_x000D_
<div class="FCLeft"><button type="button">Button on the Left</button></div>_x000D_
<div class="FCCenter"><button type="button">Button on the Centre</button></div>_x000D_
<div class="FCRight"><button type="button">Button on the Right</button></div>_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
I added some padding on the right of all labels (padding-right:8px
) just to make the example slight less horrible looking, but that should be done more carefully in a real project (adding padding to all other elements would also be a good idea).
Encryption and hash algorithms work in similar ways. In each case, there is a need to create confusion and diffusion amongst the bits. Boiled down, confusion is creating a complex relationship between the key and the ciphertext, and diffusion is spreading the information of each bit around.
Many hash functions actually use encryption algorithms (or primitives of encryption algorithms. For example, the SHA-3 candidate Skein uses Threefish as the underlying method to process each block. The difference is that instead of keeping each block of ciphertext, they are destructively, deterministically merged together to a fixed length
CharSequence
is a contract (interface), and String
is an implementation of this contract.
public final class String extends Object
implements Serializable, Comparable<String>, CharSequence
The documentation for CharSequence
is:
A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details.
public static Integer valueOf(String s)
The result is an Integer object that represents the integer value specified by the string.
In other words, this method returns an Integer object equal to the value of: new Integer(Integer.parseInt(s))
Create unique constraint that two numbers together CANNOT together be repeated:
ALTER TABLE someTable
ADD UNIQUE (col1, col2)
On CentOS 7, try running following command:
sudo yum install php72u-gd.x86_64
In particular if you need recursive clone
GIT_SSL_NO_VERIFY=true git clone --recursive https://github.com/xx/xx.git
Following up on these solutions, here is some helpful code illustrating :
#
# Copying columns in pandas without slice warning
#
import numpy as np
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))
#
# copies column B into new column D
df.loc[:,'D'] = df['B']
print df
#
# creates new column 'E' with values -99
#
# But copy command replaces those where 'B'>0 while others become NaN (not copied)
df['E'] = -99
print df
df['E'] = df[df['B']>0]['B'].copy()
print df
#
# creates new column 'F' with values -99
#
# Copy command only overwrites values which meet criteria 'B'>0
df['F']=-99
df.loc[df['B']>0,'F'] = df[df['B']>0]['B'].copy()
print df
Is to do with IPv6
All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx
Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...
I ran into a similar limitation with DataTriggers, and it would seem that you can only check for equality. The closest thing I've seen that might help you is a technique for doing other types of comparisons other than equality.
This blog post describes how to do comparisons such as LT, GT, etc in a DataTrigger.
This limitation of the DataTrigger can be worked around to some extent by using a Converter to massage the data into a special value you can then compare against, as suggested in Robert Macnee's answer.
If the table is InnoDB, see http://dev.mysql.com/doc/refman/5.1/en/innodb-consistent-read.html -- it uses consistent-read (no-locking mode) for SELECTs "that do not specify FOR UPDATE or LOCK IN SHARE MODE if the innodb_locks_unsafe_for_binlog option is set and the isolation level of the transaction is not set to SERIALIZABLE. Thus, no locks are set on rows read from the selected table".
If you really don't like the Terminal here is the GUI way to do dkamins is telling you :
1) Go to your user home directory (ludo would be mine) and from the File menu choose Get Info cmdI in the inspector :
2) By alt/option clicking on the [+] sign add the _www group and set it's permission to read-only :
3) Show the Get Info inspector of your user Sites folder and reproduce step 2 then from the gear action sub-menu choose Apply to enclosed Items... :
Voilà 3 steps and the GUI only way...
I recognized those screens, I'm using CodeFluentEntities, and I've got solution that worked for me as well.
I'm using that construction:
$.ajax({
url: path,
type: "POST",
contentType: "text/plain",
data: {"some":"some"}
}
as you can see, if I use
contentType: "",
or
contentType: "text/plain", //chrome
Everything works fine.
I'm not 100% sure that it's all that you need, cause I've also changed headers.
if your using sqlsrv_connect you have to download and install MS sql driver for your php. download it here http://www.microsoft.com/en-us/download/details.aspx?id=20098 extract it to your php folder or ext in xampp folder then add this on the end of the line in your php.ini file
extension=php_pdo_sqlsrv_55_ts.dll
extension=php_sqlsrv_55_ts.dll
im using xampp version 5.5 so its name php_pdo_sqlsrv_55_ts.dll & php_sqlsrv_55_ts.dll
if you are using xampp version 5.5 dll files is not included in the link...hope it helps
Check out also the --sig-proxy
option:
docker attach --sig-proxy=false 304f5db405ec
Then use CTRL+c to detach
Another way of doing it is by using isdigit function. Below is the code for it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
char input[MAXINPUT] = "";
int length,i;
scanf ("%s", input);
length = strlen (input);
for (i=0;i<length; i++)
if (!isdigit(input[i]))
{
printf ("Entered input is not a number\n");
exit(1);
}
printf ("Given input is a number\n");
}
You can't.
The only way to set the value of a file input is by the user to select a file.
This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.
The difference is substantial for many applications. If you are currently constrained by storage throughput, particularly when reading data, BitLocker will slow you down.
It would be useful to compare with other software based whole disk or whole partition encryption like TrueCrypt (which has the advantage if you dual boot with Linux since it works for both Windows and Linux).
A much better option is to use hardware encryption, which is available in many SSDs as well as in Hitachi 7200 RPM HDD. The performance of encrypted v. not is undetectable, and the encryption is invisible to operating systems. If you have a decent laptop, you can use the built-in security functions to generate and store the key, which your password unlocks from the encrypted key storage of the laptop.
zoom is a css3 spec for the @viewport descriptor, as described here
http://dev.w3.org/csswg/css-device-adapt/#zoom-desc
used to zoom the entire viewport ('screen'). it also happens to zoom individuals elements in a lot of browsers, but not all. css3 specifies transform:scale should be used to achieve such an effect:
http://www.w3.org/TR/css3-transforms/#transform-functions
but it works a little different than the 'element zoom' in those browsers that support it.
I agree with Thomas and I would choose the DECIMAL(5,4) solution at least for WPF applications.
Have a look to the MSDN Numeric Format String to know why : http://msdn.microsoft.com/en-us/library/dwhawy9k#PFormatString
The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage.
Then you would be able to use this in your XAML code:
DataFormatString="{}{0:P}"
I ran into a similar problem while creating a library to handle authentication. I want the app owner using my library to be able to register a callback with the library for checking authorization against LDAP groups the authenticated person is in. The configuration is getting passed in as a config.py file that gets imported and contains a dict with all the config parameters.
I got this to work:
>>> class MyClass(object):
... def target_func(self):
... print "made it!"
...
... def __init__(self,config):
... self.config = config
... self.config['funcname'] = getattr(self,self.config['funcname'])
... self.config['funcname']()
...
>>> instance = MyClass({'funcname':'target_func'})
made it!
Is there a pythonic-er way to do this?
Check the return value of find
against end
.
map<int, Bar>::iterator it = m.find('2');
if ( m.end() != it ) {
// contains
...
}
You could filter the file through cat -n
before piping to less
:
cat -n file.txt | less
Or, if your version of less
supports it, the -N
option:
less -N file.txt
Visual Studio 2003 - 2008 (Visual C++ 7.1 - 9) don't claim to be C99 compatible. (Thanks to rdentato for his comment.)
Just in case someone comes here trying to know how to create a tuple assigning each part of the string "Quattro" and "TT" to an element of the list, it would be like this
print tuple(a.split())
This is just because the application is built in non unicode language fonts and you are running the system on unicode fonts. change your default non unicode fonts to arabic by going in regional settings advanced tab in control panel. That will solve your problem.
To roll back all migrations up to a particular version (e.g. 20181002222222
), use:
rake db:migrate VERSION=20181002222222
(Note that this uses db:migrate
-- not db:migrate:down
as in other answers to this question.)
Assuming the specified migration version is older than the current version, this will roll back all migrations up to, but not including, the specified version.
For example, if rake db:migrate:status
initially displays:
(... some older migrations ...)
up 20181001002039 Some migration description
up 20181002222222 Some migration description
up 20181003171932 Some migration description
up 20181004211151 Some migration description
up 20181005151403 Some migration description
Running:
rake db:migrate VERSION=20181002222222
Will result in:
(... some older migrations ...)
up 20181001002039 Some migration description
up 20181002222222 Some migration description
down 20181003171932 Some migration description
down 20181004211151 Some migration description
down 20181005151403 Some migration description
Reference: https://makandracards.com/makandra/845-migrate-or-revert-only-some-migrations
If you want to add 2px padding around the textRect, just do this:
let insets = UIEdgeInsets(top: -2, left: -2, bottom: -2, right: -2)
label.frame = UIEdgeInsetsInsetRect(textRect, insets)
window_handles
should give you the references to all open windows.
this is what the docu has to say about switching windows.
Accessing direct properties and related are explained
// Get an instance of the WC_Order object
$order = wc_get_order($order_id);
$order_data = array(
'order_id' => $order->get_id(),
'order_number' => $order->get_order_number(),
'order_date' => date('Y-m-d H:i:s', strtotime(get_post($order->get_id())->post_date)),
'status' => $order->get_status(),
'shipping_total' => $order->get_total_shipping(),
'shipping_tax_total' => wc_format_decimal($order->get_shipping_tax(), 2),
'fee_total' => wc_format_decimal($fee_total, 2),
'fee_tax_total' => wc_format_decimal($fee_tax_total, 2),
'tax_total' => wc_format_decimal($order->get_total_tax(), 2),
'cart_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_cart_discount(), 2),
'order_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_order_discount(), 2),
'discount_total' => wc_format_decimal($order->get_total_discount(), 2),
'order_total' => wc_format_decimal($order->get_total(), 2),
'order_currency' => $order->get_currency(),
'payment_method' => $order->get_payment_method(),
'shipping_method' => $order->get_shipping_method(),
'customer_id' => $order->get_user_id(),
'customer_user' => $order->get_user_id(),
'customer_email' => ($a = get_userdata($order->get_user_id() )) ? $a->user_email : '',
'billing_first_name' => $order->get_billing_first_name(),
'billing_last_name' => $order->get_billing_last_name(),
'billing_company' => $order->get_billing_company(),
'billing_email' => $order->get_billing_email(),
'billing_phone' => $order->get_billing_phone(),
'billing_address_1' => $order->get_billing_address_1(),
'billing_address_2' => $order->get_billing_address_2(),
'billing_postcode' => $order->get_billing_postcode(),
'billing_city' => $order->get_billing_city(),
'billing_state' => $order->get_billing_state(),
'billing_country' => $order->get_billing_country(),
'shipping_first_name' => $order->get_shipping_first_name(),
'shipping_last_name' => $order->get_shipping_last_name(),
'shipping_company' => $order->get_shipping_company(),
'shipping_address_1' => $order->get_shipping_address_1(),
'shipping_address_2' => $order->get_shipping_address_2(),
'shipping_postcode' => $order->get_shipping_postcode(),
'shipping_city' => $order->get_shipping_city(),
'shipping_state' => $order->get_shipping_state(),
'shipping_country' => $order->get_shipping_country(),
'customer_note' => $order->get_customer_note(),
'download_permissions' => $order->is_download_permitted() ? $order->is_download_permitted() : 0,
);
Additional details
$line_items_shipping = $order->get_items('shipping');
foreach ($line_items_shipping as $item_id => $item) {
if (is_object($item)) {
if ($meta_data = $item->get_formatted_meta_data('')) :
foreach ($meta_data as $meta_id => $meta) :
if (in_array($meta->key, $line_items_shipping)) {
continue;
}
// html entity decode is not working preoperly
$shipping_items[] = implode('|', array('item:' . wp_kses_post($meta->display_key), 'value:' . str_replace('×', 'X', strip_tags($meta->display_value))));
endforeach;
endif;
}
}
//get fee and total
$fee_total = 0;
$fee_tax_total = 0;
foreach ($order->get_fees() as $fee_id => $fee) {
$fee_items[] = implode('|', array(
'name:' . html_entity_decode($fee['name'], ENT_NOQUOTES, 'UTF-8'),
'total:' . wc_format_decimal($fee['line_total'], 2),
'tax:' . wc_format_decimal($fee['line_tax'], 2),
));
$fee_total += $fee['line_total'];
$fee_tax_total += $fee['line_tax'];
}
// get tax items
foreach ($order->get_tax_totals() as $tax_code => $tax) {
$tax_items[] = implode('|', array(
'rate_id:'.$tax->id,
'code:' . $tax_code,
'total:' . wc_format_decimal($tax->amount, 2),
'label:'.$tax->label,
'tax_rate_compound:'.$tax->is_compound,
));
}
// add coupons
foreach ($order->get_items('coupon') as $_ => $coupon_item) {
$coupon = new WC_Coupon($coupon_item['name']);
$coupon_post = get_post((WC()->version < '2.7.0') ? $coupon->id : $coupon->get_id());
$discount_amount = !empty($coupon_item['discount_amount']) ? $coupon_item['discount_amount'] : 0;
$coupon_items[] = implode('|', array(
'code:' . $coupon_item['name'],
'description:' . ( is_object($coupon_post) ? $coupon_post->post_excerpt : '' ),
'amount:' . wc_format_decimal($discount_amount, 2),
));
}
foreach ($order->get_refunds() as $refunded_items){
$refund_items[] = implode('|', array(
'amount:' . $refunded_items->get_amount(),
'reason:' . $refunded_items->get_reason(),
'date:'. date('Y-m-d H-i-s',strtotime((WC()->version < '2.7.0') ? $refunded_items->date_created : $refunded_items->get_date_created())),
));
}
This is happening due to the fact that the logging level of your logger is set to 'error' - therefore you will only see error messages or above this level in terms of severity so this is why you also see the 'fatal' message.
If you set the logging level to 'debug' on your logger in your log4j.xml you should see all messages.
Have a look at the log4j introduction for explaination.
Actually you can do with VS Code the following:
You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.
$(window).scroll(function () {
var Bottom = $(window).height() + $(window).scrollTop() >= $(document).height();
if(Bottom )
{
$('#div').hide();
}
});
EDIT:
The point with the nulls in the array has been cleared. Sorry for my comments.
Original:
Ehm... the line
array = list.toArray(array);
replaces all gaps in the array where the removed element has been with null. This might be dangerous, because the elements are removed, but the length of the array remains the same!
If you want to avoid this, use a new Array as parameter for toArray(). If you don`t want to use removeAll, a Set would be an alternative:
String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
System.out.println(Arrays.toString(array));
Set<String> asSet = new HashSet<String>(Arrays.asList(array));
asSet.remove("a");
array = asSet.toArray(new String[] {});
System.out.println(Arrays.toString(array));
Gives:
[a, bc, dc, a, ef]
[dc, ef, bc]
Where as the current accepted answer from Chris Yester Young outputs:
[a, bc, dc, a, ef]
[bc, dc, ef, null, ef]
with the code
String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
System.out.println(Arrays.toString(array));
List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);
System.out.println(Arrays.toString(array));
without any null values left behind.
This depends on what function1 is doing.
If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.
If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:
function1()
{
new AjaxCall(ajaxOptions, MyCallback);
}
function MyCallback(result)
{
function2(result);
}
RealVNC 5.0.x now offers a VNCViewer that will do dual displays on Windows without having to buy a license. (Licensing now covers the SERVER portion of their tools).
based on @fabien-snauwaert's answer but simplified if you do not need the original key
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_values( $array ) as $index=>$value ) {
// display the current index + value
echo $index . ':' . $value;
// first index
if ( $index == 0 ) {
echo ' -- This is the first element in the associative array';
}
// last index
if ( $index == count( $array ) - 1 ) {
echo ' -- This is the last element in the associative array';
}
echo '<br>';
}
Is it me or is the List<T>.Foreach pretty much been made obsolete by Linq. Originally there was
foreach(X x in Y)
where Y simply had to be IEnumerable (Pre 2.0), and implement a GetEnumerator(). If you look at the MSIL generated you can see that it is exactly the same as
IEnumerator<int> enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
int i = enumerator.Current;
Console.WriteLine(i);
}
(See http://alski.net/post/0a-for-foreach-forFirst-forLast0a-0a-.aspx for the MSIL)
Then in DotNet2.0 Generics came along and the List. Foreach has always felt to me to be an implementation of the Vistor pattern, (see Design Patterns by Gamma, Helm, Johnson, Vlissides).
Now of course in 3.5 we can instead use a Lambda to the same effect, for an example try http://dotnet-developments.blogs.techtarget.com/2008/09/02/iterators-lambda-and-linq-oh-my/
I do it this way...
public static function multiExplode($delims, $string, $special = '|||') {
if (is_array($delims) == false) {
$delims = array($delims);
}
if (empty($delims) == false) {
foreach ($delims as $d) {
$string = str_replace($d, $special, $string);
}
}
return explode($special, $string);
}
Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.
At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ
Awesome tutorial: 3 Different Ways to Display Progress in an ASP.NET AJAX Application
The terminal uses environment variables to determine which character set to use, therefore you can determine it by looking at those variables:
echo $LC_CTYPE
or
echo $LANG
You could use Narrative JavaScript, a compiler that will transforms your code into a state machine, effectively allowing you to emulate threading. It does so by adding a "yielding" operator (notated as '->') to the language that allows you to write asynchronous code in a single, linear code block.
Setting CommandTimeout to 120 is not recommended. Try using pagination as mentioned above. Setting CommandTimeout to 30 is considered as normal. Anything more than that is consider bad approach and that usually concludes something wrong with the Implementation. Now the world is running on MiliSeconds Approach.
Put your JavaScript into separate .js file and use bundling & minification to obscure the code.
An else
block can often exist to complement functionality that occurs in every except
block.
try:
test_consistency(valuable_data)
except Except1:
inconsistency_type = 1
except Except2:
inconsistency_type = 2
except:
# Something else is wrong
raise
else:
inconsistency_type = 0
"""
Process each individual inconsistency down here instead of
inside the except blocks. Use 0 to mean no inconsistency.
"""
In this case, inconsistency_type
is set in each except block, so that behaviour is complemented in the no-error case in else
.
Of course, I'm describing this as a pattern that may turn up in your own code someday. In this specific case, you just set inconsistency_type
to 0 before the try
block anyway.
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
In addition to the other answers here showing you how to git checkout <the-hash-you-want>
it's worth knowing you can switch back to where you were using:
git checkout @{-1}
This is often more convenient than:
git checkout what-was-that-original-branch-called-again-question-mark
As you might anticipate, git checkout @{-2}
will take you back to the branch you were at two git checkout
s ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.
Sadly for productivity, git checkout @{1}
does not take you to the branch you will be on in future, which is a shame.
One more simple way you can try out which will not add duplicate Value before adding object in array:-
//Assume mutableArray is allocated and initialize and contains some value
if (![yourMutableArray containsObject:someValue])
{
[yourMutableArray addObject:someValue];
}
python -c 'from myfile import hello; hello()'
where myfile
must be replaced with the basename of your Python script. (E.g., myfile.py
becomes myfile
).
However, if hello()
is your "permanent" main entry point in your Python script, then the usual way to do this is as follows:
def hello():
print "Hi :)"
if __name__ == "__main__":
hello()
This allows you to execute the script simply by running python myfile.py
or python -m myfile
.
Some explanation here: __name__
is a special Python variable that holds the name of the module currently being executed, except when the module is started from the command line, in which case it becomes "__main__"
.
There's an unofficial open-source API for the Android Market you may try to use to get the information you need. Hope this helps.
I just want to make a specific point about the for in loop in Ruby. It might seem like a construct similar to other languages, but in fact it is an expression like every other looping construct in Ruby. In fact, the for in works with Enumerable objects just as the each iterator.
The collection passed to for in can be any object that has an each iterator method. Arrays and hashes define the each method, and many other Ruby objects do, too. The for/in loop calls the each method of the specified object. As that iterator yields values, the for loop assigns each value (or each set of values) to the specified variable (or variables) and then executes the code in body.
This is a silly example, but illustrates the point that the for in loop works with ANY object that has an each method, just like how the each iterator does:
class Apple
TYPES = %w(red green yellow)
def each
yield TYPES.pop until TYPES.empty?
end
end
a = Apple.new
for i in a do
puts i
end
yellow
green
red
=> nil
And now the each iterator:
a = Apple.new
a.each do |i|
puts i
end
yellow
green
red
=> nil
As you can see, both are responding to the each method which yields values back to the block. As everyone here stated, it is definitely preferable to use the each iterator over the for in loop. I just wanted to drive home the point that there is nothing magical about the for in loop. It is an expression that invokes the each method of a collection and then passes it to its block of code. Hence, it is a very rare case you would need to use for in. Use the each iterator almost always (with the added benefit of block scope).
If you have forked a repository fro Delete your forked copy and fork it again from master.
Just do this way:-
$('ul li').on('click', function(e) {
alert($(this).index());
});
OR
$('ul li').click(function() {
alert($(this).index());
});
Conda can also be used as package manager. It can be installed from Anaconda.
Alternatively, a free minimal installer is Miniconda.
Pass the object from controller to view, convert it to markup without encoding, and parse it to json.
@model IEnumerable<CollegeInformationDTO>
@section Scripts{
<script>
var jsArray = JSON.parse('@Html.Raw(Json.Encode(@Model))');
</script>
}
You can also get them with pure javascript.
For example:
new URL(location.href).searchParams.get('page')
For this url: websitename.com/user/?page=1, it would return a value of 1
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
*// here is where you set it to show on the toolbar*
setSupportActionBar(toolbar);
}
Well, you need to set support action bar setSupportActionBar(); and pass your variable, like so: setSupportActionBar(toolbar);
If you do git update-index --assume-unchanged file.csproj
, git won't check file.csproj for changes automatically: that will stop them coming up in git status whenever you change them. So you can mark all your .csproj files this way- although you'll have to manually mark any new ones that the upstream repo sends you. (If you have them in your .gitignore
or .git/info/exclude
, then ones you create will be ignored)
I'm not entirely sure what .csproj files are... if they're something along the lines of IDE configurations (similar to Eclipse's .eclipse and .classpath files) then I'd suggest they should simply never be source-controlled at all. On the other hand, if they're part of the build system (like Makefiles) then clearly they should--- and a way to pick up optional local changes (e.g. from a local.csproj a la config.mk) would be useful: divide the build up into global parts and local overrides.
The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.
const http = require('http')
const server = http.createServer(function(request, response) {
console.dir(request.param)
if (request.method == 'POST') {
console.log('POST')
var body = ''
request.on('data', function(data) {
body += data
console.log('Partial body: ' + body)
})
request.on('end', function() {
console.log('Body: ' + body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('post received')
})
} else {
console.log('GET')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
}
})
const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)
If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation
var express = require('express')
var fs = require('fs')
var app = express()
app.use(express.bodyParser())
app.get('/', function(request, response) {
console.log('GET /')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
})
app.post('/', function(request, response) {
console.log('POST /')
console.dir(request.body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('thanks')
})
port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
You can use $.ajax call to get the value and then put it in the div you want to. One thing you must know is you cannot receive JSON Data. You have to use JSONP.
Code would be like this:
function CallURL() {
$.ajax({
url: 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan',
type: "GET",
dataType: "jsonp",
async: false,
success: function(msg) {
JsonpCallback(msg);
},
error: function() {
ErrorFunction();
}
});
}
function JsonpCallback(json) {
document.getElementById('summary').innerHTML = json.result;
}
I also stuck on this issue. But I solved simply by defining the foreign key as unsigned integer
.
Find the below example-
CREATE TABLE parent (
id int(10) UNSIGNED NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id int(10) UNSIGNED NOT NULL,
parent_id int(10) UNSIGNED DEFAULT NULL,
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;
Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:
7 % 3 = 1 // dividend % divisor = remainder
What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.
The findstr
command sets the ErrorLevel
(or exit code) to one of the following values, given that there are no invalid or incompatible switches and no search string exceeds the applicable length limit:
0
when at least a single match is encountered in one line throughout all specified files;1
otherwise;A line is considered to contain a match when:
/V
option is given and the search expression occurs at least once;/V
option is given and the search expression does not occur;This means that the /V
option also changes the returned ErrorLevel
, but it does not just revert it!
For example, when you have got a file test.txt
with two lines, one of which contains the string text
but the other one does not, both findstr "text" "test.txt"
and findstr /V "text" "test.txt"
return an ErrorLevel
of 0
.
Basically you can say: if findstr
returns at least a line, ErrorLevel
is set to 0
, else to 1
.
Note that the /M
option does not affect the ErrorLevel
value, it just alters the output.
(Just for the sake of completeness: the find
command behaves exactly the same way with respect to the /V
option and ErrorLevel
; the /C
option does not affect ErrorLevel
.)
In Pyspark you can simply specify each condition separately:
val Lead_all = Leads.join(Utm_Master,
(Leaddetails.LeadSource == Utm_Master.LeadSource) &
(Leaddetails.Utm_Source == Utm_Master.Utm_Source) &
(Leaddetails.Utm_Medium == Utm_Master.Utm_Medium) &
(Leaddetails.Utm_Campaign == Utm_Master.Utm_Campaign))
Just be sure to use operators and parenthesis correctly.
As of React Native 0.4.2, View components have an onLayout
prop. Pass in a function that takes an event object. The event's nativeEvent
contains the view's layout.
<View onLayout={(event) => {
var {x, y, width, height} = event.nativeEvent.layout;
}} />
The onLayout
handler will also be invoked whenever the view is resized.
The main caveat is that the onLayout
handler is first invoked one frame after your component has mounted, so you may want to hide your UI until you have computed your layout.
When you create local variables inside a function that are created on the stack, they most likely get overwritten in memory when exiting the function.
So code like this in most C++ implementations will not work:
char[] populateChar()
{
char* ch = "wonet return me";
return ch;
}
A fix is to create the variable that want to be populated outside the function or where you want to use it, and then pass it as a parameter and manipulate the function, example:
void populateChar(char* ch){
strcpy(ch, "fill me, Will. This will stay", size); // This will work as long as it won't overflow it.
}
int main(){
char ch[100]; // Reserve memory on the stack outside the function
populateChar(ch); // Populate the array
}
A C++11 solution using std::move(ch) to cast lvalues to rvalues:
void populateChar(char* && fillme){
fillme = new char[20];
strcpy(fillme, "this worked for me");
}
int main(){
char* ch;
populateChar(std::move(ch));
return 0;
}
Or this option in C++11:
char* populateChar(){
char* ch = "test char";
// Will change from lvalue to r value
return std::move(ch);
}
int main(){
char* ch = populateChar();
return 0;
}
Originally from this blog post. We can achieve if else by using below code
<xsl:choose>
<xsl:when test="something to test">
</xsl:when>
<xsl:otherwise>
</xsl:otherwise>
</xsl:choose>
So here is what I did
<h3>System</h3>
<xsl:choose>
<xsl:when test="autoIncludeSystem/autoincludesystem_info/@mdate"> <!-- if attribute exists-->
<p>
<dd><table border="1">
<tbody>
<tr>
<th>File Name</th>
<th>File Size</th>
<th>Date</th>
<th>Time</th>
<th>AM/PM</th>
</tr>
<xsl:for-each select="autoIncludeSystem/autoincludesystem_info">
<tr>
<td valign="top" ><xsl:value-of select="@filename"/></td>
<td valign="top" ><xsl:value-of select="@filesize"/></td>
<td valign="top" ><xsl:value-of select="@mdate"/></td>
<td valign="top" ><xsl:value-of select="@mtime"/></td>
<td valign="top" ><xsl:value-of select="@ampm"/></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</dd>
</p>
</xsl:when>
<xsl:otherwise> <!-- if attribute does not exists -->
<dd><pre>
<xsl:value-of select="autoIncludeSystem"/><br/>
</pre></dd> <br/>
</xsl:otherwise>
</xsl:choose>
My Output
purple.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new tasks();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
you write the above code...there we are replacing R.id.content_frame with our fragment. hope this helps you
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
public async Task<ActionResult> Index()
{
apiTable table = new apiTable();
table.Name = "Asma Nadeem";
table.Roll = "6655";
string str = "";
string str2 = "";
HttpClient client = new HttpClient();
string json = JsonConvert.SerializeObject(table);
StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);
str = "" + response.Content + " : " + response.StatusCode;
if (response.IsSuccessStatusCode)
{
str2 = "Data Posted";
}
return View();
}
An easy way to do this with some jQuery and straight JavaScript, just view your console in Chrome or Firefox to see the output...
var queries = {};
$.each(document.location.search.substr(1).split('&'),function(c,q){
var i = q.split('=');
queries[i[0].toString()] = i[1].toString();
});
console.log(queries);
Your problem is with this line:
number4 = list(cow[n])
It tries to take cow[n]
, which returns an integer, and make it a list. This doesn't work, as demonstrated below:
>>> a = 1
>>> list(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
Perhaps you meant to put cow[n]
inside a list:
number4 = [cow[n]]
See a demonstration below:
>>> a = 1
>>> [a]
[1]
>>>
Also, I wanted to address two things:
:
at the end.input
like that, since it evaluates its input as real Python code. It would be better here to use raw_input
and then convert the input to an integer with int
.To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum
:
>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>
Methods suggest something has to happen to return the value, properties suggest that the value is already there. This is a rule of thumb, sometimes you might want a property that does a little work (i.e. Count
), but generally it's a useful way to decide.
You cannot refer non-static members from a static method.
Non-Static members (like your fxn(int y)) can be called only from an instance of your class.
Example:
You can do this:
public class A
{
public int fxn(int y) {
y = 5;
return y;
}
}
class Two {
public static void main(String[] args) {
int x = 0;
A a = new A();
System.out.println("x = " + x);
x = a.fxn(x);
System.out.println("x = " + x);
}
or you can declare you method as static.
I believe that the dates have to be specified in the current culture of the application. You might want to experiment with setting CultureInvariantValues to true and see if that solves your problem. Otherwise you may need to change the DateTimeFormat for the current culture (or the culture itself) to get what you want.
Prevent saving changes that require table re-creation
Five swift clicks
- Tools
- Options
- Designers
- Prevent saving changes that require table re-creation
- OK.
After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.
Further explanation
By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*
When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.
*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild
using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
okay got it , you have to use ngAfterViewInit
method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit
will not throw any error because it will render after template loading
SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.
SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.
Some useful links can be found below:
Disclosure: I am the tech lead on the SciChart project!
You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.
In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".
$(document).ready(function () {
$('input[type=checkbox]').click(function(){
var areYouSure = confirm('Are you sure you want make this change?');
if (areYouSure) {
$(this).prop('checked', this.checked);
} else {
$(this).prop('checked', !this.checked);
}
});
});
<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />
protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
using (myDataContext db = new myDataDataContext())
{
CheckBox chk = (CheckBox)sender;
RepeaterItem row = (RepeaterItem) chk.NamingContainer;
var studentID = ((Label) row.FindControl("lblID")).Text;
var z = (from b in db.StudentApplicants
where b.StudentID == studentID
select b).FirstOrDefault();
if(chk != null && chk.Checked != z.FinancialAid){
z.FinancialAid = chk.Checked;
z.ModifiedDate = DateTime.Now;
db.SubmitChanges();
BindGrid();
}
gvData.DataBind();
}
}
Having read the above answers i found that for my situation the following fixed the issue.
This threw the error
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(getApplicationContext());
dialog.show();
}
});
Based on the previous answers that suggested the context was the wrong one, i changed the getApplicationContext() to retrieve the context from the View passed in to the buttons onClick method.
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(v.getContext());
dialog.show();
}
});
I don't fully understand the workings of Java so i could be wrong, but I'm guessing that for my specific situation the cause could have been related to the fact that the above snippet was defined in an Abstract Activity class; inherited and used by many Activities, perhaps that contributed to the fact that getApplicationContext() doesn't return a valid context?? (Just a guess).
Have you tried using:
(status,output) = commands.getstatusoutput("ps aux")
I thought this had fixed the exact same problem for me. But then my process ended up getting killed instead of failing to spawn, which is even worse..
After some testing I found that this only occurred on older versions of python: it happens with 2.6.5 but not with 2.7.2
My search had led me here python-close_fds-issue, but unsetting closed_fds had not solved the issue. It is still well worth a read.
I found that python was leaking file descriptors by just keeping an eye on it:
watch "ls /proc/$PYTHONPID/fd | wc -l"
Like you, I do want to capture the command's output, and I do want to avoid OOM errors... but it looks like the only way is for people to use a less buggy version of Python. Not ideal...
I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line.
The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.
I resolved the problem.This is for EAServer Windows Service
Resolution is --> Open Regedit in Run prompt
Under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\EAServer
In parameters, give SERVERNAME entry as EAServer.
[It is sometime overwritten with Envirnoment variable : Path value]
I found out that this simple assignmnent also works:
dateOriginal = new Date();
cloneDate = new Date(dateOriginal);
But I don't know how "safe" it is. Successfully tested in IE7 and Chrome 19.
Here is the documentation on IEnumerator
. They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate
, which means "to count off or name one by one".
IEnumerator
and IEnumerator<T>
is provided by all IEnumerable
and IEnumerable<T>
interfaces (the latter providing both) in .NET via GetEnumerator()
. This is important because the foreach
statement is designed to work directly with enumerators through those interface methods.
So for example:
IEnumerator enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext())
{
object item = enumerator.Current;
// Perform logic on the item
}
Becomes:
foreach(object item in enumerable)
{
// Perform logic on the item
}
As to your specific scenario, almost all collections in .NET implement IEnumerable
. Because of that, you can do the following:
public IEnumerator Enumerate(IEnumerable enumerable)
{
// List implements IEnumerable, but could be any collection.
List<string> list = new List<string>();
foreach(string value in enumerable)
{
list.Add(value + "roxxors");
}
return list.GetEnumerator();
}
For Powershell it is
[System.Net.ServicePointManager]::Expect100Continue = $false
Adding a roundabout answer here. I was struggling to install git on an RHEL 6.0 Amazon instance, and what ended up saving me was ... conda, as in Anaconda Python.
I installed conda on the command line from the archives (code modeled after this):
wget http://repo.continuum.io/miniconda/Miniconda2-4.2.12-Linux-x86_64.sh -O ~/miniconda.sh
bash ~/miniconda.sh -b -p $HOME/miniconda
export PATH="$HOME/miniconda/bin:$PATH"
and then ran
conda install git
and a relatively recent version git was installed. Today is 12/26/2016 and the version is 2.9.3.
This should be (condition)? True statement : False statement
Leave out the "if"
You forget the @ID above the userId
driver.save_screenshot("path to save \\screen.jpeg")
len(queue)
should give you the result, 3 in this case.
Specifically, len(object)
function will call object.__len__
method [reference link]. And the object in this case is deque
, which implements __len__
method (you can see it by dir(deque)
).
queue= deque([]) #is this length 0 queue?
Yes it will be 0 for empty deque
.
I Solved with this setting:
IIS > Application Pools > [your site] > Advanced Settings... > Identity > Built-in accound > LocalSystem
If you need to use a dictionary’s keys or values with an API that takes an Array instance, initialize a new array with the keys or values property:
let airportCodes = [String](airports.keys) // airportCodes is ["TYO", "LHR"]
let airportNames = [String](airports.values) // airportNames is ["Tokyo", "London Heathrow"]
Get the latest Selenium jars (2.30) for FireFox 19
You can download the latest jars (2.31 as of writing) here: https://code.google.com/p/selenium/downloads/list
You can do this:
def deleteContent(pfile):
fn=pfile.name
pfile.close()
return open(fn,'w')
You mentioned a signed angle (-90). In many applications angles may have signs (positive and negative, see http://en.wikipedia.org/wiki/Angle). If the points are (say) P2(1,0), P1(0,0), P3(0,1) then the angle P3-P1-P2 is conventionally positive (PI/2) whereas the angle P2-P1-P3 is negative. Using the lengths of the sides will not distinguish between + and - so if this matters you will need to use vectors or a function such as Math.atan2(a, b).
Angles can also extend beyond 2*PI and while this is not relevant to the current question it was sufficiently important that I wrote my own Angle class (also to make sure that degrees and radians did not get mixed up). The questions as to whether angle1 is less than angle2 depends critically on how angles are defined. It may also be important to decide whether a line (-1,0)(0,0)(1,0) is represented as Math.PI or -Math.PI
After installing weblogic and forms server on a Linux machine we met some problems initializing sqlplus
and tnsping
. We altered the bash_profile
in a way that the forms_home acts as the oracle home. It works fine, both commands
(sqlplus and tnsping) are executable for user oracle
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export JAVA_HOME=/mnt/software/java/jdk1.7.0_71
export ORACLE_HOME=/oracle/Middleware/Oracle_FRHome1
export PATH=$PATH:$JAVA_HOME/bin:$ORACLE_HOME/bin
export LD_LIBRARY_PATH=/oracle/Middleware/Oracle_FRHome1/lib
export FORMS_PATH=$FORMS_PATH:/oracle/Middleware/Oracle_FRHome1/forms:/oracle/Middleware/asinst_1/FormsComponent/forms:/appl/myapp:/home/oracle/myapp
From the HashSet<T>
page on MSDN:
The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
(emphasis mine)
.dex file
Compiled Android application code file.
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.
Maybe you want unpack elements of array, I don't know if I got it, but below a example:
def my_func(*args):
for a in args:
print a
my_func(*[1,2,3,4])
my_list = ['a','b','c']
my_func(*my_list)