You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.
Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.
Just use plt.tight_layout()
before plt.show()
. It works well.
That's still a constant. See the JLS for more information regarding the naming convention for constants. But in reality, it's all a matter of preference.
The names of constants in interface types should be, and
final
variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore"_"
characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants includeMIN_VALUE
,MAX_VALUE
,MIN_RADIX
, andMAX_RADIX
of the classCharacter
.A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:
interface ProcessStates { int PS_RUNNING = 0; int PS_SUSPENDED = 1; }
Obscuring involving constant names is rare:
- Constant names normally have no lowercase letters, so they will not normally obscure names of packages or types, nor will they normally shadow fields, whose names typically contain at least one lowercase letter.
- Constant names cannot obscure method names, because they are distinguished syntactically.
It might be worth noting that this can also occur when Windows blocks downloads that it considers to be unsafe. This can be addressed by right-clicking the jar file (such as ojdbc7.jar), and checking the 'Unblock' box at the bottom.
Windows JAR File Properties Dialog:
I have a similar issue, have you tried:
proxy.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Impersonation;
Components are declared, Modules are imported, and Services are provided. An example I'm working with:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms';
import { UserComponent } from './components/user/user.component';
import { StateService } from './services/state.service';
@NgModule({
declarations: [
AppComponent,
UserComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [ StateService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
I did some research on this by using different methods to assign values to a nullable int. Here is what happened when I did various things. Should clarify what's going on.
Keep in mind: Nullable<something>
or the shorthand something?
is a struct for which the compiler seems to be doing a lot of work to let us use with null as if it were a class.
As you'll see below, SomeNullable == null
and SomeNullable.HasValue
will always return an expected true or false. Although not demonstrated below, SomeNullable == 3
is valid too (assuming SomeNullable is an int?
).
While SomeNullable.Value
gets us a runtime error if we assigned null
to SomeNullable
. This is in fact the only case where nullables could cause us a problem, thanks to a combination of overloaded operators, overloaded object.Equals(obj)
method, and compiler optimization and monkey business.
Here is a description of some code I ran, and what output it produced in labels:
int? val = null;
lbl_Val.Text = val.ToString(); //Produced an empty string.
lbl_ValVal.Text = val.Value.ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValEqNull.Text = (val == null).ToString(); //Produced "True" (without the quotes)
lbl_ValNEqNull.Text = (val != null).ToString(); //Produced "False"
lbl_ValHasVal.Text = val.HasValue.ToString(); //Produced "False"
lbl_NValHasVal.Text = (!(val.HasValue)).ToString(); //Produced "True"
lbl_ValValEqNull.Text = (val.Value == null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValValNEqNull.Text = (val.Value != null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
Ok, lets try the next initialization method:
int? val = new int?();
lbl_Val.Text = val.ToString(); //Produced an empty string.
lbl_ValVal.Text = val.Value.ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValEqNull.Text = (val == null).ToString(); //Produced "True" (without the quotes)
lbl_ValNEqNull.Text = (val != null).ToString(); //Produced "False"
lbl_ValHasVal.Text = val.HasValue.ToString(); //Produced "False"
lbl_NValHasVal.Text = (!(val.HasValue)).ToString(); //Produced "True"
lbl_ValValEqNull.Text = (val.Value == null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValValNEqNull.Text = (val.Value != null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
All the same as before. Keep in mind that initializing with int? val = new int?(null);
, with null passed to the constructor, would have produced a COMPILE time error, since the nullable object's VALUE is NOT nullable. It is only the wrapper object itself that can equal null.
Likewise, we would get a compile time error from:
int? val = new int?();
val.Value = null;
not to mention that val.Value
is a read-only property anyway, meaning we can't even use something like:
val.Value = 3;
but again, polymorphous overloaded implicit conversion operators let us do:
val = 3;
No need to worry about polysomthing whatchamacallits though, so long as it works right? :)
Thought to share a different solution which no one suggested here. There's a property called text-stroke
which will be handy for this.
p span:hover {_x000D_
-webkit-text-stroke: 1px black;_x000D_
}
_x000D_
<p>Some stuff, <span>hover this,</span> it's cool</p>
_x000D_
Here, I am targeting the text inside of the span
tag and we stroke it by a pixel with black
which will simulate bold
style for that particular text.
Note that this property is not widely supported, as of now (while writing this answer), only Chrome and Firefox seems to support this. For more information on browser support for text-stroke
, you can refer to CanIUse.
Just for sharing some extra stuff, you can use -webkit-text-stroke-width: 1px;
if you are not looking to set a color
for your stroke.
You want:
answer = str(raw_input("Is the information correct? Enter Y for yes or N for no"))
if answer == "y" or answer == "Y":
print("this will do the calculation")
else:
exit()
Or
answer = str(raw_input("Is the information correct? Enter Y for yes or N for no"))
if answer in ["y","Y"]:
print("this will do the calculation")
else:
exit()
Note:
input
evals the input."a" or "b"
evaluates to "a"
, whereas 0 or "b"
evaluates to "b"
. See The Peculiar Nature of and and or.A simple representation written by 'Robert Sedgwick' and 'Kevin Wayne' is available at http://algs4.cs.princeton.edu/41graph/Graph.java.html
Explanation copied from the above page.
The Graph class represents an undirected graph of vertices named 0 through V - 1.
It supports the following two primary operations: add an edge to the graph, iterate over all of the vertices adjacent to a vertex. It also provides methods for returning the number of vertices V and the number of edges E. Parallel edges and self-loops are permitted. By convention, a self-loop v-v appears in the adjacency list of v twice and contributes two to the degree of v.
This implementation uses an adjacency-lists representation, which is a vertex-indexed array of Bag objects. All operations take constant time (in the worst case) except iterating over the vertices adjacent to a given vertex, which takes time proportional to the number of such vertices.
A simple way to add a JAR file as a library to your Android Studio project:
a) Copy your *.jar files
b) Paste into the libs directory under your projects:
c) Add to build.gradle:
dependencies {
...
compile files('libs/ScanAPIAndroid.jar', 'libs/ScanAPIFactoryAndroid.jar', .., ..)
}
b) If your project from example com.example.MYProject and libraries com.example.ScanAPI has the same namespace com.example, Android Studio will check your build and create all necessary changes in your project. After that you can review these settings in menu File -> Project Structure.
c) If your project and libraries have a different namespace you have to right click on the library and select option "Add as Library" and select the type what you need.
Remember the "Project structure" option is not doing any auto changes in "build.gradle" in the current version of Android Studio (0.2.3). Maybe this feature will be available in the next versions.
In the Windows Command Prompt the ^
is used to escape the next character on the command line. (Like \
is used in strings.) Characters that need to be used in the command line as they are should have a ^ prefixed to them, hence that's why it works for the newline.
For reference the characters that need escaping (if specified as command arguments and not within quotes) are: &|()
So the equivalent of your linux example would be (the More? being a prompt):
C:\> dir ^
More? C:\Windows
I extracted the code and put into one single method, hope it would help others.
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
...
- (BOOL)isInternetReachable
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
SCNetworkReachabilityFlags flags;
if(reachability == NULL)
return false;
if (!(SCNetworkReachabilityGetFlags(reachability, &flags)))
return false;
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
// if target host is not reachable
return false;
BOOL isReachable = false;
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
// if target host is reachable and no connection is required
// then we'll assume (for now) that your on Wi-Fi
isReachable = true;
}
if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
// ... and the connection is on-demand (or on-traffic) if the
// calling application is using the CFSocketStream or higher APIs
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
// ... and no [user] intervention is needed
isReachable = true;
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
isReachable = true;
}
return isReachable;
}
You can use
try {
user.OtherFriend = row["US_OTHERFRIEND"].ToString();
}
catch (Exception ex)
{
// do something if you want
}
cursor.execute(sql,array)
Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)
No need to use sub query, just Try this,Its working fine:
DB::table('orders')->orderBy('id', 'desc')->first();
If you commit to the wrong branch
While on the wrong branch:
git log -2
gives you hashes of 2 last commits, let's say $prev
and $last
git checkout $prev
checkout correct commitgit checkout -b new-feature-branch
creates a new branch for the featuregit cherry-pick $last
patches a branch with your changesThen you can follow one of the methods suggested above to remove your commit from the first branch.
You can use NSNumberFormatter().numberFromString(yourNumberString)
. It's great because it returns an an optional that you can then test with if let
to determine if the conversion was successful.
eg.
var myString = "\(10)"
if let myNumber = NSNumberFormatter().numberFromString(myString) {
var myInt = myNumber.integerValue
// do what you need to do with myInt
} else {
// what ever error code you need to write
}
var myString = "\(10)"
if let myNumber = NumberFormatter().number(from: myString) {
var myInt = myNumber.intValue
// do what you need to do with myInt
} else {
// what ever error code you need to write
}
you use the scrollTop attribute
var position = document.getElementById('id').scrollTop;
First You Have To Add Name Of Your Module In setting.gradle(Project Setting) File Like This..
include ':app', ':simple-crop-image-lib'
Then You Need To Compile This Module Into build.gradle(Module app) File Like This..
implementation project(':simple-crop-image-lib')
That's all for adding module now it will be appear in android section or project section as well.
If It's till did't appear rebuild or clean your project..
Via css. Put this inside the <head>
tag.
<style type="text/css" media="screen">
table{
border-collapse:collapse;
border:1px solid #FF0000;
}
table td{
border:1px solid #FF0000;
}
</style>
Not working for me.
The mode is true, the file perms have been changed, but git says there's no work to do.
git init
git add dir/file
chmod 440 dir/file
git commit -a
The problem seems to be that git recognizes only certain permission changes.
Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:
System.out.printf("%s \r\n",String.valueOf(d));
or
System.out.printf("%s \r\n",Double.toString(d));
This is what println do by default:
System.out.println(d)
(and terminates the line)
There are probably many architectural differences between myRDD.foreach(println)
and myRDD.collect().foreach(println)
(not only 'collect', but also other actions). One the differences I saw is when doing myRDD.foreach(println)
, the output will be in a random order. For ex: if my rdd is coming from a text file where each line has a number, the output will have a different order. But when I did myRDD.collect().foreach(println)
, order remains just like the text file.
Using ImageMagick, this is very similar to hackerb9 code and result, but is a little simpler command line. It does assume that the top left pixel is the background color. I just flood fill the background with transparency, then select the alpha channel and blur it and remove half of the blurred area using -level 50x100%. Then turn back on all the channels and flatten it against the brown color. The -blur 0x1 -level 50x100% acts to antialias the boundaries of the alpha channel transparency. You can adjust the fuzz value, blur amount and the -level 50% value to change the degree of antialiasing.
convert logo: -fuzz 25% -fill none -draw "matte 0,0 floodfill" -channel alpha -blur 0x1 -level 50x100% +channel -background saddlebrown -flatten result.jpg
I think @Erlend's use of HTMLDocument
is the best way to go. However, I have also had good luck using this simple library:
Ascx-files are called User Controls and are meant for reusability and also for making complex aspx-pages less complex (lift out some part of the page). They could also be beneficial for something called donut caching, that is when you would like to cache a certain part of a page.
for (int i = 0; i < list.length; i++) {
if (list.get(i) .getName().equalsIgnoreCase("myName")) {
System.out.println(i);
break;
}
}
For UNIX:
As Stephen C has suggested, changing the maximum file descriptor value to a higher value avoids this problem.
Try looking at your present file descriptor capacity:
$ ulimit -n
Then change the limit according to your requirements.
$ ulimit -n <value>
Note that this just changes the limits in the current shell and any child / descendant process. To make the change "stick" you need to put it into the relevant shell script or initialization file.
[SOLVED]
I only observed this error today, for me the Error code was different though.
SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
It was occurring randomly and not all the time. but what it noticed is, if it comes for subsequent ajax calls. so i put some delay of 5 seconds between the ajax calls and it resolved.
One way:
import os
os.listdir("/home/username/www/")
glob.glob("/home/username/www/*")
The glob.glob
method above will not list hidden files.
Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir
method on Path
objects:
from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")
To extract the jar into specified folder use this command via command prompt
C:\Java> jar xf myFile.jar -C "C:\tempfolder"
I think you can also execute the pwd() function on the particular node:
node {
def PWD = pwd();
...
}
Instead:
public class PhotosFragment extends Fragment
You can use:
public class PhotosFragment extends ListFragment
It change the methods
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<ListviewContactItem> listContact = GetlistContact();
setAdapter(new ListviewContactAdapter(getActivity(), listContact));
}
onActivityCreated is void and you didn't need to return a view like in onCreateView
You can see an example here
This is a simple circle as a drawable in Android.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#666666"/>
<size
android:width="120dp"
android:height="120dp"/>
</shape>
I would recommend writing these helpers using named parameters for the sake of clarity as follows:
@Html.ActionLink(
linkText: "Details",
actionName: "Details",
controllerName: "Product",
routeValues: new {
id = item.ID
},
htmlAttributes: null
)
This answer does not address the Debug button (you'd have to design a form and use the buttons on that to do something like the method in your next question). But it does address this part:
now I don't want to lose the comfortableness of the default handler which also point me to the exact line where the error has occured.
First, I'll assume you don't want this in production code - you want it either for debugging or for code you personally will be using. I use a compiler flag to indicate debugging; then if I'm troubleshooting a program, I can easily find the line that's causing the problem.
# Const IsDebug = True
Sub ProcA()
On Error Goto ErrorHandler
' Main code of proc
ExitHere:
On Error Resume Next
' Close objects and stuff here
Exit Sub
ErrorHandler:
MsgBox Err.Number & ": " & Err.Description, , ThisWorkbook.Name & ": ProcA"
#If IsDebug Then
Stop ' Used for troubleshooting - Then press F8 to step thru code
Resume ' Resume will take you to the line that errored out
#Else
Resume ExitHere ' Exit procedure during normal running
#End If
End Sub
Note: the exception to Resume
is if the error occurs in a sub-procedure without an error handling routine, then Resume
will take you to the line in this proc that called the sub-procedure with the error. But you can still step into and through the sub-procedure, using F8 until it errors out again. If the sub-procedure's too long to make even that tedious, then your sub-procedure should probably have its own error handling routine.
There are multiple ways to do this. Sometimes for smaller programs where I know I'm gonna be stepping through it anyway when troubleshooting, I just put these lines right after the MsgBox statement:
Resume ExitHere ' Normally exits during production
Resume ' Never will get here
Exit Sub
It will never get to the Resume statement, unless you're stepping through and set it as the next line to be executed, either by dragging the next statement pointer to that line, or by pressing CtrlF9 with the cursor on that line.
Here's an article that expands on these concepts: Five tips for handling errors in VBA. Finally, if you're using VBA and haven't discovered Chip Pearson's awesome site yet, he has a page explaining Error Handling In VBA.
INADDR_ANY
is used when you don't need to bind a socket to a specific IP. When you use this value as the address when calling bind()
, the socket accepts connections to all the IPs of the machine.
In the child
<input
type="number"
class="form-control"
id="phoneNumber"
placeholder
v-model="contact_number"
v-on:input="(event) => this.$emit('phoneNumber', event.target.value)"
/>
data(){
return {
contact_number : this.contact_number_props
}
},
props : ['contact_number_props']
In parent
<contact-component v-on:phoneNumber="eventPhoneNumber" :contact_number_props="contact_number"></contact-component>
methods : {
eventPhoneNumber (value) {
this.contact_number = value
}
Console.WriteLine(DateTime.UtcNow.ToString("o"));
Console.WriteLine(DateTime.Now.ToString("o"));
Outputs:
2012-07-09T19:22:09.1440844Z
2012-07-09T12:22:09.1440844-07:00
You can use the RedirectToAction()
method, then the action you redirect to can return a View. The easiest way to do this is:
return RedirectToAction("Index", model);
Then in your Index method, return the view you want.
Simple and even faster way to get it via ES6
let newArray = users.flatMap(i => i.ID) // -> [ 12, 13, 14, 15 ]
Might not be relevant for everyone but this little detail was causing mine not to work:
Change div from this:
<div class="map">
To this:
<div id="map">
Use the modulus operator %
, it returns the remainder.
int a = 5;
int b = 3;
if (a % b != 0) {
printf("The remainder is: %i", a%b);
}
This is directly from http://www.programcreek.com/2011/10/java-class-instance-initializers/
Look at the following class, do you know which one gets executed first?
public class Foo {
//instance variable initializer
String s = "abc";
//constructor
public Foo() {
System.out.println("constructor called");
}
//static initializer
static {
System.out.println("static initializer called");
}
//instance initializer
{
System.out.println("instance initializer called");
}
public static void main(String[] args) {
new Foo();
new Foo();
}
}
Output:
static initializer called
instance initializer called
constructor called
instance initializer called
constructor called
The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0
. This can make it more obvious to understand.
Instead of
int b = 0
, you could write
int b;
b = 0;
Therefore, instance initializers and instance variable initializers are pretty much the same.
The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:
Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.
With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)
Another case in which instance initializers are useful is anonymous inner classes, which can’t declare any constructors at all. (Will this be a good place to place a logging function?)
Thanks to Derhein.
Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are needed to execute any kinds of expressions at construction time.
WARNING: This post will make you hungry.
I found myself wanting to select multiple, individual rows—instead of a group—and concatenate on a certain field.
Let's say you have a table of product ids and their names and prices:
+------------+--------------------+-------+
| product_id | name | price |
+------------+--------------------+-------+
| 13 | Double Double | 5 |
| 14 | Neapolitan Shake | 2 |
| 15 | Animal Style Fries | 3 |
| 16 | Root Beer | 2 |
| 17 | Lame T-Shirt | 15 |
+------------+--------------------+-------+
Then you have some fancy-schmancy ajax that lists these puppies off as checkboxes.
Your hungry-hippo user selects 13, 15, 16
. No dessert for her today...
A way to summarize your user's order in one line, with pure mysql.
Use GROUP_CONCAT
with the the IN
clause:
mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary FROM product WHERE product_id IN (13, 15, 16);
Which outputs:
+------------------------------------------------+
| order_summary |
+------------------------------------------------+
| Double Double + Animal Style Fries + Root Beer |
+------------------------------------------------+
If you want the total price too, toss in SUM()
:
mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary, SUM(price) AS total FROM product WHERE product_id IN (13, 15, 16);
+------------------------------------------------+-------+
| order_summary | total |
+------------------------------------------------+-------+
| Double Double + Animal Style Fries + Root Beer | 10 |
+------------------------------------------------+-------+
In Kotlin, you can do this.
val editText1 = findViewById(R.id.editText)
val intNum = editText1.text.toString().toInt()
Android O removed the possibility to receive the implicit broadcasts for a wifi state change. So if your app is closed, you'll not be able to receive them. The new WorkManager
has the ability to run when your app is closed, so I've experimented a bit with it and it seems to work quite well:
Add this to your dependencies:
implementation "android.arch.work:work-runtime:1.0.0-alpha08"
WifiConnectWorker.kt
class WifiConnectWorker : Worker() {
override fun doWork(): Result {
Log.i(TAG, "I think we connected to a wifi")
return Result.SUCCESS
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
val workManager = WorkManager.getInstance()
// Add constraint to start the worker when connecting to WiFi
val request = OneTimeWorkRequest.Builder(WifiConnectWorker::class.java)
.setConstraints(Constraints.Builder()
.setRequiredNetworkType(UNMETERED)
.build())
.build()
// The worker should be started, even if your app is closed
workManager.beginUniqueWork("watch_wifi", REPLACE, request).enqueue()
}
}
Keep in mind that this was just a quick test for a one-time notification. There is more work to do to always get notified when WiFi is turned on and off.
PS: When the app is force quit, the worker is not started, it seems WorkManager
is canceling the requests then.
Multiple statements are to be separated by a new line:
If SkyIsBlue Then
StartEngines
Pollute
ElseIf SkyIsRed Then
StopAttack
Vent
ElseIf SkyIsYellow Then
If Sunset Then
Sleep
ElseIf Sunrise or IsMorning Then
Smoke
GetCoffee
Else
Error
End If
Else
Joke
Laugh
End If
I use Fedora (currently 31)
Even with JDK's installed, I still need to specify JAVAC_HOME in the .bashrc, especially since I have 4 Java versions using sudo alternatives --configure java to switch between them.
To find java location of java selected in alternatives
readlink -f $(which java)
In my case: /usr/java/jdk1.8.0_241-amd64/jre/bin/java
So I set following in .bashrc to:
export JAVA_HOME=/usr/java/jdk1.8.0_241-amd64/jre/bin/java
export JAVAC_HOME=/usr/java/jdk1.8.0_241-amd64/bin/javac
export PATH=$PATH:/usr/java/jdk1.8.0_241-amd64/jre/bin
export PATH=$PATH:/usr/java/jdk1.8.0_241-amd64/bin/
Now javac –version gives: javac 1.8.0_241
This is useful for those who want to use Oracle's version. Just remember to change your .bashrc again if you make a change with java alternatives.
Rake::Task['reklamer:orville'].invoke
or
Rake::Task['reklamer:orville'].invoke(args)
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
Or you can use the ANDROID_ID setting from Android.Provider.Settings.System (as described here strazerre.com).
This has the advantage that it doesn't require special permissions but can change if another application has write access and changes it (which is apparently unusual but not impossible).
Just for reference here is the code from the blog:
import android.provider.Settings;
import android.provider.Settings.System;
String androidID = System.getString(this.getContentResolver(),Secure.ANDROID_ID);
Implementation note: if the ID is critical to the system architecture you need to be aware that in practice some of the very low end Android phones & tablets have been found reusing the same ANDROID_ID (9774d56d682e549c was the value showing up in our logs)
use DIRECTORY option.
Documentation here: http://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_import.htm#SUTIL907
DIRECTORY
Default: DATA_PUMP_DIR
Purpose
Specifies the default location in which the import job can find the dump file set and where it should create log and SQL files.
Syntax and Description
DIRECTORY=directory_object
The directory_object is the name of a database directory object (not the file path of an actual directory). Upon installation, privileged users have access to a default directory object named DATA_PUMP_DIR. Users with access to the default DATA_PUMP_DIR directory object do not need to use the DIRECTORY parameter at all.
A directory object specified on the DUMPFILE, LOGFILE, or SQLFILE parameter overrides any directory object that you specify for the DIRECTORY parameter. You must have Read access to the directory used for the dump file set and Write access to the directory used to create the log and SQL files.
Example
The following is an example of using the DIRECTORY parameter. You can create the expfull.dmp dump file used in this example by running the example provided for the Export FULL parameter. See "FULL".
> impdp hr DIRECTORY=dpump_dir1 DUMPFILE=expfull.dmp
LOGFILE=dpump_dir2:expfull.log
This command results in the import job looking for the expfull.dmp dump file in the directory pointed to by the dpump_dir1 directory object. The dpump_dir2 directory object specified on the LOGFILE parameter overrides the DIRECTORY parameter so that the log file is written to dpump_dir2.
The best solution we found was to team up with one of those intermediaries. Otherwise you will have to deal with a bunch of other requirements like PCI compliance. We use Verifone's IPCharge and it works quite well.
The best way in browsers that support it, is to send the file as a Blob, or using FormData if you want a multipart form. You do not need a FileReader for that. This is both simpler and more efficient than trying to read the data.
If you specifically want to send it as multipart/form-data
, you can use a FormData object:
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);
var formData = new FormData();
// This should automatically set the file name and type.
formData.append("file", file);
// Sending FormData automatically sets the Content-Type header to multipart/form-data
xmlHttpRequest.send(formData);
You can also send the data directly, instead of using multipart/form-data
. See the documentation. Of course, this will need a server-side change as well.
// file is an instance of File, e.g. from a file input.
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);
xmlHttpRequest.setRequestHeader("Content-Type", file.type);
// Send the binary data.
// Since a File is a Blob, we can send it directly.
xmlHttpRequest.send(file);
For browser support, see: http://caniuse.com/#feat=xhr2 (most browsers, including IE 10+).
I had NuGet packages breaking after I did a System Restore on my system, backing it up about two days. (The NuGet packages had been installed in the meantime.) To fix it, I had to go to the .nuget\packages folder in my user profile, find the packages, and delete them. Only then would Visual Studio pull the packages down fresh and properly add them as references.
On the data dictionary side there are a lot of tools you can use to such as Schema Spy
To look at what queries are running look at views sys.v_$sql and sys.v_$sqltext. You will also need access to sys.all_users
One thing to note that queries that use parameters will show up once with entries like
and TABLETYPE=’:b16’
while others that dont will show up multiple times such as:
and TABLETYPE=’MT’
An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the WHERE rownum <= 20 and maybe add ORDER BY module. You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc)
SELECT
module,
sql_text,
username,
disk_reads_per_exec,
buffer_gets,
disk_reads,
parse_calls,
sorts,
executions,
rows_processed,
hit_ratio,
first_load_time,
sharable_mem,
persistent_mem,
runtime_mem,
cpu_time,
elapsed_time,
address,
hash_value
FROM
(SELECT
module,
sql_text ,
u.username ,
round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec,
s.disk_reads ,
s.buffer_gets ,
s.parse_calls ,
s.sorts ,
s.executions ,
s.rows_processed ,
100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio,
s.first_load_time ,
sharable_mem ,
persistent_mem ,
runtime_mem,
cpu_time,
elapsed_time,
address,
hash_value
FROM
sys.v_$sql s,
sys.all_users u
WHERE
s.parsing_user_id=u.user_id
and UPPER(u.username) not in ('SYS','SYSTEM')
ORDER BY
4 desc)
WHERE
rownum <= 20;
Note that if the query is long .. you will have to query v_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH_VALUE and pick up all the pieces. Eg:
SELECT
*
FROM
sys.v_$sqltext
WHERE
address = 'C0000000372B3C28'
and hash_value = '1272580459'
ORDER BY
address, hash_value, command_type, piece
;
At first you need to understand first, that Tomcat is a Java application. So, to see which java version Tomcat is using, you can just simply find the script file from which Tomcat is started, usually catalina.sh.
Inside this file, you will get something like below:
catalina.sh:# JAVA_HOME Must point at your Java Development Kit installation.
catalina.sh:# Defaults to JAVA_HOME if empty.
catalina.sh: [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
catalina.sh: JAVA_HOME=`cygpath --absolute --windows "$JAVA_HOME"`
catalina.sh: echo "Using JAVA_HOME: $JAVA_HOME"
By default, JAVA_HOME should be empty, which mean it will use the default version of java, or you can test with: echo $JAVA_HOME
And then use "java -version" to see which version you default java is.
And vice versa by setting this property: JAVA_HOME, you can configure which Java version to use when starting Tomcat.
Have you tried innerHTML
?
I'd be inclined to use getElementsByTagName()
to find the <tr>
elements, and then on each to call it again to find the <td>
elements. To get the contents, you can either use innerHTML
or the appropriate (browser-specific) variation on innerText
.
Put your Main Java class file in src/main/java
folder and check if there is not any error in 'Java Build Path' by following right click on project and select Java Build Path->Source
.
Uri.parse(STRING);
See doc:
String: an RFC 2396-compliant, encoded URI
Url must be canonicalized before using, like this:
Uri.parse(Uri.decode(STRING));
This is more a workaround than a real solution. You can create a new object test_data
with another column name:
left_join("names<-"(test_data, "name"), kantrowitz, by = "name")
name gender
1 john M
2 bill either
3 madison M
4 abby either
5 zzz <NA>
you can use the <text>
tag for both cshtml code with javascript
From http://pyyaml.org/wiki/PyYAMLDocumentation:
add_path_resolver(tag, path, kind)
adds a path-based implicit tag resolver. A path is a list of keys that form a path to a node in the representation graph. Paths elements can be string values, integers, or None. The kind of a node can be str, list, dict, or None.
#!/usr/bin/env python
import yaml
class Person(yaml.YAMLObject):
yaml_tag = '!person'
def __init__(self, name):
self.name = name
yaml.add_path_resolver('!person', ['Person'], dict)
data = yaml.load("""
Person:
name: XYZ
""")
print data
# {'Person': <__main__.Person object at 0x7f2b251ceb10>}
print data['Person'].name
# XYZ
Increase the size of your perm space, of course. Use the -XX:MaxPermSize=128m
option. Set the value to something appropriate.
Check your home folder ~/.gradle/gradle.properties
. Sometimes if you have gradle.properties
in home directory it takes details from the there. Either you can change that or delete the files. Then it will take required details from your local folder.
I think it's asking you to do this:
SELECT ID
FROM (SELECT ID,
msisdn
FROM (SELECT * FROM TT2) as myalias
) as anotheralias;
But why would you write this query in the first place?
If nothing of this helps (my case), you can set it in your pom.xml, like this:
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
As this cool guy mentioned here: https://stackoverflow.com/a/25888116/1643465
My contribution is aimed at those on a Mac, and it can be applied to not only those working on an iOS project (as implied by the question mentioning Xcode), but any type of project.
The easy way that I do it is to go into the terminal and run vim .gitignore
and then add the files. Usually you can just copy what you need from one of the templates on GitHub at https://github.com/github/gitignore.
Step 1
While in your project, type the following command
vim .gitignore
Step 2
You now have your file open with Vim.
Press i
to insert text. You will see that the file is ready when you see the --INSERT-- at the bottom.
Step 3 (option 1)
For Objective-C projects, you can copy from https://raw.githubusercontent.com/github/gitignore/master/Objective-C.gitignore and paste it into your .gitignore
file:
Press Esc, type in :wq
, and press Return. Which saves the file.
Step 3 (option 2)
Add whatever files apply to your project.
If you are not sure what to add, the best keywords to use in your search engine would be to include your project type and text editor. For example, if you use Sublime Text you would want to add
*.sublime-workspace
And if you are working with a Cordova project in Dreamweaver you would want to add
_notes
dwsync.xml
Well if you're happy printing it in decimal, you could just make it positive by masking:
int positive = bytes[i] & 0xff;
If you're printing out a hash though, it would be more conventional to use hex. There are plenty of other questions on Stack Overflow addressing converting binary data to a hex string in Java.
Lot of good answers. I needed mine for Indian (South Asian) numbering system. I modified one of the codes above - attaching it here, in case, someone else needs this. In the Indian numbering system, groups after thousands are in in 2 digits, not 3 as in the western system.
var IS_SOUTH_ASIAN = true;
function int_to_words(int) {
if (int === 0) return 'zero';
var ONES_WORD = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
var TENS_WORD = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
var SCALE_WORD_WESTERN = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];
var SCALE_WORD_SOUTH_ASIAN = ['','thousand','lakh','crore','arab','kharab','neel','padma','shankh','***','***'];
var GROUP_SIZE = (typeof IS_SOUTH_ASIAN != "undefined" && IS_SOUTH_ASIAN) ? 2 : 3;
var SCALE_WORD = (typeof IS_SOUTH_ASIAN != "undefined" && IS_SOUTH_ASIAN) ? SCALE_WORD_SOUTH_ASIAN : SCALE_WORD_WESTERN;
// Return string of first three digits, padded with zeros if needed
function get_first_3(str) {
return ('000' + str).substr(-(3));
}
function get_first(str) { //-- Return string of first GROUP_SIZE digits, padded with zeros if needed, if group size is 2, make it size 3 by prefixing with a '0'
return (GROUP_SIZE == 2 ? '0' : '') + ('000' + str).substr(-(GROUP_SIZE));
}
// Return string of digits with first three digits chopped off
function get_rest_3(str) {
return str.substr(0, str.length - 3);
}
function get_rest(str) { // Return string of digits with first GROUP_SIZE digits chopped off
return str.substr(0, str.length - GROUP_SIZE);
}
// Return string of triplet convereted to words
function triplet_to_words(_3rd, _2nd, _1st) {
return (_3rd == '0' ? '' : ONES_WORD[_3rd] + ' hundred ') +
(_1st == '0' ? TENS_WORD[_2nd] : TENS_WORD[_2nd] && TENS_WORD[_2nd] + '-' || '') +
(ONES_WORD[_2nd + _1st] || ONES_WORD[_1st]); //-- 1st one returns one-nineteen - second one returns one-nine
}
// Add to result, triplet words with scale word
function add_to_result(result, triplet_words, scale_word) {
return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + result : result;
}
function recurse (result, scaleIdx, first, rest) {
if (first == '000' && rest.length === 0) return result;
var newResult = add_to_result (result, triplet_to_words (first[0], first[1], first[2]), SCALE_WORD[scaleIdx]);
return recurse (newResult, ++scaleIdx, get_first(rest), get_rest(rest));
}
return recurse ('', 0, get_first_3(String(int)), get_rest_3(String(int)));
}
Short answer:
[a[:,:j] for j in i]
What you are trying to do is not a vectorizable operation. Wikipedia defines vectorization as a batch operation on a single array, instead of on individual scalars:
In computer science, array programming languages (also known as vector or multidimensional languages) generalize operations on scalars to apply transparently to vectors, matrices, and higher-dimensional arrays.
...
... an operation that operates on entire arrays can be called a vectorized operation...
In terms of CPU-level optimization, the definition of vectorization is:
"Vectorization" (simplified) is the process of rewriting a loop so that instead of processing a single element of an array N times, it processes (say) 4 elements of the array simultaneously N/4 times.
The problem with your case is that the result of each individual operation has a different shape: (3, 1)
, (3, 2)
and (3, 3)
. They can not form the output of a single vectorized operation, because the output has to be one contiguous array. Of course, it can contain (3, 1)
, (3, 2)
and (3, 3)
arrays inside of it (as views), but that's what your original array a
already does.
What you're really looking for is just a single expression that computes all of them:
[a[:,:j] for j in i]
... but it's not vectorized in a sense of performance optimization. Under the hood it's plain old for
loop that computes each item one by one.
Actually, DB::connection('name')->select(..)
doesnt work for me, because 'name' has to be in double quotes: "name"
Still, the select query is executed on my default connection. Still trying to figure out, how to convince Laravel to work the way it is intended: change the connection.
Edit: I figured it out. After debugging Laravels DatabaseManager it turned out my database.php (config file) (inside $this->app) was wrong. In the section "connections" I had stuff like "database" with values of the one i copied it from. In clear terms, instead of
env('DB_DATABASE', 'name')
I needed to place something like
'myNewName'
since all connections were listed with the same values for the database, username, password, etc. which of course makes little sense if I want to access at least another database name
Therefore, every time I wanted to select something from another database I always ended up in my default database
I'd solve it with a javascript solution (jQUery) if the sizes can vary.
window.setTimeout(function () {
$(document).ready(function () {
var ResizeTarget = $('#B');
ResizeTarget.resize(function () {
var target = $('#B2');
target.css('height', ResizeTarget.height());
}).trigger('resize');
});
}, 500);
Alternative syntax using the -Not
operator and depending on your preference for readability:
if( -Not (Test-Path -Path $TARGETDIR ) )
{
New-Item -ItemType directory -Path $TARGETDIR
}
In regards to Gordon M's answer above, the 1st and 2nd parameter in mysqli_real_escape_string ()
call should be swapped for the newer php versions,
according to: http://php.net/manual/en/mysqli.real-escape-string.php
EDIT: Kanbanize is a commercial product and offers a 30 day free trial.
Disclosing: I am a co-founder of http://kanbanize.com/
Mark, I understand your desire to find the perfect application with all these features inside, but I really doubt that you will get it for free. There's a bunch of super cool apps (including Kanbanize) out there, but none of them is completely free.
Be careful what you call a Kanban board and what not, though. Trello is definitely NOT a kanban system (no WIP limits, no analytics, etc.). It is a great visual management system, but not a Kanban one.
Finally, to answer your question, tools that deserve attention in my opinion are: Kanbanize (of course), LeanKit, KanbanTool, Kanbanery and probably a few others. My personal bias is that LeanKit is the most advanced to date followed by Kanbanize and KanbanTool.
I hope that helps.
output=$(*command* 2>&1) && exit_status=$? || exit_status=$?
echo $output
echo $exit_status
Example of using this to create a log file
log_event(){
timestamp=$(date '+%D %T') #mm/dd/yy HH:MM:SS
echo -e "($timestamp) $event" >> "$log_file"
}
output=$(*command* 2>&1) && exit_status=$? || exit_status=$?
if [ "$exit_status" = 0 ]
then
event="$output"
log_event
else
event="ERROR $output"
log_event
fi
from datetime import date
def calculate_age(born):
today = date.today()
try:
birthday = born.replace(year=today.year)
except ValueError: # raised when birth date is February 29 and the current year is not a leap year
birthday = born.replace(year=today.year, month=born.month+1, day=1)
if birthday > today:
return today.year - born.year - 1
else:
return today.year - born.year
Update: Use Danny's solution, it's better
This should do the trick:
df[- grep("REVERSE", df$Name),]
Or a safer version would be:
df[!grepl("REVERSE", df$Name),]
class App():
def __init__(self):
self.root = Tkinter.Tk()
button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.root.destroy()
app = App()
Query string parameters can be accepted simply by using an argument on the action - i.e.
public ActionResult Foo(string someValue, int someOtherValue) {...}
which will accept a query like .../someroute?someValue=abc&someOtherValue=123
Other than that, you can look at the request directly for more control.
I think the reason may be that mock object libraries typically create mocks by dynamically creating classes at runtime (using cglib). This means they either implement an interface at runtime (that's what EasyMock does if I'm not mistaken), or they inherit from the class to mock (that's what Mockito does if I'm not mistaken). Both approaches do not work for static members, since you can't override them using inheritance.
The only way to mock statics is to modify a class' byte code at runtime, which I suppose is a little more involved than inheritance.
That's my guess at it, for what it's worth...
This is usually the problem with web.xml descriptor file. May be you have mixed up the annotations and web.xml servlet description definitions. Please check the console for more information.
You have to catch the error just as you're already doing for your save()
call and since you're handling multiple errors here, you can try
multiple calls sequentially in a single do-catch block, like so:
func deleteAccountDetail() {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
do {
let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
} catch {
print(error)
}
}
Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws
then try
to call the method. For example:
func deleteAccountDetail() throws {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
}
If you are wrapping the RatingBar
inside a ConstraintLayout
with match_constraint
for its width, the editor preview is going to show a number of stars proportional to its actual width, no matter what if you set android:numStars
property. Use wrap_content
to get the correct preview:
<RatingBar android:id="@+id/myRatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="48dp"
android:layout_marginEnd="48dp"
android:numStars="5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent" />
There is no good solution to your problem, so here is an okey solution ;-)
It keeps your efficiency when assertions are disabled and when assertions are enabled it will raise an assertion error when the hash value is wrong.
I suspect that the D programming language could compute the hash value during compile time, thus removing the need to explicitly write down the hash value.
template <std::size_t h>
struct prehash
{
const your_string_type str;
static const std::size_t hash_value = h;
pre_hash(const your_string_type& s) : str(s)
{
assert(_myhash(s) == hash_value);
}
};
/* ... */
std::size_t h = _myhash(mystring);
static prehash<66452> first_label = "label1";
switch (h) {
case first_label.hash_value:
// ...
;
}
By the way, consider removing the initial underscore from the declaration of _ myhash() (sorry but stackoverflow forces me to insert a space between _ and myhash). A C++ implementation is free to implement macros with names starting with underscore and an uppercase letter (Item 36 of "Exceptional C++ Style" by Herb Sutter), so if you get into the habit of giving things names that start underscore, then a beautiful day could come when you give a symbol a name that starts with underscore and an uppercase letter, where the implementation has defined a macro with the same name.
First you need to make sure if both of your files are in the same working directory. Next, you can import the whole file. For example,
import myClass
or you can import the entire class and entire functions from the file. For example,
from myClass import
Finally, you need to create an instance of the class from the original file and call the instance objects.
for multiple classes situation, as @jbojcic mentioned above, you can use:
host: {class: 'A B C'}
(I don't have enough rep points to add a comment, but I want to add some clarity on the answers here)
Application.AskToUpdateLinks = False is probably not what you want.
If set to False, then MS Excel will attempt to update the links automatically it just won't prompt the user beforehand, sorta counter-intuitive.
The correct solution, if you're looking to open a file without updating links should be:
Workbook.Open(UpdateLinks:=0)
Related link: Difference in AskToUpdateLinks=False and UpdateLinks:=0
Comparator
provides a way for you to provide custom comparison logic for types that you have no control over.
Comparable
allows you to specify how objects that you are implementing get compared.
Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator
.
Otherwise you can use Comparable
.
DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed
In CentOS, RedHat, etc. use below command. don't forget to restart the Apache. Because the PHP module has to be loaded.
yum -y install php-gd
service httpd restart
I suspect there is something wrong either with your Git installation or your repository.
Try running:
GIT_TRACE=2 git <command>
See if you get anything useful. If that doesn't help, just use strace and see what's going wrong:
strace git <command>
This answer address the topic/question
OR
basically what happens is
When you make a factory()
it sets you function
provided in second argument to provider's $get
and return it(provider(name, {$get:factoryFn })
), all you get is provider
but there is no property/method other than $get
of that provider
(means you can't configure this)
Source code of factory
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
});
};
When making a service()
it return you providing a factory() with a function
that injects the constructor
(return the instance of the constructor you provided in your service) and returns it
Source code of service
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
};
So basically in both cases you eventually get a providers $get set to your function you provided , but you can give anything extra than $get as you can originally provide in provider() for config block
function confirmDetete(ctl, event) {
debugger;
event.preventDefault();
var defaultAction = $(ctl).prop("href");
swal({
title: "Are you sure?",
text: "You will be able to add it back again!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "Cancel",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
$.get(ctl);
swal({
title: "success",
text: "Deleted",
confirmButtonText: "ok",
allowOutsideClick: "true"
}, function () { window.location.href = ctl })
// $("#signupform").submit();
} else {
swal("Cancelled", "Is safe :)", "success");
}
});
}
I am working with code first, C# 7 and entity framework 6.0.0.0. it works for me
Add()
{
bool isDuplicate = false;
try
{
//add to database
}
catch (DbUpdateException ex)
{
if (dbUpdateException.InnerException != null)
{
var sqlException = dbUpdateException.InnerException.InnerException as SqlException;
if(sqlException != null)
isDuplicate = IsDuplicate(sqlException);
}
}
catch (SqlException ex)
{
isDuplicate = IsDuplicate(ex);
}
if(isDuplicate){
//handle here
}
}
bool IsDuplicate(SqlException sqlException)
{
switch (sqlException.Number)
{
case 2627:
return true;
default:
return false;
}
}
N.B: my query for add item to db is in another project(layer)
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
This would definitely help Many!
private void axWindowsMediaPlayer1_ClickEvent(object sender, AxWMPLib._WMPOCXEvents_ClickEvent e)
{
if(e.nButton==2)
{
contextMenuStrip1.Show(MousePosition);
}
}
[ e.nbutton==2 ] is like [ e.button==MouseButtons.Right ]
Convert the CommandField to a TemplateField and set the visible property of the button based on the value of the field (true/false)
<asp:Button ID="btnSelect"
runat="server" Text="Select"
Visible='<%# DataBinder.Eval(Container.DataItem,"IsLeaf") %>'/>
I had a problem also with .env variables not loading and being undefined
.
What I tried:
index.js:
import dotenv from 'dotenv';
dotenv.config();
import models from './models';
models.js
import Sequelize from 'sequelize';
const sequelize = new Sequelize(
process.env.DATABASE,
process.env.DATABASE_USER,
process.env.DATABASE_PASSWORD,
{
dialect: 'postgres',
}
);
Apparently, because of how loading the imports works in nodejs, the import of models in index.js
caused that the models.js was executed before dotenv.config()
. Therefore I got undefined values from process.env.
When I changed models.js to do the dotenv configuration like:
import Sequelize from 'sequelize';
import dotenv from 'dotenv';
dotenv.config();
const sequelize = new Sequelize(
process.env.DATABASE,
process.env.DATABASE_USER,
process.env.DATABASE_PASSWORD,
{
dialect: 'postgres',
}
);
it started to work!
I use ngrok (https://ngrok.com/) for this. ngrok is a command line tool and create a tunnel for localhost. It creates both http and https connection. After downloading it, following command needs to be run :
ngrok http 80
( In version 2, the syntax is : ngrok http 80 . In version 2, any port can be tunneled. )
After few seconds, it will give two urls :
http://a_hexadecimal_number.ngrok.com
https://a_hexadecimal_number.ngrok.com
Now, both the urls point to the localhost.
This one worked for me
//Javascript part_x000D_
//file_input is a file input id_x000D_
var formData = new FormData();_x000D_
var filesLength=document.getElementById('file_input').files.length;_x000D_
for(var i=0;i<filesLength;i++){_x000D_
formData.append("file[]", document.getElementById('file_input').files[i]);_x000D_
}_x000D_
$.ajax({_x000D_
url: 'upload.php',_x000D_
type: 'POST',_x000D_
data: formData,_x000D_
contentType: false,_x000D_
cache: false,_x000D_
processData: false,_x000D_
success: function (html) {_x000D_
_x000D_
}_x000D_
});
_x000D_
<?php_x000D_
//PHP part_x000D_
$file_names = $_FILES["file"]["name"];_x000D_
for ($i = 0; $i < count($file_names); $i++) {_x000D_
$file_name=$file_names[$i];_x000D_
$extension = end(explode(".", $file_name));_x000D_
$original_file_name = pathinfo($file_name, PATHINFO_FILENAME);_x000D_
$file_url = $original_file_name . "-" . date("YmdHis") . "." . $extension;_x000D_
move_uploaded_file($_FILES["file"]["tmp_name"][$i], $absolute_destination . $file_url);_x000D_
}
_x000D_
As you have figured out that you cannot do it the way you have done in Java (or C#). Here is another suggestion, you could pass in the reference of the object as an argument and return bool value. If the result is found in your collection, you could assign it to the reference being passed and return ‘true’, otherwise return ‘false’. Please consider this code.
typedef std::map<string, Operator> OPERATORS_MAP;
bool OperatorList::tryGetOperator(string token, Operator& op)
{
bool val = false;
OPERATORS_MAP::iterator it = m_operators.find(token);
if (it != m_operators.end())
{
op = it->second;
val = true;
}
return val;
}
The function above has to find the Operator against the key 'token', if it finds the one it returns true and assign the value to parameter Operator& op.
The caller code for this routine looks like this
Operator opr;
if (OperatorList::tryGetOperator(strOperator, opr))
{
//Do something here if true is returned.
}
In addition to the locations listed above, the OS X version of Perl also has two more ways:
The /Library/Perl/x.xx/AppendToPath file. Paths listed in this file are appended to @INC at runtime.
The /Library/Perl/x.xx/PrependToPath file. Paths listed in this file are prepended to @INC at runtime.
Relative:
An element with position: relative;
is positioned relative to its normal position.
If you add no positioning attributes (top, left, bottom or right) on a relative element it will have no effect on it's positioning at all. It will behave exactly as a position: static
element.
But if you do add some other positioning attribute, say, top: 10px;, it will shift its position 10 pixels down from where it would normally be.
An element with this type of positioning gets affected by other elements and it itself also affects others.
Absolute:
An element with position: absolute;
allows you to place any element exactly where you want it to be. You use the positioning attributes top, left, bottom. and right to set the location.
It is placed relative to the nearest non-static ancestor. If there is no such container, it is placed relative to the page itself.
It gets removed from the normal flow of elements on the page.
An element with this type of positioning is not affected by other elements and also it doesn't affect flow of other elements.
See this self-explanatory example for better clarity. https://codepen.io/nyctophiliac/pen/BJMqjX
Just Delete the (obj)Object folder in project folder then Run the application then It will work fine. Steps:
Oracle would be
SELECT NVL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1;
You can just add moveTaskToBack(true)
in your exit button's onClickedListener
to minimize the application.
Hope it helps.
I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).
The only difference would be if you try to reassign it before the end of this very file.
ok. I tried the above two ways but it didnt work for me. After trial and error i came to know that actually the file was not getting saved in 'this.state.file' variable.
fileUpload = (e) => {
let data = e.target.files
if(e.target.files[0]!=null){
this.props.UserAction.fileUpload(data[0], this.fallBackMethod)
}
}
here fileUpload is a different js file which accepts two params like this
export default (file , callback) => {
const formData = new FormData();
formData.append('fileUpload', file);
return dispatch => {
axios.put(BaseUrl.RestUrl + "ur/url", formData)
.then(response => {
callback(response.data);
}).catch(error => {
console.log("***** "+error)
});
}
}
don't forget to bind method in the constructor. Let me know if you need more help in this.
To get the first n
elements of an array, use
array.slice(0, n);
There are necessary steps that are missing in the above answers to work for all levels of devs:
... looking for an equivalent in python of
dict.get(key, default)
for lists
There is an itertools recipes that does this for general iterables. For convenience, you can > pip install more_itertools
and import this third-party library that implements such recipes for you:
Code
import more_itertools as mit
mit.nth([1, 2, 3], 0)
# 1
mit.nth([], 0, 5)
# 5
Detail
Here is the implementation of the nth
recipe:
def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(itertools.islice(iterable, n, None), default)
Like dict.get()
, this tool returns a default for missing indices. It applies to general iterables:
mit.nth((0, 1, 2), 1) # tuple
# 1
mit.nth(range(3), 1) # range generator (py3)
# 1
mit.nth(iter([0, 1, 2]), 1) # list iterator
# 1
if the error looks like this
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module:
dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/_mysql.so, 2): Library not loaded:
/usr/local/opt/mysql/lib/libmysqlclient.20.dylib
Referenced from: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/_mysql.so
then try :
pip install python-mysqldb
I'm guessing you get the error on accessing audioSounds
and minTime
, right?
The problem is you can't access instance members
from static methods
. What this means is that, a static method is a method that exists only once and can be used by all other objects (if its access modifier permits it).
Instance members, on the other hand, are created for every instance of the object. So if you create ten instances, how would the runtime know out of all these instances, which audioSounds
list it should access?
Like others said, make your audioSounds
and minTime
static, or you could make your method an instance method, if your design permits it.
In Java 8 for an Obj
entity with field
and getField() method you can use:
List<Obj> objs ...
Stream<Obj> notNullObjs =
objs.stream().filter(obj -> obj.getValue() != null);
Double sum = notNullObjs.mapToDouble(Obj::getField).sum();
Yes - just do it this way:
WITH DependencedIncidents AS
(
....
),
lalala AS
(
....
)
You don't need to repeat the WITH
keyword
You can do it easily with grep:
grep -oE '[^ ]+$' file
(-E
use extended regex; -o
output only the matched text instead of the full line)
string.Format
is your friend.
String.Format("{0:0.00}", 123.4567); // "123.46"
Use this PRINT BIG
function to output everything:
IF OBJECT_ID('tempdb..#printBig') IS NOT NULL
DROP PROCEDURE #printBig
GO
CREATE PROCEDURE #printBig (
@text NVARCHAR(MAX)
)
AS
--DECLARE @text NVARCHAR(MAX) = 'YourTextHere'
DECLARE @lineSep NVARCHAR(2) = CHAR(13) + CHAR(10) -- Windows \r\n
DECLARE @off INT = 1
DECLARE @maxLen INT = 4000
DECLARE @len INT
WHILE @off < LEN(@text)
BEGIN
SELECT @len =
CASE
WHEN LEN(@text) - @off - 1 <= @maxLen THEN LEN(@text)
ELSE @maxLen
- CHARINDEX(REVERSE(@lineSep), REVERSE(SUBSTRING(@text, @off, @maxLen)))
- LEN(@lineSep)
+ 1
END
PRINT SUBSTRING(@text, @off, @len)
--PRINT '@off=' + CAST(@off AS VARCHAR) + ' @len=' + CAST(@len AS VARCHAR)
SET @off += @len + LEN(@lineSep)
END
Source:
Say P7 is a Cell then you can use the following Syntex to check the value of the cell and assign appropriate value to another cell based on this following nested if:
=IF(P7=0,200,IF(P7=1,100,IF(P7=2,25,IF(P7=3,10,IF((P7=4),5,0)))))
you can try as follows
File dir = new File("path");
if (dir.isDirectory())
{
dir.delete();
}
If there are sub folders inside your folder you may need to recursively delete them.
This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.
You can call the mklink
provided by cmd
, from PowerShell to make symbolic links:
cmd /c mklink c:\path\to\symlink c:\target\file
You must pass /d
to mklink
if the target is a directory.
cmd /c mklink /d c:\path\to\symlink c:\target\directory
For hard links, I suggest something like Sysinternals Junction.
You're calculating the y-part of your new coordinate based on the 'new' x-part of the new coordinate. Basically this means your calculating the new output in terms of the new output...
Try to rewrite in terms of input and output:
vector2<double> multiply( vector2<double> input, double cs, double sn ) {
vector2<double> result;
result.x = input.x * cs - input.y * sn;
result.y = input.x * sn + input.y * cs;
return result;
}
Then you can do this:
vector2<double> input(0,1);
vector2<double> transformed = multiply( input, cs, sn );
Note how choosing proper names for your variables can avoid this problem alltogether!
I Following this thought to guide the development object-oriented Perl.
Bless associate any data structure reference with a class. Given how Perl creates the inheritance structure (in a kind of tree) it is easy to take advantage of the object model to create Objects for composition.
For this association we called object, to develop always have in mind that the internal state of the object and class behaviours are separated. And you can bless/allow any data reference to use any package/class behaviours. Since the package can understand "the emotional" state of the object.
The command above worked for me
C:\Users\marcelo\Downloads\vs_community.exe --lang en-en --layout C:\VisualStudio2017 --all
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
Even I faced this issue and solved it with 2 ways:
1) In your IDE select project and clean all projects then install all the maven dependencies by right clicking on project -> go to maven and Update project dependencies select all projects at once to install the same. Once this is done run the particular project
2) Else What you can do is check in the pom.xml for the dependencies for which you are getting error and "mvn clean install" those dependent project first and the install maven dependencies of the current project in which you facing issue. By this the dependencies of the local project will be build and jars will be created.
In node.js you can also do the following:
const { promisify } = require('util')
const delay = promisify(setTimeout)
delay(1000).then(() => console.log('hello'))
http://www.program-transformation.org/Transform/VisualBasicDecompilers
This link provides a lot of resources for VB6 Decompiling, but it seems like it will depend greatly on what you DO have (do you still have the pre-link Object code [EDIT: er... p-code I mean], or just the EXE?) Either way, it looks like there's something, take a look in there.
This probably isn't the optimal solution but you might download and install the free Visual C++ Express package from MS. This will give you the C++ compiler you need to compile the PyCrypto code.
First, convert the string into a timestamp:
$timestamp = strtotime($string);
Then do a
date("Y-m-d H:i:s", $timestamp);
Try to use:
require('events').EventEmitter.defaultMaxListeners = Infinity;
I also had an issue with a slow IDE.
In my case I installed
The following helped me a bit:
Uninstalled JetBrain's Resharper - WOW!! I am fast again!!
It is correct that rm –rf .
will remove everything in the current directly including any subdirectories and their content. The single dot (.
) means the current directory. be carefull not to do rm -rf ..
since the double dot (..
) means the previous directory.
This being said, if you are like me and have multiple terminal windows open at the same time, you'd better be safe and use rm -ir .
Lets look at the command arguments to understand why.
First, if you look at the rm
command man page (man rm
under most Unix) you notice that –r
means "remove the contents of directories recursively". So, doing rm -r .
alone would delete everything in the current directory and everything bellow it.
In rm –rf .
the added -f means "ignore nonexistent files, never prompt". That command deletes all the files and directories in the current directory and never prompts you to confirm you really want to do that. -f
is particularly dangerous if you run the command under a privilege user since you could delete the content of any directory without getting a chance to make sure that's really what you want.
On the otherhand, in rm -ri .
the -i
that replaces the -f
means "prompt before any removal". This means you'll get a chance to say "oups! that's not what I want" before rm goes happily delete all your files.
In my early sysadmin days I did an rm -rf /
on a system while logged with full privileges (root). The result was two days passed a restoring the system from backups. That's why I now employ rm -ri
now.
1) 51,983 is a string type number does not accept comma
so u should set it as text
<input type="text" name="commanumber" id="commanumber" value="1,99" step='0.01' min='0' />
replace , with .
and change type attribute to number
$(document).ready(function() {
var s = $('#commanumber').val().replace(/\,/g, '.');
$('#commanumber').attr('type','number');
$('#commanumber').val(s);
});
Check out http://jsfiddle.net/ydf3kxgu/
Hope this solves your Problem
If you are inheriting from a fragment you can do:
Drawable drawable = getActivity().getDrawable(R.drawable.icon)
If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:
import subprocess
# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"
# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"
subprocess.Popen([python_bin, script_file])
However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py
script:
# Doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
execfile(activate_this_file, dict(__file__=activate_this_file))
If your task is performing some kind of action in a loop there is a way to pause/restart processing, but I think it would have to be outside what the Thread API currently offers. If its a single shot process I am not aware of any way to suspend/restart without running into API that has been deprecated or is no longer allowed.
As for looped processes, the easiest way I could think of is that the code that spawns the Task instantiates a ReentrantLock and passes it to the task, as well as keeping a reference itself. Every time the Task enters its loop it attempts a lock on the ReentrantLock instance and when the loop completes it should unlock. You may want to encapsulate all this try/finally, making sure you let go of the lock at the end of the loop, even if an exception is thrown.
If you want to pause the task simply attempt a lock from the main code (since you kept a reference handy). What this will do is wait for the loop to complete and not let it start another iteration (since the main thread is holding a lock). To restart the thread simply unlock from the main code, this will allow the task to resume its loops.
To permanently stop the thread I would use the normal API or leave a flag in the Task and a setter for the flag (something like stopImmediately). When the loop encountered a true value for this flag it stops processing and completes the run method.
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
document.body.appendChild(link); // Firefox requires the link to be in the body
link.download = filename;
link.href = uri;
link.click();
document.body.removeChild(link); // remove the link when done
} else {
location.replace(uri);
}
}
jQuery can handle JSONP, just pass an url formatted with the callback=? parameter to the $.getJSON
method, for example:
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
console.log(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
This example is of a really simple JSONP service implemented on with api.ipify.org
.
If you aren't looking for a cross-domain solution the script can be simplified even more, since you don't need the callback parameter, and you return pure JSON.
Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?
There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.
Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.
In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.
i really disadvise you against using Thread.Sleep(2000)
, because of a several reasons (a few are described here), but most of all because its not useful when it comes to debugging/testing.
I recommend to use a C# Timer instead of Thread.Sleep()
. Timers let you perform methods frequently (if necessary) AND are much easiert to use in testing! There's a very nice example of how to use a timer right behind the hyperlink - just put your logic "what happens after 2 seconds" right into the Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
method.
You could simply do:
Select Req_ID, (avg(R1)+avg(R2)+avg(R3)+avg(R4)+avg(R5))/5 as Average
from Request
Group by Req_ID
Right?
I'm assuming that you may have multiple rows with the same Req_ID and in these cases you want to calculate the average across all columns and rows for those rows with the same Req_ID
Last 5 rows retrieve in mysql
This query working perfectly
SELECT * FROM (SELECT * FROM recharge ORDER BY sno DESC LIMIT 5)sub ORDER BY sno ASC
or
select sno from(select sno from recharge order by sno desc limit 5) as t where t.sno order by t.sno asc
There are few methods :
1. typeof tells you which one of the 6 javascript types is the object.
2. instanceof tells you if the object is an instance of another object.
3. List properties with for(var k in obj)
4. Object.getOwnPropertyNames( anObjectToInspect )
5. Object.getPrototypeOf( anObject )
6. anObject.hasOwnProperty(aProperty)
In a console context, sometimes the .constructor or .prototype maybe useful:
console.log(anObject.constructor );
console.log(anObject.prototype ) ;
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
You could put it in the session:
session_start();
$_SESSION['array_name'] = $array_name;
Or if you want to send it via a form you can serialize it:
<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />
$passed_array = unserialize($_POST['input_name']);
Note that to work with serialized arrays, you need to use POST as the form's transmission method, as GET has a size limit somewhere around 1024 characters.
I'd use sessions wherever possible.
FYI: The other solutions will only log statements from the default database—usually postgres
—to log others; start with their solution; then:
ALTER DATABASE your_database_name
SET log_statement = 'all';
While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:
<script type="text/javascript">
function parse(a, b, c) {
alert(c);
}
</script>
<a href="#x" onclick="parse('#', false, 'xyc"foo');return false;">Test</a>
The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
You need python-dev installed.
For Ubuntu :
sudo apt-get install python-dev # for python2.x installs
sudo apt-get install python3-dev # for python3.x installs
For more distros, refer -
https://stackoverflow.com/a/21530768/6841045
SERIOUS DISCLAIMER
This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.
OK, I had to go to the customer premises and found a solution. I:
Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!
I would actually do the following.
Have my hidden input field with the same name with the checkbox input
<input type="hidden" name="checkbox_name[]" value="0" />
<input type="checkbox" name="checkbox_name[]" value="1" />
and then when i post I first of all remove the duplicate values picked up in the $_POST array, atfer that display each of the unique values.
$posted = array_unique($_POST['checkbox_name']);
foreach($posted as $value){
print $value;
}
I got this from a post remove duplicate values from array
string[] coleccion = Directory.GetFiles(inputPath)
.Select(x => new FileInfo(x).Name)
.ToArray();
An alternative solution to floats is to use absolute positioning:
.title {
position: relative;
}
.title span:last-child {
position: absolute;
right: 6px; /* must be equal to parent's right padding */
}
See also the fiddle.
I feel it would be helpful for someone who is looking for passing the array in a query string to a servlet. I tested below query string and was able to get the array values using req.getgetParameterValues(); method. Below is the query string I passed through browser.
http://localhost:8080/ServletsTutorials/*.html?
myname=abc&initial=xyz&checkbox=a&checkbox=b
checkbox is my parameter array here.
Step 1: Create HTML Page where to place the HTML Code.
Step 2: In the HTML Code Page Bottom(footer)Create Javascript: and put Jquery Code in Script tag.
Step 3: Create PHP File and php code copy past. after Jquery Code in $.ajax
Code url apply which one on your php file name.
JS
//$(document).on("change", "#avatar", function() { // If you want to upload without a submit button
$(document).on("click", "#upload", function() {
var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
url: "/upload_avatar", // Upload Script
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
// Do something after Ajax completes
}
});
});
HTML
<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />
Php
print_r($_FILES);
print_r($_POST);
One way this can be done is using shell script in global environment section, here, I am using UNIX timestamp but you can use any shell script syntax compatible time format:
pipeline {
agent any
environment {
def BUILDVERSION = sh(script: "echo `date +%s`", returnStdout: true).trim()
}
stages {
stage("Awesome Stage") {
steps {
echo "Current build version :: $BUILDVERSION"
}
}
}
}
I am adding more points to the solution by @Rushi Shah
mvn clean install -X
helps to identify the root cause.
Some of the important phases of Maven build lifecycle are:
clean
– the project is clean of all artifacts that came from previous compilations
compile
– the project is compiled into /target directory of project root
install
– packaged archive is copied into local maven repository (could in your user's home directory under /.m2)
test
– unit tests are run
package
– compiled sources are packaged into archive (JAR by default)
The 1.6 under tag refers to JDK version. We need to ensure that proper jdk version in our dev environment or change the value to 1.7 or 1.5 or whatever if the application can be supported in that JDK version.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
We can find the complete details on Maven build lifecycle in Maven site.
Use the attribute selector
[id^=product]{property:value}
This is the fastest way:
if ($coll->isEmpty()) {...}
Other solutions like count
do a bit more than you need which costs slightly more time.
Plus, the isEmpty()
name quite precisely describes what you want to check there so your code will be more readable.
In the case of named lists I find those helper functions useful
member <- function(list,names){
## return the elements of the list with the input names
member..names <- names(list)
index <- which(member..names %in% names)
list[index]
}
exclude <- function(list,names){
## return the elements of the list not belonging to names
member..names <- names(list)
index <- which(!(member..names %in% names))
list[index]
}
aa <- structure(list(a = 1:10, b = 4:5, fruits = c("apple", "orange"
)), .Names = c("a", "b", "fruits"))
> aa
## $a
## [1] 1 2 3 4 5 6 7 8 9 10
## $b
## [1] 4 5
## $fruits
## [1] "apple" "orange"
> member(aa,"fruits")
## $fruits
## [1] "apple" "orange"
> exclude(aa,"fruits")
## $a
## [1] 1 2 3 4 5 6 7 8 9 10
## $b
## [1] 4 5
try this one
npm cache clean --force
after that run
npm cache verify
Building upon the fiddle from @tim, this version tightens the scope and formatting, and converts bind()
-> on()
. It's designed to bind on a dedicated td
as the handle instead of the entire row. In my use case, I have input
fields so the "drag anywhere on the row" approach felt confusing.
Tested working on desktop. Only partial success with mobile touch. Can't get it to run correctly on SO's runnable snippet for some reason...
let ns = {
drag: (e) => {
let el = $(e.target),
d = $('body'),
tr = el.closest('tr'),
sy = e.pageY,
drag = false,
index = tr.index();
tr.addClass('grabbed');
function move(e) {
if (!drag && Math.abs(e.pageY - sy) < 10)
return;
drag = true;
tr.siblings().each(function() {
let s = $(this),
i = s.index(),
y = s.offset().top;
if (e.pageY >= y && e.pageY < y + s.outerHeight()) {
i < tr.index() ? s.insertAfter(tr) : s.insertBefore(tr);
return false;
}
});
}
function up(e) {
if (drag && index !== tr.index())
drag = false;
d.off('mousemove', move).off('mouseup', up);
//d.off('touchmove', move).off('touchend', up); //failed attempt at touch compatibility
tr.removeClass('grabbed');
}
d.on('mousemove', move).on('mouseup', up);
//d.on('touchmove', move).on('touchend', up);
}
};
$(document).ready(() => {
$('body').on('mousedown touchstart', '.drag', ns.drag);
});
_x000D_
.grab {
cursor: grab;
user-select: none
}
tr.grabbed {
box-shadow: 4px 1px 5px 2px rgba(0, 0, 0, 0.5);
}
tr.grabbed:active {
user-input: none;
}
tr.grabbed:active * {
user-input: none;
cursor: grabbing !important;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th></th>
<th>Drag the rows below...</th>
</tr>
</thead>
<tbody>
<tr>
<td class='grab'>⋮</td>
<td><input type="text" value="Row 1" /></td>
</tr>
<tr>
<td class='grab'>⋮</td>
<td><input type="text" value="Row 2" /></td>
</tr>
<tr>
<td class='grab'>⋮</td>
<td><input type="text" value="Row 3" /></td>
</tr>
</tbody>
</table>
_x000D_
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
What we are looking at here is called specificity as stated by Mozilla:
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.
Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector. When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted by multiple declarations. As per CSS rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor.
I like the 0-0-0 explanation at https://specifishity.com:
Quite descriptive the picture of the !important
directive! But sometimes it's the only way to override the inline style
attribute. So it's a best practice trying to avoid both.
I encountered the same error while using SpringBoot 2.1.4, along with Spring Security 5 (I believe). After one day of trying everything that Google had to offer, I discovered the cause of error in my case. I had a setup of micro-services, with the Auth server being different from the Resource Server. I had the following lines in my application.yml which prevented 'auto-configuration' despite of having included dependencies spring-boot-starter-security
, spring-security-oauth2
and spring-security-jwt
. I had included the following in the properties (during development) which caused the error.
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Commenting it out solved it for me.
#spring:
# autoconfigure:
# exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Hope, it helps someone.
You are using Python 2 methodology instead of Python 3.
Change:
outfile=open('./immates.csv','wb')
To:
outfile=open('./immates.csv','w')
and you will get a file with the following output:
SNo,States,Dist,Population
1,Andhra Pradesh,13,49378776
2,Arunachal Pradesh,16,1382611
3,Assam,27,31169272
4,Bihar,38,103804637
5,Chhattisgarh,19,25540196
6,Goa,2,1457723
7,Gujarat,26,60383628
.....
In Python 3 csv takes the input in text mode, whereas in Python 2 it took it in binary mode.
Edited to Add
Here is the code I ran:
url='http://www.mapsofindia.com/districts-india/'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
table=soup.find('table', attrs={'class':'tableizer-table'})
list_of_rows=[]
for row in table.findAll('tr')[1:]:
list_of_cells=[]
for cell in row.findAll('td'):
list_of_cells.append(cell.text)
list_of_rows.append(list_of_cells)
outfile = open('./immates.csv','w')
writer=csv.writer(outfile)
writer.writerow(['SNo', 'States', 'Dist', 'Population'])
writer.writerows(list_of_rows)
// timestamp to Date
long timestamp = 5607059900000; //Example -> in ms
Date d = new Date(timestamp );
// Date to timestamp
long timestamp = d.getTime();
//If you want the current timestamp :
Calendar c = Calendar.getInstance();
long timestamp = c.getTimeInMillis();
In jQuery e
short for event
, the current event object. It's usually passed as a parameter for the event function to be fired.
Demo: jQuery Events
In the demo I used e
$("img").on("click dblclick mouseover mouseout",function(e){
$("h1").html("Event: " + e.type);
});
I may as well have used event
$("img").on("click dblclick mouseover mouseout",function(event){
$("h1").html("Event: " + event.type);
});
Same thing!
Programmers are lazy we use a lot of shorthand, partly it decreases our work, partly is helps with readability. Understanding that will help you understand the mentality of writing code.
I posted the technique I use to deal with these here
Try to set processData: false in ajax settings like this
$.ajax({
url : base_url+'index.php',
type: 'POST',
dataType: 'json',
data: data,
cache : false,
processData: false
}).done(function(response) {
alert(response);
});
The canvas
element provides a toDataURL
method which returns a data:
URL that includes the base64-encoded image data in a given format. For example:
var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default
Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.
The toDataURL
method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.
For more information see the MDN docs on the canvas
API, which includes details on toDataURL
, and the Wikipedia article on the data:
URI scheme, which includes details on the format of the URI you'll receive from this call.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
Simply use the base transpose function t
, wrapped with as.data.frame
:
final_df <- as.data.frame(t(starting_df))
final_df
A B C D
a 1 2 3 4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd
Above updated. As docendo discimus pointed out, t
returns a matrix. As Mark suggested wrapping it with as.data.frame
gets back a data frame instead of a matrix. Thanks!
You have to use new operator here to instantiate. For example:
Contacts.add(new Data(name, address, contact));
It does seem you would have to use a MessageBodyReader
here. Here's an example, using jdom:
import org.jdom.Document;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MediaType;
import javax.ws.rs.ext.MultivaluedMap;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.InputStream;
@Provider // this annotation is necessary!
@ConsumeMime("application/xml") // this is a hint to the system to only consume xml mime types
public class XMLMessageBodyReader implements MessageBodyReader<Document> {
private SAXBuilder builder = new SAXBuilder();
public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
// check if we're requesting a jdom Document
return Document.class.isAssignableFrom(type);
}
public Document readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
try {
return builder.build(entityStream);
}
catch (Exception e) {
// handle error somehow
}
}
}
Add this class to the list of resources your jersey deployment will process (usually configured via web.xml, I think). You can then use this reader in one of your regular resource classes like this:
@Path("/somepath") @POST
public void handleXMLData(Document doc) {
// do something with the document
}
I haven't verified that this works exactly as typed, but that's the gist of it. More reading here:
Use the constants defined in the math package:
const (
MaxInt8 = 1<<7 - 1
MinInt8 = -1 << 7
MaxInt16 = 1<<15 - 1
MinInt16 = -1 << 15
MaxInt32 = 1<<31 - 1
MinInt32 = -1 << 31
MaxInt64 = 1<<63 - 1
MinInt64 = -1 << 63
MaxUint8 = 1<<8 - 1
MaxUint16 = 1<<16 - 1
MaxUint32 = 1<<32 - 1
MaxUint64 = 1<<64 - 1
)
$(document).ready(function() {
window.setTimeout(function(){window.location.href = "https://www.google.co.in"},5000);
});
Of course it's approximate; that is how math with floating-point numbers work.
Anyway, the standard way is with Newton's method. This is about the same as using Taylor's series, the other way that comes to mind immediately.
Since neither of the above worked for me, here's what did: android:scrollbarDefaultDelayBeforeFade="500000"
var divss = 0;
$(function(){
$("#foo div").each(function(){
divss++;
});
console.log(divss);
});
<div id="foo">
<div id="bar" class="1"></div>
<div id="baz" class="1"></div>
<div id="bam" class="1"></div>
</div>
Firstly, you must understand that DataFrames
are distributed, that means you can't access them in a typical procedural way, you must do an analysis first. Although, you are asking about Scala
I suggest you to read the Pyspark Documentation, because it has more examples than any of the other documentations.
However, continuing with my explanation, I would use some methods of the RDD
API cause all DataFrame
s have one RDD
as attribute. Please, see my example bellow, and notice how I take the 2nd record.
df = sqlContext.createDataFrame([("a", 1), ("b", 2), ("c", 3)], ["letter", "name"])
myIndex = 1
values = (df.rdd.zipWithIndex()
.filter(lambda ((l, v), i): i == myIndex)
.map(lambda ((l,v), i): (l, v))
.collect())
print(values[0])
# (u'b', 2)
Hopefully, someone gives another solution with fewer steps.
I solved this problem by closing Eclipse and restarting it again. Eclipse sometimes fails to establish a connection with the Emulator/device, so this can happen sometimes.
How about a slightly simplified version of @Morten Christiansen's nice extension method idea:
public static object Execute(this IWebDriver driver, string script)
{
return ((IJavaScriptExecutor)driver).ExecuteScript(script);
}
// usage
var title = (string)driver.Execute("return document.title");
or maybe the generic version:
public static T Execute<T>(this IWebDriver driver, string script)
{
return (T)((IJavaScriptExecutor)driver).ExecuteScript(script);
}
// usage
var title = driver.Execute<string>("return document.title");
we can easily print the current time and date using echo
and system
variables as below.
echo %DATE% %TIME%
output example: 13-Sep-19 15:53:05.62
The answers provided by other folks (Ben James) are quite good and I have used them. As user889030 points out, the last array element may be empty. Actually, the first and last array elements can be empty. The code below addresses both issues.
# Split an input string into an array of substrings using any set
# whitespace characters
function explode_whitespace($str) {
# Split the input string into an array
$parts = preg_split('/\s+/', $str);
# Get the size of the array of substrings
$sizeParts = sizeof($parts);
# Check if the last element of the array is a zero-length string
if ($sizeParts > 0) {
$lastPart = $parts[$sizeParts-1];
if ($lastPart == '') {
array_pop($parts);
$sizeParts--;
}
# Check if the first element of the array is a zero-length string
if ($sizeParts > 0) {
$firstPart = $parts[0];
if ($firstPart == '')
array_shift($parts);
}
}
return $parts;
}
Just to add a different option - I use Node-DBI to connect to PG, but also due to the ability to talk to MySQL and sqlite. Node-DBI also includes functionality to build a select statement, which is handy for doing dynamic stuff on the fly.
Quick sample (using config information stored in another file):
var DBWrapper = require('node-dbi').DBWrapper;
var config = require('./config');
var dbConnectionConfig = { host:config.db.host, user:config.db.username, password:config.db.password, database:config.db.database };
var dbWrapper = new DBWrapper('pg', dbConnectionConfig);
dbWrapper.connect();
dbWrapper.fetchAll(sql_query, null, function (err, result) {
if (!err) {
console.log("Data came back from the DB.");
} else {
console.log("DB returned an error: %s", err);
}
dbWrapper.close(function (close_err) {
if (close_err) {
console.log("Error while disconnecting: %s", close_err);
}
});
});
config.js:
var config = {
db:{
host:"plop",
database:"musicbrainz",
username:"musicbrainz",
password:"musicbrainz"
},
}
module.exports = config;
Use a ByteArrayOutputStream
. Here is the process:
InputStream
to read dataByteArrayOutputStream
.InputStream
into the OutputStream
byte[]
from the ByteArrayOutputStream
using the toByteArray()
methodThanking Daniel Jimenez for his perfect solution to fetch column names alone from my csv, I extend his solution to use DictReader so we can iterate over the rows using column names as indexes. Thanks Jimenez.
with open('myfile.csv') as csvfile:
rest = []
with open("myfile.csv", "rb") as f:
reader = csv.reader(f)
i = reader.next()
i=i[1:]
re=csv.DictReader(csvfile)
for row in re:
for x in i:
print row[x]
This is how I've done it.
#copyright {_x000D_
float: left;_x000D_
padding-bottom: 10px;_x000D_
padding-top: 10px;_x000D_
text-align: center;_x000D_
bottom: 0px;_x000D_
width: 100%;_x000D_
}
_x000D_
<div id="copyright">_x000D_
Copyright 2018 © Steven Clough_x000D_
</div>
_x000D_
Listen to the podcast JavaScript Jabber: Episode #32 that features the original creators of AngularJS: Misko Hevery & Igor Minar. They talk a lot about what it's like to come to AngularJS from other JavaScript backgrounds, especially jQuery.
One of the points made in the podcast made a lot of things click for me with respects to your question:
MISKO: [...] one of the things we thought about very hardly in Angular is, how do we provide lots of escape hatches so that you can get out and basically figure out a way out of this. So to us, the answer is this thing called “Directives”. And with directives, you essentially become a regular little jQuery JavaScript, you can do whatever you want.
IGOR: So think of directive as the instruction to the compiler that tells it whenever you come across this certain element or this CSS in the template, and you keep this kind of code and that code is in charge of the element and everything below that element in the DOM tree.
A transcript of the entire episode is available at the link provided above.
So, to directly answer your question: AngularJS is -very- opinionated and is a true MV* framework. However, you can still do all of the really cool stuff you know and love with jQuery inside of directives. It's not a matter of "How do I do what I used to in jQuery?" as much as it's a matter of "How do I supplement AngularJS with all of the stuff I used to do in jQuery?"
It's really two very different states of mind.
I had a similar thing happen to me. I didn't want to stage the files just yet so I added them with git add
and then just did git reset
. This basically just added and then unstaged my changes but cleared the unmerged paths.
You could create a function that reads an integer between 1 and 23 or returns 0 if non-int
e.g.
int getInt()
{
int n = 0;
char buffer[128];
fgets(buffer,sizeof(buffer),stdin);
n = atoi(buffer);
return ( n > 23 || n < 1 ) ? 0 : n;
}
For the most part, the number of bytes and range of values is determined by the CPU's architecture not by C++. However, C++ sets minimum requirements, which litb explained properly and Martin York only made a few mistakes with.
The reason why you can't use int and long interchangeably is because they aren't always the same length. C was invented on a PDP-11 where a byte had 8 bits, int was two bytes and could be handled directly by hardware instructions. Since C programmers often needed four-byte arithmetic, long was invented and it was four bytes, handled by library functions. Other machines had different specifications. The C standard imposed some minimum requirements.
You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-
Set oShell = CreateObject ("WScript.Shell")
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
Do something like this:
A <div>
with ID of #imageDIV
, another one with ID #download
and a hidden <div>
with ID #previewImage
.
Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN
Then add this script:
var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});
$("#download").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#download").attr("download", "image.png").attr("href", newData);
});
The div will be saved as a PNG on clicking the #download