--allow-empty-message -m ''
(and -m ""
) fail in Git 2.29.2 on PowerShell:
error: switch `m' requires a value
(oddly enough, with a backtick on one side and a single quote on the other)
The following works consistently in Linux, PowerShell, and Command Prompt:
git commit --allow-empty-message --no-edit
The --no-edit
bit does the trick, as it prevents the editor from launching.
I find this form more explicit and a bit less hacky than forcing an empty message with -m ''
.
This is what my final options section looks like for chart.js version 2.8.0.
options: {
legend: {
display: false //Have this or else legend will display as undefined
},
scales: {
//This will show money for y-axis labels with format of $xx.xx
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value) {
return (new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})).format(value);
}
}
}]
},
//This will show money in tooltip with format of $xx.xx
tooltips: {
callbacks: {
label: function (tooltipItem) {
return (new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})).format(tooltipItem.value);
}
}
}
}
I wanted to show money values for both the y-axis and the tooltip values that show up when you hover over them. This works to show $49.99 and values with zero cents (ex: $50.00)
My approach to understand zookeeper was, to play around with the CLI client. as described in Getting Started Guide and Command line interface
From this I learned that zookeeper's surface looks very similar to a filesystem and clients can create and delete objects and read or write data.
create /myfirstnode mydata
ls /
get /myfirstnode
delete /myfirstnode
How to spin up a zookeper environment within minutes on docker for windows, linux or mac:
One time set up:
docker network create dn
Run server in a terminal window:
docker run --network dn --name zook -d zookeeper
docker logs -f zookeeper
Run client in a second terminal window:
docker run -it --rm --network dn zookeeper zkCli.sh -server zook
See also documentation of image on dockerhub
Update for Retrofit 2.0.0-beta3
Now you have to use okhttp3 with builder. Also the old interceptor will not work. This response is tailored for Android.
Here's a quick copy paste for you with the new stuff.
1. Modify your gradle file to
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile "com.squareup.retrofit2:converter-gson:2.0.0-beta3"
compile "com.squareup.retrofit2:adapter-rxjava:2.0.0-beta3"
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
2. Check this sample code:
with the new imports. You can remove Rx if you don't use it, also remove what you don't use.
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.RxJavaCallAdapterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
public interface APIService {
String ENDPOINT = "http://api.openweathermap.org";
String API_KEY = "2de143494c0b2xxxx0e0";
@GET("/data/2.5/weather?appid=" + API_KEY) Observable<WeatherPojo> getWeatherForLatLon(@Query("lat") double lat, @Query("lng") double lng, @Query("units") String units);
class Factory {
public static APIService create(Context context) {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.readTimeout(10, TimeUnit.SECONDS);
builder.connectTimeout(5, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
builder.addInterceptor(interceptor);
}
//Extra Headers
//builder.addNetworkInterceptor().add(chain -> {
// Request request = chain.request().newBuilder().addHeader("Authorization", authToken).build();
// return chain.proceed(request);
//});
builder.addInterceptor(new UnauthorisedInterceptor(context));
OkHttpClient client = builder.build();
Retrofit retrofit =
new Retrofit.Builder().baseUrl(APIService.ENDPOINT).client(client).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
return retrofit.create(APIService.class);
}
}
}
Bonus
I know it's offtopic but I find it cool.
In case there's an http error code of unauthorized, here is an interceptor. I use eventbus for transmitting the event.
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import com.androidadvance.ultimateandroidtemplaterx.BaseApplication;
import com.androidadvance.ultimateandroidtemplaterx.events.AuthenticationErrorEvent;
import de.greenrobot.event.EventBus;
import java.io.IOException;
import javax.inject.Inject;
import okhttp3.Interceptor;
import okhttp3.Response;
public class UnauthorisedInterceptor implements Interceptor {
@Inject EventBus eventBus;
public UnauthorisedInterceptor(Context context) {
BaseApplication.get(context).getApplicationComponent().inject(this);
}
@Override public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
if (response.code() == 401) {
new Handler(Looper.getMainLooper()).post(() -> eventBus.post(new AuthenticationErrorEvent()));
}
return response;
}
}
code take from https://github.com/AndreiD/UltimateAndroidTemplateRx (my project).
A regex can also be used to split words.
\w
can be used to match word characters ([A-Za-z0-9_]
), so that punctuation is removed from the results:
String s = "I want to walk my dog, and why not?";
Pattern pattern = Pattern.compile("\\w+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
System.out.println(matcher.group());
}
Outputs:
I
want
to
walk
my
dog
and
why
not
See Java API documentation for Pattern
Most of the aspects are covered. But there could be a requirement to find the aggregation of other data types apart from Integer, Long(for which specialized stream support is already present). For e.g. stram with BigInteger For such a type we can use reduce operation like
list.stream().reduce((bigInteger1, bigInteger2) -> bigInteger1.add(bigInteger2))
HashMap<String, String> meMap = new HashMap<String, String>();
meMap.put("Color1", "Red");
meMap.put("Color2", "Blue");
meMap.put("Color3", "Green");
meMap.put("Color4", "White");
Iterator myVeryOwnIterator = meMap.values().iterator();
while(myVeryOwnIterator.hasNext()) {
Toast.makeText(getBaseContext(), myVeryOwnIterator.next(), Toast.LENGTH_SHORT).show();
}
I was trying to add an Azure Artifacts NuGet source.
I followed Microsoft's instructions here, with one critical oversight.
I forgot to replace /v3/index.json
with /v2
.
If you use Perl try Net::IPv6Addr
use Net::IPv6Addr;
if( defined Net::IPv6Addr::is_ipv6($ip_address) ){
print "Looks like an ipv6 address\n";
}
use NetAddr::IP;
my $obj = NetAddr::IP->new6($ip_address);
use Validate::IP qw'is_ipv6';
if( is_ipv6($ip_address) ){
print "Looks like an ipv6 address\n";
}
I would like to improve answer from chris-b a little bit more.
See below for my code:
from threading import Thread, Lock
import threading
mutex = Lock()
def processData(data, thread_safe):
if thread_safe:
mutex.acquire()
try:
thread_id = threading.get_ident()
print('\nProcessing data:', data, "ThreadId:", thread_id)
finally:
if thread_safe:
mutex.release()
counter = 0
max_run = 100
thread_safe = False
while True:
some_data = counter
t = Thread(target=processData, args=(some_data, thread_safe))
t.start()
counter = counter + 1
if counter >= max_run:
break
In your first run if you set thread_safe = False
in while loop, mutex will not be used, and threads will step over each others in print method as below;
but, if you set thread_safe = True
and run it, you will see all the output comes perfectly fine;
hope this helps.
look at String.indexOf
and String.substring
.
Make sure you check for -1 for indexOf
.
Return the address of the thing pointed to by the iterator:
&(*iterator)
Edit: To clear up some confusion:
vector <int> vec; // a global vector of ints
void f() {
vec.push_back( 1 ); // add to the global vector
vector <int>::iterator it = vec.begin();
* it = 2; // change what was 1 to 2
int * p = &(*it); // get pointer to first element
* p = 3; // change what was 2 to 3
}
No need for vectors of pointers or dynamic allocation.
I had the SAME issue today and it was driving me nuts!!! What I had done was upgrade to node 8.10 and upgrade my NPM to the latest I uninstalled angular CLI
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
I then verified my Cache from NPM if it wasn't up to date I cleaned it and ran the install again
if npm version is < 5 then use npm cache clean --force
npm install -g @angular/cli@latest
and created a new project file and create a new angular project.
The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.
Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.
Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.
Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).
Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.
It is saying the value is undefined
because it is a constructor function
, not a class
with a constructor
. In order to use it, you would need to use Customer()
or customer()
.
First, you need to load file1.js before file2.js, like slebetman said:
<script defer src="file1.js" type="module"></script>
<script defer src="file2.js" type="module"></script>
Then, you could change your file1.js as follows:
export default class Customer(){
constructor(){
this.name="Jhon";
this.getName=function(){
return this.name;
};
}
}
And the file2.js as follows:
import { Customer } from "./file1";
var customer=new Customer();
Please correct me if I am wrong.
Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference
under the info tar
command.
x
means --extract
. v
means --verbose
. f
means --file
. z
means --gzip
. You can combine one-letter arguments together, and f
takes an argument, the filename. There is something you have to watch out for:
Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).
This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:tar cfz archive.tar.gz file tar -cfz archive.tar.gz file
are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.
wmic bios get serialnumber
if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)
I had to do exactly that.:):)
I suppose you can do it like this:
string accountNumber = DBSqlHelperFactory.ExecuteScalar(...) as string;
If accountNumber is null it means it was DBNull not string :)
From the Python docs, set the PATH like you did as above.
You should arrange for Python’s installation directory to be added to the PATH of every command window as it starts. If you installed Python fairly recently then the command dir C:\py* will probably tell you where it is installed; the usual location is something like C:\Python27. Otherwise you will be reduced to a search of your whole disk
Use Tools ? Find or hit the Search button and look for “python.exe”. Supposing you discover that Python is installed in the C:\Python27 directory (the default at the time of writing), you should make sure that entering the command
Then execute the Python command using the full path name to make sure that works.
Note: With ConcurrentMap you can use the more efficient
values.putIfAbsent(NoteColumns.CREATED_DATE, now);
I prefer the less verbose solution and avoid methods like IsTrue or IsFalse or their like.
(Here's my advice from How to write a reproducible example. I've tried to make it short but sweet).
You are most likely to get good help with your R problem if you provide a reproducible example. A reproducible example allows someone else to recreate your problem by just copying and pasting R code.
You need to include four things to make your example reproducible: required packages, data, code, and a description of your R environment.
Packages should be loaded at the top of the script, so it's easy to see which ones the example needs.
The easiest way to include data in an email or Stack Overflow question is to use dput()
to generate the R code to recreate it. For example, to recreate the mtcars
dataset in R,
I'd perform the following steps:
dput(mtcars)
in Rmtcars <-
then paste.Spend a little bit of time ensuring that your code is easy for others to read:
Make sure you've used spaces and your variable names are concise, but informative
Use comments to indicate where your problem lies
Do your best to remove everything that is not related to the problem.
The shorter your code is, the easier it is to understand.
Include the output of sessionInfo()
in a comment in your code. This summarises your R
environment and makes it easy to check if you're using an out-of-date
package.
You can check you have actually made a reproducible example by starting up a fresh R session and pasting your script in.
Before putting all of your code in an email, consider putting it on Gist github. It will give your code nice syntax highlighting, and you don't have to worry about anything getting mangled by the email system.
i agree with alf's answer,but little modification to it is,, to use,
try
{
control_name.Click -= event_Click;
main_browser.Document.Click += Document_Click;
}
catch(Exception exce)
{
main_browser.Document.Click += Document_Click;
}
Another option is to get a ".pem" (public key) file for that particular server, and install it locally into the heart of your JRE's "cacerts" file (use the keytool helper application), then it will be able to download from that server without complaint, without compromising the entire SSL structure of your running JVM and enabling download from other unknown cert servers...
This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.
Here is a good post on permanent generation.
I like the descriptions given for each space in Oracle's guide on JConsole:
For the HotSpot Java VM, the memory pools for serial garbage collection are the following.
- Eden Space (heap): The pool from which memory is initially allocated for most objects.
- Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
- Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
- Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
- Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.
From the searching I've done it appears you can not declare and set variables like this in Select statements. Is this right or am I missing something?
Within Oracle PL/SQL and SQL are two separate languages with two separate engines. You can embed SQL DML within PL/SQL, and that will get you variables. Such as the following anonymous PL/SQL block. Note the /
at the end is not part of PL/SQL, but tells SQL*Plus to send the preceding block.
declare
v_Date1 date := to_date('03-AUG-2010', 'DD-Mon-YYYY');
v_Count number;
begin
select count(*) into v_Count
from Usage
where UseTime > v_Date1;
dbms_output.put_line(v_Count);
end;
/
The problem is that a block that is equivalent to your T-SQL code will not work:
SQL> declare
2 v_Date1 date := to_date('03-AUG-2010', 'DD-Mon-YYYY');
3 begin
4 select VisualId
5 from Usage
6 where UseTime > v_Date1;
7 end;
8 /
select VisualId
*
ERROR at line 4:
ORA-06550: line 4, column 5:
PLS-00428: an INTO clause is expected in this SELECT statement
To pass the results of a query out of an PL/SQL, either an anonymous block, stored procedure or stored function, a cursor must be declared, opened and then returned to the calling program. (Beyond the scope of answering this question. EDIT: see Get resultset from oracle stored procedure)
The client tool that connects to the database may have it's own bind variables. In SQL*Plus:
SQL> -- SQL*Plus does not all date type in this context
SQL> -- So using varchar2 to hold text
SQL> variable v_Date1 varchar2(20)
SQL>
SQL> -- use PL/SQL to set the value of the bind variable
SQL> exec :v_Date1 := '02-Aug-2010';
PL/SQL procedure successfully completed.
SQL> -- Converting to a date, since the variable is not yet a date.
SQL> -- Note the use of colon, this tells SQL*Plus that v_Date1
SQL> -- is a bind variable.
SQL> select VisualId
2 from Usage
3 where UseTime > to_char(:v_Date1, 'DD-Mon-YYYY');
no rows selected
Note the above is in SQLPlus, may not (probably won't) work in Toad PL/SQL developer, etc. The lines starting with variable and exec are SQLPlus commands. They are not SQL or PL/SQL commands. No rows selected because the table is empty.
There are several options you can use. Quite good way is to use exceptions and class for handling called @ControllerAdvice
:
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Nothing to do
}
}
Also you can pass HttpServletResponse
to controller method and just set response code:
public RestModel create(@RequestBody String data, HttpServletResponse response) {
// response committed...
response.setStatus(HttpServletResponse.SC_ACCEPTED);
}
Please refer to the this great blog post for details: Exception Handling in Spring MVC
In Spring MVC using @ResponseBody
annotation is redundant - it's already included in @RestController
annotation.
It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:
$('input', $('#mydiv')).each(function () {
console.log($(this)); //log every element found to console output
});
The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.
<option value="" defaultValue disabled> Something </option>
you can replace defaultValue
with selected
but that would give warning.
I will answer your question using a math analogy:
In this instance, the number 0 will represent no value. If you pick a random number, say 15, how many times can 0 be subtracted from 15? Infinite times because 0 has no value, thus you are taking nothing out of 15. Do you have difficulty accepting that 15 - 0 = 15 instead of ERROR? So if we switch this analogy back to Java coding, the String "" represents no value. Pick a random string, say "hello world", how many times can "" be subtracted from "hello world"?
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
Django-model-values (disclosure: author) provides an implementation of the NotEqual lookup, as in this answer. It also provides syntactic support for it:
from model_values import F
Model.objects.exclude(F.x != 5, a=True)
You can wire up your own custom event
$('textarea').bind("enterKey",function(e){
//do stuff here
});
$('textarea').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
I had to include "PROJECT_NAME/osdep.h" and that includes the os specific configurations.
I would look in other files using the types you are interested in and find where/how they are defined (by looking at includes).
Nobody provided the "classic Reflection" solution, so here is a complete code example:
using System;
using System.Collections;
using System.Collections.Generic;
namespace DictionaryRuntime
{
public class DynamicDictionaryFactory
{
/// <summary>
/// Factory to create dynamically a generic Dictionary.
/// </summary>
public IDictionary CreateDynamicGenericInstance(Type keyType, Type valueType)
{
//Creating the Dictionary.
Type typeDict = typeof(Dictionary<,>);
//Creating KeyValue Type for Dictionary.
Type[] typeArgs = { keyType, valueType };
//Passing the Type and create Dictionary Type.
Type genericType = typeDict.MakeGenericType(typeArgs);
//Creating Instance for Dictionary<K,T>.
IDictionary d = Activator.CreateInstance(genericType) as IDictionary;
return d;
}
}
}
The above DynamicDictionaryFactory
class has a method
CreateDynamicGenericInstance(Type keyType, Type valueType)
and it creates and returns an IDictionary instance, the types of whose keys and values are exactly the specified on the call keyType
and valueType
.
Here is a complete example how to call this method to instantiate and use a Dictionary<String, int>
:
using System;
using System.Collections.Generic;
namespace DynamicDictionary
{
class Test
{
static void Main(string[] args)
{
var factory = new DictionaryRuntime.DynamicDictionaryFactory();
var dict = factory.CreateDynamicGenericInstance(typeof(String), typeof(int));
var typedDict = dict as Dictionary<String, int>;
if (typedDict != null)
{
Console.WriteLine("Dictionary<String, int>");
typedDict.Add("One", 1);
typedDict.Add("Two", 2);
typedDict.Add("Three", 3);
foreach(var kvp in typedDict)
{
Console.WriteLine("\"" + kvp.Key + "\": " + kvp.Value);
}
}
else
Console.WriteLine("null");
}
}
}
When the above console application is executed, we get the correct, expected result:
Dictionary<String, int>
"One": 1
"Two": 2
"Three": 3
That's not a typical Wordpress rewrite block. This is:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
See http://codex.wordpress.org/Using_Permalinks#Where.27s_my_.htaccess_file.3F
Where's my .htaccess file? WordPress's index.php and .htaccess files should be together in the directory indicated by the Site address (URL) setting on your General Options page. Since the name of the file begins with a dot, the file may not be visible through an FTP client unless you change the preferences of the FTP tool to show all files, including the hidden files. Some hosts (e.g. Godaddy) may not show or allow you to edit .htaccess if you install WordPress through the Godaddy Hosting Connection installation.
Creating and editing (.htaccess) If you do not already have a .htaccess file, create one. If you have shell or ssh access to the server, a simple touch .htaccess command will create the file. If you are using FTP to transfer files, create a file on your local computer, call it 1.htaccess, upload it to the root of your WordPress folder, and then rename it to .htaccess.
You can edit the .htaccess file by FTP, shell, or (possibly) your host's control panel.
The easiest and fastest thing to do it reset your permalinks in Dashboard>>Settings>>Permalinks and make sure .htaccess is writable so WordPress can write the rules itself.
And: are you aware you are calling index.cgi
as your default document rather than index.php
? That's wrong. Remove index.cgi
. Or try removing the whole line, too, because defining a default doc on your server may not be needed.
Here's a variant that uses fancy indexing and has the actual values as an intermediate:
p31 = numpy.asarray(o31)
values = p31[p31<200]
za = len(values)
For people who have come here to look for a general answer for duplicate row removal, use !duplicated()
:
a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
df <-data.frame(a,b)
duplicated(df)
[1] FALSE TRUE FALSE FALSE FALSE TRUE FALSE TRUE
> df[duplicated(df), ]
a b
2 A 1
6 B 1
8 C 2
> df[!duplicated(df), ]
a b
1 A 1
3 A 2
4 B 4
5 B 1
7 C 2
Answer from: Removing duplicated rows from R data frame
Here's a quick, admittedly butchered response, but in a sentence:
1NF : Your table is organized as an unordered set of data, and there are no repeating columns.
2NF: You don't repeat data in one column of your table because of another column.
3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.
For more detail, see wikipedia...
Import connect
from react-redux
and use it to connect the component with the state connect(mapStates,mapDispatch)(component)
import React from "react";
import { connect } from "react-redux";
const MyComponent = (props) => {
return (
<div>
<h1>{props.title}</h1>
</div>
);
}
}
Finally you need to map the states to the props to access them with this.props
const mapStateToProps = state => {
return {
title: state.title
};
};
export default connect(mapStateToProps)(MyComponent);
Only the states that you map will be accessible via props
Check out this answer: https://stackoverflow.com/a/36214059/4040563
For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132
You can simply add an id attribute to the panel. Like this
<div class="panel-heading" id="mypanelId">Hello world </div>
Then in your custom CSS file:
#mypanelId{
background-image: none;
background: rgba(22, 20, 100, 0.8);
color: white;
}
You will have to use a class, but don't worry, it's pretty simple. First we'll assign your :hover
rules to not only apply to physically-hovered links, but also to links that have the classname hovered
.
a:hover, a.hovered { color: #ccff00; }
Next, when you click #btn
, we'll toggle the .hovered
class on the #link
.
$("#btn").click(function() {
$("#link").toggleClass("hovered");
});
If the link has the class already, it will be removed. If it doesn't have the class, it will be added.
I think this could work:
select
case when datepart(dw,[Date]) = 1 then 7 else DATEPART(DW,[Date])-1 end as WeekDay
$(this.parentNode).addClass('newClass');
In addition mysql passwords when not using the IDENTIFIED BY
clause, may be blank values, if non-blank, they may be encrypted. But yes USAGE
is used to modify an account by granting simple resource limiters such as MAX_QUERIES_PER_HOUR
, again this can be specified by also
using the WITH clause, in conjuction with GRANT USAGE
(no privileges added) or GRANT ALL
, you can also specify GRANT USAGE
at the global level, database level, table level,etc....
readonly
can be initialized at declaration or get its value from the constructor only. Unlike const
it has to be initialized and declare at the same time.
readonly
has everything const
has, plus constructor initialization
using System;
class MainClass {
public static void Main (string[] args) {
Console.WriteLine(new Test().c);
Console.WriteLine(new Test("Constructor").c);
Console.WriteLine(new Test().ChangeC()); //Error A readonly field
// `MainClass.Test.c' cannot be assigned to (except in a constructor or a
// variable initializer)
}
public class Test {
public readonly string c = "Hello World";
public Test() {
}
public Test(string val) {
c = val;
}
public string ChangeC() {
c = "Method";
return c ;
}
}
}
Cloning the objects before adding them. For example, instead of newList.addAll(oldList);
for(Person p : oldList) {
newList.add(p.clone());
}
Assuming clone
is correctly overriden inPerson
.
Using ${mySet.toArray[0]} does not work.
I do not think it is possible without having forEach loop at least one iteration.
Passing HTMLInputElement as a generic to the event type should work too:
onUpdatingServerName(event: React.ChangeEvent<HTMLInputElement>) {
console.log(event);
this.newserverName = event.target.value;
}
For most cases i would prefer processes over threads. threads can be useful when you have a relatively smaller task (process overhead >> time taken by each divided task unit) and there is a need of memory sharing between them. Think a large array. Also (offtopic), note that if your CPU utilization is 100 percent or close to it, there is going to be no benefit out of multithreading or processing. (in fact it will worsen)
+1 simple and cross-browser way: You can also put transparent picture over the video with css z-index and opacity. So users will see "save picture as" instead of "save video" in context menu.
Save as fix_whitespace.py
:
#!/usr/bin/env python
"""
Fix trailing whitespace and line endings (to Unix) in a file.
Usage: python fix_whitespace.py foo.py
"""
import os
import sys
def main():
""" Parse arguments, then fix whitespace in the given file """
if len(sys.argv) == 2:
fname = sys.argv[1]
if not os.path.exists(fname):
print("Python file not found: %s" % sys.argv[1])
sys.exit(1)
else:
print("Invalid arguments. Usage: python fix_whitespace.py foo.py")
sys.exit(1)
fix_whitespace(fname)
def fix_whitespace(fname):
""" Fix whitespace in a file """
with open(fname, "rb") as fo:
original_contents = fo.read()
# "rU" Universal line endings to Unix
with open(fname, "rU") as fo:
contents = fo.read()
lines = contents.split("\n")
fixed = 0
for k, line in enumerate(lines):
new_line = line.rstrip()
if len(line) != len(new_line):
lines[k] = new_line
fixed += 1
with open(fname, "wb") as fo:
fo.write("\n".join(lines))
if fixed or contents != original_contents:
print("************* %s" % os.path.basename(fname))
if fixed:
slines = "lines" if fixed > 1 else "line"
print("Fixed trailing whitespace on %d %s" \
% (fixed, slines))
if contents != original_contents:
print("Fixed line endings to Unix (\\n)")
if __name__ == "__main__":
main()
Erlang is awesome
palindrome(L) -> palindrome(L,[]).
palindrome([],_) -> false;
palindrome([_|[]],[]) -> true;
palindrome([_|L],L) -> true;
palindrome(L,L) -> true;
palindrome([H|T], Acc) -> palindrome(T, [H|Acc]).
To remove duplicates from a single column
Sub removeDuplicate()
'removeDuplicate Macro
Columns("A:A").Select
ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _
Header:=xlNo
Range("A1").Select
End Sub
if you have header then use Header:=xlYes
Increase your range as per your requirement.
you can make it to 1000 like this :
ActiveSheet.Range("$A$1:$A$1000")
More info here here
adb install <path_to_apk>
http://developer.android.com/guide/developing/tools/adb.html#move
Use the System.getenv(String)
method, passing the name of the variable to read.
This one is:
def binsearch(t, key, low = 0, high = len(t) - 1):
# bisecting the range
while low < high:
mid = (low + high)//2
if t[mid] < key:
low = mid + 1
else:
high = mid
# at this point 'low' should point at the place
# where the value of 'key' is possibly stored.
return low if t[low] == key else -1
While the above answers are probably best for this situation, if you just want to do a one-off and don't want to bother with modifying other files, you can in-line the CSS.
<p style="margin-bottom:3cm;">This is the first question?</p>
You'll want to use a number of layout managers to help you achieve the basic results you want.
Check out A Visual Guide to Layout Managers for a comparision.
You could use a GridBagLayout
but that's one of the most complex (and powerful) layout managers available in the JDK.
You could use a series of compound layout managers instead.
I'd place the graphics component and text area on a single JPanel
, using a BorderLayout
, with the graphics component in the CENTER
and the text area in the SOUTH
position.
I'd place the text field and button on a separate JPanel
using a GridBagLayout
(because it's the simplest I can think of to achieve the over result you want)
I'd place these two panels onto a third, master, panel, using a BorderLayout
, with the first panel in the CENTER
and the second at the SOUTH
position.
But that's me
My Solution in laravel 5.2
{{ Form::open(['route' => ['votes.submit', $video->id], 'method' => 'POST']) }}
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-thumbs-up"></span> Votar
</button>
{{ Form::close() }}
My Routes File (under middleware)
Route::post('votar/{id}', [
'as' => 'votes.submit',
'uses' => 'VotesController@submit'
]);
Route::delete('votar/{id}', [
'as' => 'votes.destroy',
'uses' => 'VotesController@destroy'
]);
ok, so i follow uhmdown's answer for dimming background activity when pop window is open. But it creates problem for me. it was dimming activity and include popup window (means dimmed-black layered on both activity and popup also, it can not be separate them).
so i tried this way,
create an dimming_black.xml file for dimming effect,
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#33000000" />
</shape>
And add as background
in FrameLayout
as root xml tag, also put my other controls in LinearLayout
like this layout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/ff_drawable_black">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="bottom"
android:background="@color/white">
// other codes...
</LinearLayout>
</FrameLayout>
at last i show popup on my MainActivity
with some extra parameter set as below.
//instantiate popup window
popupWindow = new PopupWindow(viewPopup, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
//display the popup window
popupWindow.showAtLocation(layout_ff, Gravity.BOTTOM, 0, 0);
it works for me, also solved problem as commented by BaDo. With this Actionbar
also can be dimmed.
P.s i am not saying uhmdown's is wrong. i learnt form his answer and try to evolve for my problem. I also confused whether this is a good way or not.
Any suggestions is also appreciated also sorry for my bad English.
start javaw -DSTOP.PORT=8079 -DSTOP.KEY=secret -jar start.jar
start javaw -DSTOP.PORT=8079 -DSTOP.KEY=secret -jar start.jar --stop
Driver.getPageSource() is a bad way to verify text present. Suppose you say, driver.getPageSource().contains("input");
That doesn't verify "input" is present on the screen, only that "input" is present in the html, like an input tag.
I usually verify text on an element by using xpath:
boolean textFound = false;
try {
driver.findElement(By.xpath("//*[contains(text(),'someText')]"));
textFound = true;
} catch (Exception e) {
textFound = false;
}
If you want an exact text match, just remove the contains function:
driver.findElement(By.xpath("//*[text()='someText']));
Is this role attribute necessary?
Answer: Yes.
It provides you:
http://stefangabos.ro/jquery/zebra-datepicker
use zebra date pickers:
$('#select_month1').Zebra_DatePicker({
direction: false,
format: 'Y-m-d',
pair: $('#select_month2')
});
$('#select_month2').Zebra_DatePicker({
direction: 1, format: 'Y-m-d',
});
for /f %G in ('dir *.cpp *.h /s/b') do ( find /i "what you search" "%G") >> out_file.txt
Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.
Read regular-expression.info for more details.
Syntax:
(?=REGEX_1)REGEX_2
Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.
example:
(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}
REGEX_1 is [a-z0-9]{4}$
which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3}
which matches one or two letters followed by two or three digits.
REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.
Syntax:
(?!REGEX_1)REGEX_2
Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.
example:
(?!.*\bFWORD\b)\w{10,30}$
The look-ahead part checks for the FWORD
in the string and fails if it finds it. If it doesn't find FWORD
, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_
Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.
You can try this in your web form with a button called btnSave for example:
<input type="button" id="btnSave" onclick="javascript:SaveWithParameter('Hello Michael')" value="click me"/>
<script type="text/javascript">
function SaveWithParameter(parameter)
{
__doPostBack('btnSave', parameter)
}
</script>
And in your code behind add something like this to read the value and operate upon it:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"]; // parameter
// Request["__EVENTTARGET"]; // btnSave
}
Give that a try and let us know if that worked for you.
You could use 'corrplot' package.
d <- data.frame(x1=rnorm(10),
x2=rnorm(10),
x3=rnorm(10))
M <- cor(d) # get correlations
library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix
More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html
Here's a one-liner using Streams
Iterator<?> iterator = ...
List<?> list = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false)
.collect(Collectors.toList());
Default-Values are only considered for parameters NOT given to the function.
So given a function
procedure foo( bar1 IN number DEFAULT 3,
bar2 IN number DEFAULT 5,
bar3 IN number DEFAULT 8 );
if you call this procedure with no arguments then it will behave as if called with
foo( bar1 => 3,
bar2 => 5,
bar3 => 8 );
but 'NULL' is still a parameter.
foo( 4,
bar3 => NULL );
This will then act like
foo( bar1 => 4,
bar2 => 5,
bar3 => Null );
( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )
one way to treat NULL the same as a default value would be to default the value to NULL
procedure foo( bar1 IN number DEFAULT NULL,
bar2 IN number DEFAULT NULL,
bar3 IN number DEFAULT NULL );
and using a variable with the desired value then
procedure foo( bar1 IN number DEFAULT NULL,
bar2 IN number DEFAULT NULL,
bar3 IN number DEFAULT NULL )
AS
v_bar1 number := NVL( bar1, 3);
v_bar2 number := NVL( bar2, 5);
v_bar3 number := NVL( bar3, 8);
Version 5.5 of PHP will have built-in support for BCrypt, the functions password_hash()
and password_verify()
. Actually these are just wrappers around the function crypt()
, and shall make it easier to use it correctly. It takes care of the generation of a safe random salt, and provides good default values.
The easiest way to use this functions will be:
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
This code will hash the password with BCrypt (algorithm 2y
), generates a random salt from the OS random source, and uses the default cost parameter (at the moment this is 10). The second line checks, if the user entered password matches an already stored hash-value.
Should you want to change the cost parameter, you can do it like this, increasing the cost parameter by 1, doubles the needed time to calculate the hash value:
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));
In contrast to the "cost"
parameter, it is best to omit the "salt"
parameter, because the function already does its best to create a cryptographically safe salt.
For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash()
function. For PHP versions before 5.3.7 there is no support for crypt()
with 2y
, the unicode safe BCrypt algorithm. One could replace it instead with 2a
, which is the best alternative for earlier PHP versions.
server.session.timeout
in the application.properties
file is now deprecated. The correct setting is:
server.servlet.session.timeout=60s
Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.
Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:
public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
$result = $this->model->with($with);
$dataSet = $result->where($where)
// Conditionally use $orderBy if not empty
->when(!empty($orderBy), function ($query) use ($orderBy) {
// Break $orderBy into pairs
$pairs = array_chunk($orderBy, 2);
// Iterate over the pairs
foreach ($pairs as $pair) {
// Use the 'splat' to turn the pair into two arguments
$query->orderBy(...$pair);
}
})
->paginate($limit)
->appends(Input::except('page'));
return $dataSet;
}
Now, you can make your call like this:
$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
yaml.load
Consider the following example YAML. It is well-formed YAML syntax, however it uses (non-standard) curly-brace placeholders with embedded expressions.
The embedded expressions do not produce the desired result in YAML, because they are not part of the native YAML specification. Nevertheless, they are used in this example only to help illustrate what is available with standard YAML and what is not.
part01_customer_info:
cust_fname: "Homer"
cust_lname: "Himpson"
cust_motto: "I love donuts!"
cust_email: [email protected]
part01_government_info:
govt_sales_taxrate: 1.15
part01_purchase_info:
prch_unit_label: "Bacon-Wrapped Fancy Glazed Donut"
prch_unit_price: 3.00
prch_unit_quant: 7
prch_product_cost: "{{prch_unit_price * prch_unit_quant}}"
prch_total_cost: "{{prch_product_cost * govt_sales_taxrate}}"
part02_shipping_info:
cust_fname: "{{cust_fname}}"
cust_lname: "{{cust_lname}}"
ship_city: Houston
ship_state: Hexas
part03_email_info:
cust_email: "{{cust_email}}"
mail_subject: Thanks for your DoughNutz order!
mail_notes: |
We want the mail_greeting to have all the expected values
with filled-in placeholders (and not curly-braces).
mail_greeting: |
Greetings {{cust_fname}} {{cust_lname}}!
We love your motto "{{cust_motto}}" and we agree with you!
Your total purchase price is {{prch_total_cost}}
The substitutions marked in GREEN are readily available in standard YAML, using anchors, aliases, and merge keys.
The substitutions marked in YELLOW are technically available in standard YAML, but not without a custom type declaration, or some other binding mechanism.
The substitutions marked in RED are not available in standard YAML. Yet there are workarounds and alternatives; such as through string formatting or string template engines (such as python's str.format
).
A frequently-requested feature for YAML is the ability to insert arbitrary variable placeholders that support arbitrary cross-references and expressions that relate to the other content in the same (or transcluded) YAML file(s).
YAML supports anchors and aliases, but this feature does not support arbitrary placement of placeholders and expressions anywhere in the YAML text. They only work with YAML nodes.
YAML also supports custom type declarations, however these are less common, and there are security implications if you accept YAML content from potentially untrusted sources.
There are YAML extension libraries, but these are not part of the native YAML spec.
sprintf
or str.format
style functionality from the hosting languageSELECT CASE WHEN field IS NULL THEN 'Empty' ELSE field END AS field_alias
Or more idiomatic:
SELECT coalesce(field, 'Empty') AS field_alias
You have a type-o:
its: height: 200x;
and it should be: height: 200px;
also check the image url; it should be in the same directory it seems.
Also, dont use 'px' at null (aka '0') values. 0px, 0em, 0% is still 0. :)
top: 0px;
is the same with:
top: 0;
Good Luck!
ls | xargs -I % mv % %_`date +%d%b%Y`
One line is enough. ls all files/dirs under current dir and append date to each file.
It stands for Dimension, but is generally read as "Create Variable," or "Allocate Space for This."
Break up the string into two pieces
alert ("Please select file " +
"to delete");
How about something like this?
<html>
<head>
<script type="text/javascript">
var HoverListener = {
addElem: function( elem, callback, delay )
{
if ( delay === undefined )
{
delay = 1000;
}
var hoverTimer;
addEvent( elem, 'mouseover', function()
{
hoverTimer = setTimeout( callback, delay );
} );
addEvent( elem, 'mouseout', function()
{
clearTimeout( hoverTimer );
} );
}
}
function tester()
{
alert( 'hi' );
}
// Generic event abstractor
function addEvent( obj, evt, fn )
{
if ( 'undefined' != typeof obj.addEventListener )
{
obj.addEventListener( evt, fn, false );
}
else if ( 'undefined' != typeof obj.attachEvent )
{
obj.attachEvent( "on" + evt, fn );
}
}
addEvent( window, 'load', function()
{
HoverListener.addElem(
document.getElementById( 'test' )
, tester
);
HoverListener.addElem(
document.getElementById( 'test2' )
, function()
{
alert( 'Hello World!' );
}
, 2300
);
} );
</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>
I think you can also call Refresh()
.
In C++, using the std::array class to declare an array, one can easily find the size of an array and also the last element.
#include<iostream>
#include<array>
int main()
{
std::array<int,3> arr;
//To find the size of the array
std::cout<<arr.size()<<std::endl;
//Accessing the last element
auto it=arr.end();
std::cout<<arr.back()<<"\t"<<arr[arr.size()-1]<<"\t"<<*(--it);
return 0;
}
In fact, array class has a whole lot of other functions which let us use array a standard container.
Reference 1 to C++ std::array class
Reference 2 to std::array class
The examples in the references are helpful.
After reading many articles I decided to put all the attributes information together:
- atomic //default
- nonatomic
- strong=retain //default
- weak= unsafe_unretained
- retain
- assign //default
- unsafe_unretained
- copy
- readonly
- readwrite //default
Below is a link to the detailed article where you can find these attributes.
Many thanks to all the people who give best answers here!!
Here is the Sample Description from Article
Example :
@property (retain) NSString *name;
@synthesize name;
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
Explain:
Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.
If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.
Example:
@property (strong, nonatomic) ViewController *viewController;
@synthesize viewController;
Example :
@property (weak, nonatomic) IBOutlet UIButton *myButton;
@synthesize myButton;
Strong & Weak Explanation, Thanks to BJ Homer:
Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
Example:
@property (nonatomic, assign) NSString *address;
@synthesize address;
unsafe_unretained
-unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.
Example:
@property (nonatomic, unsafe_unretained) NSString *nickName;
@synthesize nickName;
Example:
@property (nonatomic, copy) NSArray *myArray;
@synthesize myArray;
Do you have to do it with Ajax? Coouldn't it be a possibility to load it in an iframe?
I needed to know the script name and where it is executing from.
Prefixing "$global:" to the MyInvocation structure returns the full path and script name when called from both the main script, and the main line of an imported .PSM1 library file. It also works from within a function in an imported library.
After much fiddling around, I settled on using $global:MyInvocation.InvocationName. It works reliably with CMD launch, Run With Powershell, and the ISE. Both local and UNC launches return the correct path.
On old versions of Debian and Ubuntu, you solved this by installing the Curl extension for PHP, and restarting the webserver. Assuming the webserver is Apache 2:
sudo apt-get install php5-curl
sudo service apache2 restart
On newer versions, the package name as changed:
sudo apt install php-curl
It's possible you'll need to install more:
sudo apt-get install curl libcurl3 libcurl3-dev;
In the direction of Bradgonesurfing's answer, many times one doesn't really need to concatenate two vectors (O(n)), but instead just work with them as if they were concatenated (O(1)). If this is your case, it can be done without the need of Boost libraries.
The trick is to create a vector proxy: a wrapper class which manipulates references to both vectors, externally seen as a single, contiguous one.
USAGE
std::vector<int> A{ 1, 2, 3, 4, 5};
std::vector<int> B{ 10, 20, 30 };
VecProxy<int> AB(A, B); // ----> O(1). No copies performed.
for (size_t i = 0; i < AB.size(); ++i)
std::cout << AB[i] << " "; // 1 2 3 4 5 10 20 30
IMPLEMENTATION
template <class T>
class VecProxy {
private:
std::vector<T>& v1, v2;
public:
VecProxy(std::vector<T>& ref1, std::vector<T>& ref2) : v1(ref1), v2(ref2) {}
const T& operator[](const size_t& i) const;
const size_t size() const;
};
template <class T>
const T& VecProxy<T>::operator[](const size_t& i) const{
return (i < v1.size()) ? v1[i] : v2[i - v1.size()];
};
template <class T>
const size_t VecProxy<T>::size() const { return v1.size() + v2.size(); };
MAIN BENEFIT
It's O(1) (constant time) to create it, and with minimal extra memory allocation.
SOME STUFF TO CONSIDER
At least as far back as Material Components 1.3.0-alpha03, it doesn't matter if the RecyclerView is nested (in something other than a ScrollView or NestedScrollView). Just put app:layout_behavior="@string/appbar_scrolling_view_behavior"
on its top level parent that's a sibling of the AppBarLayout in the CoordinatorLayout.
This has been working for me when using a single Activity architecture with Jetpack Naviagation, where all Fragments are sharing the same AppBar from the Activity's layout. I make the FragmentContainer the direct child of the CoordinatorLayout that also contains the AppBarLayout, like below. The RecyclerViews in the various fragments are scrolling normally and the AppBar folds away and reappears as expected.
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:defaultNavHost="true"
app:navGraph="@navigation/mobile_navigation"/>
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:liftOnScroll="true">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_scrollFlags="scroll|enterAlways|snap" />
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
liftOnScroll
(used to for app bars to look like they have zero elevation when at the top of the page) works if each fragment passes the ID of its RecyclerView to AppBarLayout.liftOnScrollTargetViewId
in Fragment.onResume
. Or pass 0 if the Fragment doesn't scroll.
I was looking for an elegant solution that support quoting and wouldn't require installing anything fancy on my VMware vMA appliance. Turns out this simple python script does the trick! (I named the script csv2tsv.py
, since it converts CSV into tab-separated values - TSV)
#!/usr/bin/env python
import sys, csv
with sys.stdin as f:
reader = csv.reader(f)
for row in reader:
for col in row:
print col+'\t',
print
Tab-separated values can be split easily with the cut command (no delimiter needs to be specified, tab is the default). Here's a sample usage/output:
> esxcli -h $VI_HOST --formatter=csv network vswitch standard list |csv2tsv.py|cut -f12
Uplinks
vmnic4,vmnic0,
vmnic5,vmnic1,
vmnic6,vmnic2,
In my scripts I'm actually going to parse tsv output line by line and use read or cut to get the fields I need.
In file php.ini this line:
extension=mysqli
Replace by:
extension="C:\php\ext\php_mysqli.dll"
Most of those solution is correct, but if You need check values without case sensitivity
using System.Linq;
...
string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext"};
if(stringArray.Any(a=> String.Equals(a, stringToCheck, StringComparison.InvariantCultureIgnoreCase)) )
{
//contains
}
if (stringArray.Any(w=> w.IndexOf(stringToCheck, StringComparison.InvariantCultureIgnoreCase)>=0))
{
//contains
}
I had this issue - it was odd because I reset my repo to a time when the app was working. The issue was with my simulator (iOS).
For me the solution was to
I had this problem and it turned out the issue was that I had named my repository with CamelCase. Bitbucket automatically changes the URL of your repository to be all lower case and that gets sent to Jenkins in the webhook. Jenkins then searches for projects with a matching repository. If you, like me, have CamelCase in your repository URL in your project configuration you will be able to check out code, but the pattern matching on the webhook request will fail.
Just change your repo URL to be all lower case instead of CamelCase and the pattern match should find your project.
DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'
IF PATINDEX('%[0-9]%', @str) > 0
PRINT 'YES, The string has numbers'
ELSE
PRINT 'NO, The string does not have numbers'
The problem for me was, I had taken backup of controller (js) file with some other changes in the same folder and bundling loaded both the controller files (original and backup js). Removing backup from the scripts folder, that was bundled solved the issue.
In the ViewDidLoad Method, you have to write this line.
tableViews.separatorStyle = UITableViewCellSeparatorStyleNone;
This is working Code.
1st: Get personal access token. https://github.com/settings/tokens
2nd: Put account & the token. Example is here:
$ git push
Username for 'https://github.com': # Put your GitHub account name
Password for 'https://{USERNAME}@github.com': # Put your Personal access token
Link on how to create a personal access token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line
If you're in a class inherited from UITableViewController
, then this is the swift version:
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
NSLog("did select and the text is \(cell?.textLabel?.text)")
}
Note that cell
is an optional, so it must be unwrapped - and the same for textLabel
. If any of the 2 is nil (unlikely to happen, because the method is called with a valid index path), if you want to be sure that a valid value is printed, then you should check that both cell
and textLabel
are both not nil:
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
let text = cell?.textLabel?.text
if let text = text {
NSLog("did select and the text is \(text)")
}
}
What about using computed properties?
class MyClass {
class var myConstant: String { return "What is Love? Baby don't hurt me" }
}
MyClass.myConstant
/app/config/config.yml
framework:
# ?????? ??????????????? ???????? ? ???????, json, xml ? ???????
serializer:
enabled: true
services:
object_normalizer:
class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
tags:
# ???????? ? ???? ????????? ???? ??????, ??? ??. ?????, ?.?. ????? ???????? ?? ?????
- { name: serializer.normalizer }
and example for your controller:
/**
* ????? ???????? ?? ?? ??????? ? ?? ?????
* @Route("/search/", name="orgunitSearch")
*/
public function orgunitSearchAction()
{
$array = $this->get('request')->query->all();
$entity = $this->getDoctrine()
->getRepository('IntranetOrgunitBundle:Orgunit')
->findOneBy($array);
$serializer = $this->get('serializer');
//$json = $serializer->serialize($entity, 'json');
$array = $serializer->normalize($entity);
return new JsonResponse( $array );
}
but the problems with the field type \DateTime will remain.
This is my workable one. on mac OS X 10.10.4
grep -e 'this' -rl . | xargs sed -i '' 's/this/that/g'
The above ones use find will change the files that do not contain the search text (add a new line at the file end), which is verbose.
I had the same issue and I have tried many answers but nothing worked.
I tried the following and it worked successfully :
<input type=text data-date-format='yy-mm-dd' >
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])
x*y
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit x*y
1000000 loops, best of 3: 421 ns per loop
np.multiply(x,y)
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop
Both np.multiply
and *
would yield element wise multiplication known as the Hadamard Product
%timeit
is ipython magic
Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.
First the actual accounts:
LocalService account (preferred)
A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.
NT AUTHORITY\LocalService
HKEY_USERS\S-1-5-19
)
Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).
NT AUTHORITY\NetworkService
MANGO$
) to remote serversHKEY_USERS\S-1-5-20
)NETWORK SERVICE
into the Select User or Group dialog
LocalSystem account (dangerous, don't use!)
Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)
.\LocalSystem
(can also use LocalSystem
or ComputerName\LocalSystem
)HKCU
represents the default user)MANGO$
) to remote servers
Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService
can still access the internet.
The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).
It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.
In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).
In Windows Server 2003 you cannot run a scheduled task as
NT_AUTHORITY\LocalService
(aka the Local Service account), or NT AUTHORITY\NetworkService
(aka the Network Service account). That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.
A service running as NetworkService
presents the machine credentials on the network. This means that if your computer was called mango
, it would present as the machine account MANGO$
:
Note: I am not sure this will be of any help to you, but you never know.
I found this link:http://www.ubuntugeek.com/howto-convert-vmware-image-to-virtualbox-image.html
ENJOY :-)
For OpenFileDialog:
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
For FolderBrowserDialog:
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description";
if (fbd.ShowDialog() == DialogResult.OK)
{
string sSelectedPath = fbd.SelectedPath;
}
To access selected folder
and selected file name
you can declare both string at class level.
namespace filereplacer
{
public partial class Form1 : Form
{
string sSelectedFile;
string sSelectedFolder;
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Custom Description"; //not mandatory
if (fbd.ShowDialog() == DialogResult.OK)
sSelectedFolder = fbd.SelectedPath;
else
sSelectedFolder = string.Empty;
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
sSelectedFile = choofdlog.FileName;
else
sSelectedFile = string.Empty;
}
private void replacebtn_Click(object sender, EventArgs e)
{
if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
{
//use selected folder path and file path
}
}
....
}
NOTE:
As you have kept choofdlog.Multiselect=true;
, that means in the OpenFileDialog()
you are able to select multiple files (by pressing ctrl
key and left mouse click for selection).
In that case you could get all selected files in string[]
:
At Class Level:
string[] arrAllFiles;
Locate this line (when Multiselect=true
this line gives first file only):
sSelectedFile = choofdlog.FileName;
To get all files use this:
arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files
Just FYI, @
and its numpy equivalents dot
and matmul
are all equally fast. (Plot created with perfplot, a project of mine.)
Code to reproduce the plot:
import perfplot
import numpy
def setup(n):
A = numpy.random.rand(n, n)
x = numpy.random.rand(n)
return A, x
def at(data):
A, x = data
return A @ x
def numpy_dot(data):
A, x = data
return numpy.dot(A, x)
def numpy_matmul(data):
A, x = data
return numpy.matmul(A, x)
perfplot.show(
setup=setup,
kernels=[at, numpy_dot, numpy_matmul],
n_range=[2 ** k for k in range(15)],
)
Is your logic not round the wrong way in that example, you have it hiding when the screen is bigger than 1024. Reverse the cases, make the none
in to a block
and vice versa.
---Lalmuni Demos---
create table Users
(
userid int,date_of_birth date
)
---insert values---
insert into Users values(4,'9/10/1991')
select DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years,
MONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months,
DAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,
from users
Here's Herb Sutter's take
Guideline: Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership.
Guideline: Express that a function will store and share ownership of a heap object using a by-value shared_ptr parameter.
Guideline: Use a non-const shared_ptr& parameter only to modify the shared_ptr. Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership; otherwise use widget* instead (or if not nullable, a widget&).
Yes, the post data is safe. But the origin of that data is not. This way somebody can trick user with JS into logging in to your site, while browsing attacker's web page.
In order to prevent that, django will send a random key both in cookie, and form data. Then, when users POSTs, it will check if two keys are identical. In case where user is tricked, 3rd party website cannot get your site's cookies, thus causing auth error.
Its not possible thats the whole point of hashing. You can however bruteforce by going through all possibilities (using all possible digits characters in every possible order) and hashing them and checking for a collision.
for more information on hashing and MD5 etc see: http://en.wikipedia.org/wiki/MD5 , http://en.wikipedia.org/wiki/Hash_function , http://en.wikipedia.org/wiki/Cryptographic_hash_function and http://onin.com/hhh/hhhexpl.html
I myself created my own app to do this, its open source you can check the link: http://sourceforge.net/projects/jpassrecovery/ and of course the source. Here is the source for easy access it has a basic implementation in the comments:
Bruter.java:
import java.util.ArrayList;
public class Bruter {
public ArrayList<String> characters = new ArrayList<>();
public boolean found = false;
public int maxLength;
public int minLength;
public int count;
long starttime, endtime;
public int minutes, seconds, hours, days;
public char[] specialCharacters = {'~', '`', '!', '@', '#', '$', '%', '^',
'&', '*', '(', ')', '_', '-', '+', '=', '{', '}', '[', ']', '|', '\\',
';', ':', '\'', '"', '<', '.', ',', '>', '/', '?', ' '};
public boolean done = false;
public boolean paused = false;
public boolean isFound() {
return found;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
public boolean isPaused() {
return paused;
}
public void setFound(boolean found) {
this.found = found;
}
public synchronized void setEndtime(long endtime) {
this.endtime = endtime;
}
public int getCounter() {
return count;
}
public long getRemainder() {
return getNumberOfPossibilities() - count;
}
public long getNumberOfPossibilities() {
long possibilities = 0;
for (int i = minLength; i <= maxLength; i++) {
possibilities += (long) Math.pow(characters.size(), i);
}
return possibilities;
}
public void addExtendedSet() {
for (char c = (char) 0; c <= (char) 31; c++) {
characters.add(String.valueOf(c));
}
}
public void addStandardCharacterSet() {
for (char c = (char) 32; c <= (char) 127; c++) {
characters.add(String.valueOf(c));
}
}
public void addLowerCaseLetters() {
for (char c = 'a'; c <= 'z'; c++) {
characters.add(String.valueOf(c));
}
}
public void addDigits() {
for (int c = 0; c <= 9; c++) {
characters.add(String.valueOf(c));
}
}
public void addUpperCaseLetters() {
for (char c = 'A'; c <= 'Z'; c++) {
characters.add(String.valueOf(c));
}
}
public void addSpecialCharacters() {
for (char c : specialCharacters) {
characters.add(String.valueOf(c));
}
}
public void setMaxLength(int i) {
maxLength = i;
}
public void setMinLength(int i) {
minLength = i;
}
public int getPerSecond() {
int i;
try {
i = (int) (getCounter() / calculateTimeDifference());
} catch (Exception ex) {
return 0;
}
return i;
}
public String calculateTimeElapsed() {
long timeTaken = calculateTimeDifference();
seconds = (int) timeTaken;
if (seconds > 60) {
minutes = (int) (seconds / 60);
if (minutes * 60 > seconds) {
minutes = minutes - 1;
}
if (minutes > 60) {
hours = (int) minutes / 60;
if (hours * 60 > minutes) {
hours = hours - 1;
}
}
if (hours > 24) {
days = (int) hours / 24;
if (days * 24 > hours) {
days = days - 1;
}
}
seconds -= (minutes * 60);
minutes -= (hours * 60);
hours -= (days * 24);
days -= (hours * 24);
}
return "Time elapsed: " + days + "days " + hours + "h " + minutes + "min " + seconds + "s";
}
private long calculateTimeDifference() {
long timeTaken = (long) ((endtime - starttime) * (1 * Math.pow(10, -9)));
return timeTaken;
}
public boolean excludeChars(String s) {
char[] arrayChars = s.toCharArray();
for (int i = 0; i < arrayChars.length; i++) {
characters.remove(arrayChars[i] + "");
}
if (characters.size() < maxLength) {
return false;
} else {
return true;
}
}
public int getMaxLength() {
return maxLength;
}
public int getMinLength() {
return minLength;
}
public void setIsDone(Boolean b) {
done = b;
}
public boolean isDone() {
return done;
}
}
HashBruter.java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.swing.JOptionPane;
public class HashBruter extends Bruter {
/*
* public static void main(String[] args) {
*
* final HashBruter hb = new HashBruter();
*
* hb.setMaxLength(5); hb.setMinLength(1);
*
* hb.addSpecialCharacters(); hb.addUpperCaseLetters();
* hb.addLowerCaseLetters(); hb.addDigits();
*
* hb.setType("sha-512");
*
* hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
*
* Thread thread = new Thread(new Runnable() {
*
* @Override public void run() { hb.tryBruteForce(); } });
*
* thread.start();
*
* while (!hb.isFound()) { System.out.println("Hash: " +
* hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
* hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
* hb.getCounter()); System.out.println("Estimated hashes left: " +
* hb.getRemainder()); }
*
* System.out.println("Found " + hb.getType() + " hash collision: " +
* hb.getGeneratedHash() + " password is: " + hb.getPassword());
*
* }
*/
public String hash, generatedHash, password;
public String type;
public String getType() {
return type;
}
public String getPassword() {
return password;
}
public void setHash(String p) {
hash = p;
}
public void setType(String digestType) {
type = digestType;
}
public String getGeneratedHash() {
return generatedHash;
}
public void tryBruteForce() {
starttime = System.nanoTime();
for (int size = minLength; size <= maxLength; size++) {
if (found == true || done == true) {
break;
} else {
while (paused) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
generateAllPossibleCombinations("", size);
}
}
done = true;
}
private void generateAllPossibleCombinations(String baseString, int length) {
while (paused) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
if (found == false || done == false) {
if (baseString.length() == length) {
if(type.equalsIgnoreCase("crc32")) {
generatedHash = generateCRC32(baseString);
} else if(type.equalsIgnoreCase("adler32")) {
generatedHash = generateAdler32(baseString);
} else if(type.equalsIgnoreCase("crc16")) {
generatedHash=generateCRC16(baseString);
} else if(type.equalsIgnoreCase("crc64")) {
generatedHash=generateCRC64(baseString.getBytes());
}
else {
generatedHash = generateHash(baseString.toCharArray());
}
password = baseString;
if (hash.equals(generatedHash)) {
password = baseString;
found = true;
done = true;
}
count++;
} else if (baseString.length() < length) {
for (int n = 0; n < characters.size(); n++) {
generateAllPossibleCombinations(baseString + characters.get(n), length);
}
}
}
}
private String generateHash(char[] passwordChar) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance(type);
} catch (NoSuchAlgorithmException e1) {
JOptionPane.showMessageDialog(null, "No such algorithm for hashes exists", "Error", JOptionPane.ERROR_MESSAGE);
}
String passwordString = new String(passwordChar);
byte[] passwordByte = passwordString.getBytes();
md.update(passwordByte, 0, passwordByte.length);
byte[] encodedPassword = md.digest();
String encodedPasswordInString = toHexString(encodedPassword);
return encodedPasswordInString;
}
private void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
private String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();
int len = block.length;
for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
}
return buf.toString();
}
private String generateCRC32(String baseString) {
//Convert string to bytes
byte bytes[] = baseString.getBytes();
Checksum checksum = new CRC32();
/*
* To compute the CRC32 checksum for byte array, use
*
* void update(bytes[] b, int start, int length)
* method of CRC32 class.
*/
checksum.update(bytes,0,bytes.length);
/*
* Get the generated checksum using
* getValue method of CRC32 class.
*/
return String.valueOf(checksum.getValue());
}
private String generateAdler32(String baseString) {
//Convert string to bytes
byte bytes[] = baseString.getBytes();
Checksum checksum = new Adler32();
/*
* To compute the CRC32 checksum for byte array, use
*
* void update(bytes[] b, int start, int length)
* method of CRC32 class.
*/
checksum.update(bytes,0,bytes.length);
/*
* Get the generated checksum using
* getValue method of CRC32 class.
*/
return String.valueOf(checksum.getValue());
}
/*************************************************************************
* Compilation: javac CRC16.java
* Execution: java CRC16 s
*
* Reads in a string s as a command-line argument, and prints out
* its 16-bit Cyclic Redundancy Check (CRC16). Uses a lookup table.
*
* Reference: http://www.gelato.unsw.edu.au/lxr/source/lib/crc16.c
*
* % java CRC16 123456789
* CRC16 = bb3d
*
* Uses irreducible polynomial: 1 + x^2 + x^15 + x^16
*
*
*************************************************************************/
private String generateCRC16(String baseString) {
int[] table = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040,
};
byte[] bytes = baseString.getBytes();
int crc = 0x0000;
for (byte b : bytes) {
crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff];
}
return Integer.toHexString(crc);
}
/*******************************************************************************
* Copyright (c) 2009, 2012 Mountainminds GmbH & Co. KG and Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Marc R. Hoffmann - initial API and implementation
*
*******************************************************************************/
/**
* CRC64 checksum calculator based on the polynom specified in ISO 3309. The
* implementation is based on the following publications:
*
* <ul>
* <li>http://en.wikipedia.org/wiki/Cyclic_redundancy_check</li>
* <li>http://www.geocities.com/SiliconValley/Pines/8659/crc.htm</li>
* </ul>
*/
private static final long POLY64REV = 0xd800000000000000L;
private static final long[] LOOKUPTABLE;
static {
LOOKUPTABLE = new long[0x100];
for (int i = 0; i < 0x100; i++) {
long v = i;
for (int j = 0; j < 8; j++) {
if ((v & 1) == 1) {
v = (v >>> 1) ^ POLY64REV;
} else {
v = (v >>> 1);
}
}
LOOKUPTABLE[i] = v;
}
}
/**
* Calculates the CRC64 checksum for the given data array.
*
* @param data
* data to calculate checksum for
* @return checksum value
*/
public static String generateCRC64(final byte[] data) {
long sum = 0;
for (int i = 0; i < data.length; i++) {
final int lookupidx = ((int) sum ^ data[i]) & 0xff;
sum = (sum >>> 8) ^ LOOKUPTABLE[lookupidx];
}
return String.valueOf(sum);
}
}
you would use it like:
final HashBruter hb = new HashBruter();
hb.setMaxLength(5); hb.setMinLength(1);
hb.addSpecialCharacters(); hb.addUpperCaseLetters();
hb.addLowerCaseLetters(); hb.addDigits();
hb.setType("sha-512");
hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
Thread thread = new Thread(new Runnable() {
@Override public void run() { hb.tryBruteForce(); } });
thread.start();
while (!hb.isFound()) { System.out.println("Hash: " +
hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
hb.getCounter()); System.out.println("Estimated hashes left: " +
hb.getRemainder()); }
System.out.println("Found " + hb.getType() + " hash collision: " +
hb.getGeneratedHash() + " password is: " + hb.getPassword());
I just wrote this and it looks more clean to me:
const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const readFile = util.promisify(fs.readFile);
const readFiles = async dirname => {
try {
const filenames = await readdir(dirname);
console.log({ filenames });
const files_promise = filenames.map(filename => {
return readFile(dirname + filename, 'utf-8');
});
const response = await Promise.all(files_promise);
//console.log({ response })
//return response
return filenames.reduce((accumlater, filename, currentIndex) => {
const content = response[currentIndex];
accumlater[filename] = {
content,
};
return accumlater;
}, {});
} catch (error) {
console.error(error);
}
};
const main = async () => {
const response = await readFiles(
'./folder-name',
);
console.log({ response });
};
_x000D_
You can modify the response
format according to your need.
The response
format from this code will look like:
{
"filename-01":{
"content":"This is the sample content of the file"
},
"filename-02":{
"content":"This is the sample content of the file"
}
}
This is what we use in ASP.NET:
// Stop Caching in IE
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
// Stop Caching in Firefox
Response.Cache.SetNoStore();
It stops caching in Firefox and IE, but we haven't tried other browsers. The following response headers are added by these statements:
Cache-Control: no-cache, no-store
Pragma: no-cache
There is obviously another process listening on the port. You might find out that process by using the following command:
$ lsof -i :8000
or change your tornado app's port. tornado's error info not Explicitly on this.
var myItem = myList.Find(item => item.property == "something");
Frank's answer pointed me in the right direction. I have a Digital Ocean droplet accessing a managed Digital Ocean Postgresql database. All I needed to do was add my droplet to the database's "Trusted Sources".
(click on database in DO console, then click on settings. Edit Trusted Sources and select droplet name (click in editable area and it will be suggested to you)).
The equivalent of LIMIT
is SET ROWCOUNT
, but if you want generic pagination it's better to write a query like this:
;WITH Results_CTE AS
(
SELECT
Col1, Col2, ...,
ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
FROM Table
WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit
The advantage here is the parameterization of the offset and limit in case you decide to change your paging options (or allow the user to do so).
Note: the @Offset
parameter should use one-based indexing for this rather than the normal zero-based indexing.
If you want to alter the original objects, then a simple Array#forEach
will do:
rockets.forEach(function(rocket) {
rocket.launches += 10;
});
If you want to keep the original objects unaltered, then use Array#map
and copy the objects using Object#assign
:
var newRockets = rockets.forEach(function(rocket) {
var newRocket = Object.assign({}, rocket);
newRocket.launches += 10;
return newRocket;
});
EDIT: When this answer was posted, {...obj}
syntax was not available in most browsers. Nowadays, you should be fine using it (unless you need to support IE 11).
Use Object.assign.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
However, this won't make a deep clone. There is no native way of deep cloning as of yet.
EDIT: As @Mike 'Pomax' Kamermans mentioned in the comments, you can deep clone simple objects (ie. no prototypes, functions or circular references) using JSON.parse(JSON.stringify(input))
h = fspecial('average', n);
filter2(h, img);
See doc fspecial
:
h = fspecial('average', n)
returns an averaging filter. n
is a 1-by-2 vector specifying the number of rows and columns in h
.
Whenever I need to do this I build a simple PL/SQL block with a local procedure like this:
declare
procedure ins
is
(p_exch_wh_key INTEGER,
p_exch_nat_key INTEGER,
p_exch_date DATE, exch_rate NUMBER,
p_from_curcy_cd VARCHAR2,
p_to_curcy_cd VARCHAR2,
p_exch_eff_date DATE,
p_exch_eff_end_date DATE,
p_exch_last_updated_date DATE);
begin
insert into tmp_dim_exch_rt
(exch_wh_key,
exch_nat_key,
exch_date, exch_rate,
from_curcy_cd,
to_curcy_cd,
exch_eff_date,
exch_eff_end_date,
exch_last_updated_date)
values
(p_exch_wh_key,
p_exch_nat_key,
p_exch_date, exch_rate,
p_from_curcy_cd,
p_to_curcy_cd,
p_exch_eff_date,
p_exch_eff_end_date,
p_exch_last_updated_date);
end;
begin
ins (1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
ins (2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
ins (3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
ins (4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
ins (5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
ins (6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008');
end;
/
I recently had to build something similar. You can check it out in the snippet below.
The version I had to build uses the same button to start and stop the spinner, but you can manipulate to code if you have a button to start the spin and a different button to stop the spin
Basically, my code looks like this...
Run Code Snippet
var rocket = document.querySelector('.rocket');_x000D_
var btn = document.querySelector('.toggle');_x000D_
var rotate = false;_x000D_
var runner;_x000D_
var degrees = 0;_x000D_
_x000D_
function start(){_x000D_
runner = setInterval(function(){_x000D_
degrees++;_x000D_
rocket.style.webkitTransform = 'rotate(' + degrees + 'deg)';_x000D_
},50)_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
clearInterval(runner);_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', function(){_x000D_
if (!rotate){_x000D_
rotate = true;_x000D_
start();_x000D_
} else {_x000D_
rotate = false;_x000D_
stop();_x000D_
}_x000D_
})
_x000D_
body {_x000D_
background: #1e1e1e;_x000D_
} _x000D_
_x000D_
.rocket {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
margin: 1em;_x000D_
border: 3px dashed teal;_x000D_
border-radius: 50%;_x000D_
background-color: rgba(128,128,128,0.5);_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.rocket h1 {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
font-size: .8em;_x000D_
color: skyblue;_x000D_
letter-spacing: 1em;_x000D_
text-shadow: 0 0 10px black;_x000D_
}_x000D_
_x000D_
.toggle {_x000D_
margin: 10px;_x000D_
background: #000;_x000D_
color: white;_x000D_
font-size: 1em;_x000D_
padding: .3em;_x000D_
border: 2px solid red;_x000D_
outline: none;_x000D_
letter-spacing: 3px;_x000D_
}
_x000D_
<div class="rocket"><h1>SPIN ME</h1></div>_x000D_
<button class="toggle">I/0</button>
_x000D_
Probably you want something like:
firstline = True
for row in kidfile:
if firstline: #skip first line
firstline = False
continue
# parse the line
An other way to achive the same result is calling readline
before the loop:
kidfile.readline() # skip the first line
for row in kidfile:
#parse the line
Updated @ErickPetru for rgba compatibility:
function rgb2hex(rgb) {
rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
I updated the regex to match the alpha value if defined, but not use it.
You could create a custom pipe to return the list of key for each element. Something like that:
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push(key);
}
return keys;
}
}
and use it like that:
<tr *ngFor="let c of content">
<td *ngFor="let key of c | keys">{{key}}: {{c[key]}}</td>
</tr>
Edit
You could also return an entry containing both key and value:
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
and use it like that:
<span *ngFor="let entry of content | keys">
Key: {{entry.key}}, value: {{entry.value}}
</span>
To see what the problem is, when you get the cryptic error 0 go to ... | More Tools | Developer Tools (Ctrl+Shift+I) in Chrome (on the page giving the error)
Read the red text in the log to get the true error message. If there is too much in there, right-click and Clear Console, then do your last request again.
My first problem was, I was passing in Authorization headers to my own cross-domain web service for the browser for the first time.
I already had:
Access-Control-Allow-Origin: *
But not:
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
in the response header of my web service.
After I added that, my error zero was gone from my own web server, as well as when running the index.html file locally without a web server, but was still giving errors in code pen.
Back to ... | More Tools | Developer Tools while getting the error in codepen, and there is clearly explained: codepen uses https, so I cannot make calls to http, as the security is lower.
I need to therefore host my web service on https.
Knowing how to get the true error message - priceless!
The adb tool can be found in sdk/platform-tools/
If you don't see this directory in your SDK, launch the SDK Manager and install "Android SDK Platform-tools"
Also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.
glBegin(GL_POLYGON); // Middle circle
double radius = 0.2;
double ori_x = 0.0; // the origin or center of circle
double ori_y = 0.0;
for (int i = 0; i <= 300; i++) {
double angle = 2 * PI * i / 300;
double x = cos(angle) * radius;
double y = sin(angle) * radius;
glVertex2d(ori_x + x, ori_y + y);
}
glEnd();
I had this problem for *.sh files in Yosemite and couldn't figure out what the correct path is for a folder on my Desktop...after some gnashing of teeth, dragged the file itself into the Terminal window; hey presto!!
Your code was very close to working.
Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.
Here's some code that writes each key/value pair on a separate row:
import csv
somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerows(somedict.items())
If instead you want all the keys on one row and all the values on the next, that is also easy:
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerow(somedict.keys())
w.writerow(somedict.values())
Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr)
so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f)
.
Add
session_start();
at the beginning of your page before any HTML
You will have something like :
<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...
Don't forget to remove the space you have before
Fast
fun unicodeDecode(unicode: String): String {
val stringBuffer = StringBuilder()
var i = 0
while (i < unicode.length) {
if (i + 1 < unicode.length)
if (unicode[i].toString() + unicode[i + 1].toString() == "\\u") {
val symbol = unicode.substring(i + 2, i + 6)
val c = Integer.parseInt(symbol, 16)
stringBuffer.append(c.toChar())
i += 5
} else stringBuffer.append(unicode[i])
i++
}
return stringBuffer.toString()
}
best way is
button.setBackgroundResource(android.R.drawable.ic_delete);
OR this for Drawable left and something like that for right etc.
int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
and
getResources().getDrawable()
is now deprecated
Final class. Thanks @eXXL.
public class Properties
{
private Dictionary<String, String> list;
private String filename;
public Properties(String file)
{
reload(file);
}
public String get(String field, String defValue)
{
return (get(field) == null) ? (defValue) : (get(field));
}
public String get(String field)
{
return (list.ContainsKey(field))?(list[field]):(null);
}
public void set(String field, Object value)
{
if (!list.ContainsKey(field))
list.Add(field, value.ToString());
else
list[field] = value.ToString();
}
public void Save()
{
Save(this.filename);
}
public void Save(String filename)
{
this.filename = filename;
if (!System.IO.File.Exists(filename))
System.IO.File.Create(filename);
System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
foreach(String prop in list.Keys.ToArray())
if (!String.IsNullOrWhiteSpace(list[prop]))
file.WriteLine(prop + "=" + list[prop]);
file.Close();
}
public void reload()
{
reload(this.filename);
}
public void reload(String filename)
{
this.filename = filename;
list = new Dictionary<String, String>();
if (System.IO.File.Exists(filename))
loadFromFile(filename);
else
System.IO.File.Create(filename);
}
private void loadFromFile(String file)
{
foreach (String line in System.IO.File.ReadAllLines(file))
{
if ((!String.IsNullOrEmpty(line)) &&
(!line.StartsWith(";")) &&
(!line.StartsWith("#")) &&
(!line.StartsWith("'")) &&
(line.Contains('=')))
{
int index = line.IndexOf('=');
String key = line.Substring(0, index).Trim();
String value = line.Substring(index + 1).Trim();
if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
(value.StartsWith("'") && value.EndsWith("'")))
{
value = value.Substring(1, value.Length - 2);
}
try
{
//ignore dublicates
list.Add(key, value);
}
catch { }
}
}
}
}
Sample use:
//load
Properties config = new Properties(fileConfig);
//get value whith default value
com_port.Text = config.get("com_port", "1");
//set value
config.set("com_port", com_port.Text);
//save
config.Save()
TL;DR:
if (navigate) {
return <Redirect to="/" push={true} />
}
The simple and declarative answer is that you need to use <Redirect to={URL} push={boolean} />
in combination with setState()
push: boolean - when true, redirecting will push a new entry onto the history instead of replacing the current one.
import { Redirect } from 'react-router'
class FooBar extends React.Component {
state = {
navigate: false
}
render() {
const { navigate } = this.state
// here is the important part
if (navigate) {
return <Redirect to="/" push={true} />
}
// ^^^^^^^^^^^^^^^^^^^^^^^
return (
<div>
<button onClick={() => this.setState({ navigate: true })}>
Home
</button>
</div>
)
}
}
Full example here. Read more here.
PS. The example uses ES7+ Property Initializers to initialise state. Look here as well, if you're interested.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set up notitle
requestWindowFeature(Window.FEATURE_NO_TITLE);
//set up full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
Here's a method for getting the version from the pom.properties, falling back to getting it from the manifest
public synchronized String getVersion() {
String version = null;
// try to load from maven properties first
try {
Properties p = new Properties();
InputStream is = getClass().getResourceAsStream("/META-INF/maven/com.my.group/my-artefact/pom.properties");
if (is != null) {
p.load(is);
version = p.getProperty("version", "");
}
} catch (Exception e) {
// ignore
}
// fallback to using Java API
if (version == null) {
Package aPackage = getClass().getPackage();
if (aPackage != null) {
version = aPackage.getImplementationVersion();
if (version == null) {
version = aPackage.getSpecificationVersion();
}
}
}
if (version == null) {
// we could not compute the version so use a blank
version = "";
}
return version;
}
You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
If the customer does not exist, you'll get an sql exception which text will be something like:
null value in column "customer_id" violates not-null constraint
(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:
insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.
We can use RegularExpressionValidator to validate email address format. You need to specify the regular expression in ValidationExpression property of RegularExpressionValidator. So it will look like
<asp:RegularExpressionValidator ID="validateEmail"
runat="server" ErrorMessage="Invalid email."
ControlToValidate="txtEmail"
ValidationExpression="^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" />
Also in event handler of button or link you need to check !Page.IsValid. Check sample code here : sample code
Also if you don't want to use RegularExpressionValidator you can write simple validate method and in that method usinf RegEx class of System.Text.RegularExpressions namespace.
Check example:
Just Call super.variable in sub class constructor
public abstract class Beverage {
int cost;
int getCost() {
return cost;
}
}`
public class Coffee extends Beverage {
int cost = 10;
Coffee(){
super.cost = cost;
}
}`
public class Driver {
public static void main(String[] args) {
Beverage coffee = new Coffee();
System.out.println(coffee.getCost());
}
}
Output is 10.
In Xcode 4.5.2 goto Product -> Edit Scheme -> and Under the Diagnostics tab check the check box in between Objective C and Enable Zombie Objects and Click on OK
In this sample, I created a JavaScript progress bar (with percentage display), you can control it and hide it with JavaScript.
In this sample, the progress bar advances every 100ms. You can see it in JSFiddle
var elapsedTime = 0;
var interval = setInterval(function() {
timer()
}, 100);
function progressbar(percent) {
document.getElementById("prgsbarcolor").style.width = percent + '%';
document.getElementById("prgsbartext").innerHTML = percent + '%';
}
function timer() {
if (elapsedTime > 100) {
document.getElementById("prgsbartext").style.color = "#FFF";
document.getElementById("prgsbartext").innerHTML = "Completed.";
if (elapsedTime >= 107) {
clearInterval(interval);
history.go(-1);
}
} else {
progressbar(elapsedTime);
}
elapsedTime++;
}
If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:
The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.
In batch you could do it like this:
@echo off
setlocal EnableDelayedExpansion
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do (
set "var=%%sxyz"
svn co "!var!"
)
If you don't need the variable !var!
elsewhere in the loop, you could simplify that to
@echo off
setlocal
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do svn co "%%sxyz"
However, like C.B. I'd prefer PowerShell if at all possible:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object {
$var = "${_}xyz" # alternatively: $var = $_ + 'xyz'
svn co $var
}
Again, this could be simplified if you don't need $var
elsewhere in the loop:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }
As stated by @Dugini, some config entries have been removed. Maximal:
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":[],
"proxyType":"MANUAL"
}
The problem with every other answer in this thread is that none of them properly parse all special cases of the strings within the enum.
The biggest special case character that was throwing me for a loop was single quotes, as they are encoded themselves as 2 single quotes together! So, for example, an enum with the value 'a'
is encoded as enum('''a''')
. Horrible, right?
Well, the solution is to use MySQL to parse the data for you!
Since everyone else is using PHP in this thread, that is what I will use. Following is the full code. I will explain it after. The parameter $FullEnumString
will hold the entire enum string, extracted from whatever method you want to use from all the other answers. RunQuery()
and FetchRow()
(non associative) are stand ins for your favorite DB access methods.
function GetDataFromEnum($FullEnumString)
{
if(!preg_match('/^enum\((.*)\)$/iD', $FullEnumString, $Matches))
return null;
return FetchRow(RunQuery('SELECT '.$Matches[1]));
}
preg_match('/^enum\((.*)\)$/iD', $FullEnumString, $Matches)
confirms that the enum value matches what we expect, which is to say, "enum(".$STUFF.")"
(with nothing before or after). If the preg_match fails, NULL
is returned.
This preg_match
also stores the list of strings, escaped in weird SQL syntax, in $Matches[1]
. So next, we want to be able to get the real data out of that. So you just run "SELECT ".$Matches[1]
, and you have a full list of the strings in your first record!
So just pull out that record with a FetchRow(RunQuery(...))
and you’re done.
If you wanted to do this entire thing in SQL, you could use the following
SET @TableName='your_table_name', @ColName='your_col_name';
SET @Q=(SELECT CONCAT('SELECT ', (SELECT SUBSTR(COLUMN_TYPE, 6, LENGTH(COLUMN_TYPE)-6) FROM information_schema.COLUMNS WHERE TABLE_NAME=@TableName AND COLUMN_NAME=@ColName)));
PREPARE stmt FROM @Q;
EXECUTE stmt;
P.S. To preempt anyone from saying something about it, no, I do not believe this method can lead to SQL injection.
Short solution using C++11 and toupper().
for (auto & c: str) c = toupper(c);
Another solution, very light with high performance with payload large:
Android Asynchronous Http Client library: http://loopj.com/android-async-http/
private static AsyncHttpClient client = new AsyncHttpClient();
private void uploadFileExecute(File file) {
RequestParams params = new RequestParams();
try { params.put("photo", file); } catch (FileNotFoundException e) {}
client.post(getUrl(), params,
new AsyncHttpResponseHandler() {
public void onSuccess(String result) {
Log.d(TAG,"uploadFile response: "+result);
};
public void onFailure(Throwable arg0, String errorMsg) {
Log.d(TAG,"uploadFile ERROR!");
};
}
);
}
Just develop a normal app and then add a couple of lines to the app's manifest file.
First you need to add the following attribute to your activity:
android:launchMode="singleTask"
Then add two categories to the intent filter :
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
The result could look something like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dummy.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.dummy.app.MainActivity"
android:launchMode="singleTask"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</activity>
</application>
</manifest>
It's that simple!
It is important to note that you could use Emmet to achieve the same result. First, check what Emmet can do for you at https://emmet.io/
In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below:
Example #1
ul>li*5
... will produce
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Example #2
div#header+div.page+div#footer.class1.class2.class3
... will produce
<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>
And list goes on. There are more examples at https://docs.emmet.io/abbreviations/syntax/
And there is a library for doing that using jQuery. It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js
You have a class on your CSS that is overwriting your width and height, the class reads as such:
.postItem img {
height: auto;
width: 450px;
}
Remove that and your width/height properties on the img
tag should work.
Simple Pass Intent first
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
And u will get picture path on u onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
In my case in Angular-5, service file was not imported from which i was accessing the method and subscribing the data.After importing service file it worked fine.
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
all the above did not work when i used cloudflare, this one worked for me:
RewriteCond %{HTTP:X-Forwarded-Proto} =https
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
and this one definitely works without proxies in the way:
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
**How to accept array by user Input
Answer:-
import java.io.*;
import java.lang.*;
class Reverse1 {
public static void main(String args[]) throws IOException {
int a[]=new int[25];
int num=0,i=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of element");
num=Integer.parseInt(br.readLine());
System.out.println("Enter the array");
for(i=1;i<=num;i++) {
a[i]=Integer.parseInt(br.readLine());
}
for(i=num;i>=1;i--) {
System.out.println(a[i]);
}
}
}
user334291's answer was a life saver for me. Just want to add how you can add what the OP originally intended to do (what I ended up using):
Overriding the GetWebRequest function on the generated webservice code:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.WebRequest request = base.GetWebRequest(uri);
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(this.Credentials.GetCredential(uri, "Basic").UserName + ":" + this.Credentials.GetCredential(uri, "Basic").Password));
request.Headers.Add("Authorization", auth);
return request;
}
and setting the credentials before calling the webservice:
client.Credentials = new NetworkCredential(user, password);
var fs = require('fs');
var path = require('path');
exports.testDir = path.dirname(__filename);
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
exports.libDir = path.join(exports.testDir, '../lib');
exports.tmpDir = path.join(exports.testDir, 'tmp');
exports.PORT = +process.env.NODE_COMMON_PORT || 12346;
// Read File
fs.readFile(exports.tmpDir+'/start.html', 'utf-8', function(err, content) {
if (err) {
got_error = true;
} else {
console.log('cat returned some content: ' + content);
console.log('this shouldn\'t happen as the file doesn\'t exist...');
//assert.equal(true, false);
}
});
In more modern browsers (including IE 10+) you can now use calc()
:
.moveto {
top: 0px;
left: calc(100% - 50px);
}
A simple example:
public class Test extends Thread {
public synchronized void run() {
for (int i = 0; i <= 10; i++) {
System.out.println("i::"+i);
}
}
public static void main(String[] args) {
Test obj = new Test();
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
Thread t3 = new Thread(obj);
t1.start();
t2.start();
t3.start();
}
}
I basically did what was on this answer: https://stackoverflow.com/a/11032521/1286423
(for history, I'll copy-paste it here)
$ git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch YOURFILENAME" HEAD
$ rm -rf .git/refs/original/
$ git reflog expire --all
$ git gc --aggressive --prune
$ git push origin master --force
It didn't work, because I like to rename and move things a lot. So some big file were in folders that have been renamed, and I think the gc couldn't delete the reference to those files because of reference in tree
objects pointing to those file.
My ultimate solution to really kill it was to:
# First, apply what's in the answer linked in the front
# and before doing the gc --prune --aggressive, do:
# Go back at the origin of the repository
git checkout -b newinit <sha1 of first commit>
# Create a parallel initial commit
git commit --amend
# go back on the master branch that has big file
# still referenced in history, even though
# we thought we removed them.
git checkout master
# rebase on the newinit created earlier. By reapply patches,
# it will really forget about the references to hidden big files.
git rebase newinit
# Do the previous part (checkout + rebase) for each branch
# still connected to the original initial commit,
# so we remove all the references.
# Remove the .git/logs folder, also containing references
# to commits that could make git gc not remove them.
rm -rf .git/logs/
# Then you can do a garbage collection,
# and the hidden files really will get gc'ed
git gc --prune --aggressive
My repo (the .git
) changed from 32MB to 388KB, that even filter-branch couldn't clean.
jQuery's data()
method will give you access to data-*
attributes, BUT, it clobbers the case of the attribute name. You can either use this:
$('#myButton').data("x10") // note the lower case
Or, you can use the attr()
method, which preserves your case:
$('#myButton').attr("data-X10")
Try both methods here: http://jsfiddle.net/q5rbL/
Be aware that these approaches are not completely equivalent. If you will change the data-*
attribute of an element, you should use attr()
. data()
will read the value once initially, then continue to return a cached copy, whereas attr()
will re-read the attribute each time.
Note that jQuery will also convert hyphens in the attribute name to camel case (source -- i.e. data-some-data == $(ele).data('someData')
). Both of these conversions are in conformance with the HTML specification, which dictates that custom data attributes should contain no uppercase letters, and that hyphens will be camel-cased in the dataset
property (source). jQuery's data
method is merely mimicking/conforming to this standard behavior.
Documentation
data
- http://api.jquery.com/data/attr
- http://api.jquery.com/attr/a quick way to find out WHERE YOUR particular executable is located on your $PATH, try.
Even quicker way to find out where php
is ...
whereis php
I'm running debian
and above command showing me
php: /usr/bin/php /usr/share/php /usr/share/man/man1/php.1.gz
Hope that helps.
A simpler way is
ggplot(data=df, aes(x=xvar, y=yvar)) +
geom_point()
ggsave(path = path, width = width, height = height, device='tiff', dpi=700)
With moment you can parse the date string you have:
var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")
That's for UTC, you'll have to convert the time zone from that point if you so desire.
Then you can get the day of the week:
dt.format('dddd');
Try to use appendChild method:
select.appendChild(option);
I had the same error, because of the JUnit version. I had three 3.8.1, and I have changed to 4.8.1.
So the solution is:
You have to go to the POM, and make sure that you dependency looks like this
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
if 'a' is already a decimal; adding '.' would make 3.4/b(for example) into 3.4./b
Try float(a)/b
It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]
?
The major difference between the two is that $_SERVER['SERVER_NAME']
is a server controlled variable, while $_SERVER['HTTP_HOST']
is a user-controlled value.
The rule of thumb is to never trust values from the user, so $_SERVER['SERVER_NAME']
is the better choice.
As Gumbo pointed out, Apache will construct SERVER_NAME from user-supplied values if you don't set UseCanonicalName On
.
Edit: Having said all that, if the site is using a name-based virtual host, the HTTP Host header is the only way to reach sites that aren't the default site.
There is also Mappa - http://mappatool.com/.
It only supports polygons, but they are definitely the hardest parts :)
The Mozilla.org FAQ on debugging Mozilla on Windows is of interest here.
In short, the Visual Studio debugger can be invoked on a program from the command line, allowing one to specify the command line arguments when invoking a command line program, directly on the command line.
This looks like the following for Visual Studio 8 or 9 (Visual Studio 2005 or Visual Studio 2008, respectively)
devenv /debugexe 'program name' 'program arguments'
It is also possible to have an explorer action to start a program in the Visual Studio debugger.
You can also get the API key in the android studio. Switch to Project view in android then find the google-services.json. Scroll down and you will find the api_key
Another way to do this (in modern browsers) is with a negative spread box-shadow. Check out this updated fiddle: http://jsfiddle.net/WuZat/290/
box-shadow: 0px 24px 3px -24px magenta;
I think the safest and most compatible way is the accepted answer above, though. Just thought I'd share another technique.
I'm on 4.4.2, and calling overridePendingTransition(0, 0) in the launching activity's onCreate() will disable the starting animation (calling overridePendingTransition(0, 0) immediately after startActivity() did NOT work). As noted in another answer, calling overridePendingTransition(0, 0) after finish() disables the closing animation.
Btw, I found that setting the style with "android:windowAnimationStyle">@null (another answer mentioned here) caused a crash when my launching activity tried to set the action bar title. Debugging further, I discovered that somehow this causes window.hasFeature(Window.FEATURE_ACTION_BAR) to fail in the Activity's initActionBar().
Not tested but you can try something like this :
Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))
while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile ,
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists
when 1 then 'Yes'
else 'No'
end as isExists
set @count=@count+1
END
Swift 4
To get the first N elements of a Swift array you can use prefix(_ maxLength: Int)
:
Array(largeArray.prefix(5))
If the longValue
variable is of type Long
(the wrapper class, not the primitive long
), then yes you can check for null values.
A primitive variable needs to be initialized to some value explicitly (e.g. to 0
) so its value will never be null.
Just to offer you a different angle -
I find it's not a good idea to maintain public variables between function calls. Any variables you need to use should be stored in Subs and Functions and passed as parameters. Once the code is done running, you shouldn't expect the VBA Project to maintain the values of any variables.
The reason for this is that there is just a huge slew of things that can inadvertently reset the VBA Project while using the workbook. When this happens, any public variables get reset to 0.
If you need a value to be stored outside of your subs and functions, I highly recommend using a hidden worksheet with named ranges for any information that needs to persist.
In case anyone finds this question and you want to open up settings for your specific application:
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
intent.data = Uri.parse("package:" + context.packageName)
startActivity(intent)
Media queries are not supported at all in IE8 and below.
To add support for IE8, you could use one of several JS solutions. For example, Respond can be added to add media query support for IE8 only with the following code :
<!--[if lt IE 9]>
<script
src="respond.min.js">
</script>
<![endif]-->
CSS Mediaqueries is another library that does the same thing. The code for adding that library to your HTML would be identical :
<!--[if lt IE 9]>
<script
src="css3-mediaqueries.js">
</script>
<![endif]-->
If you don't like a JS based solution, you should also consider adding an IE<9 only stylesheet where you adjust your styling specific to IE<9. For that, you should add the following HTML to your code:
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" media="all" href="style-ielt9.css"/>
<![endif]-->
Note :
Technically it's one more alternative: using CSS hacks to target IE<9. It has the same impact as an IE<9 only stylesheet, but you don't need a seperate stylesheet for that. I do not recommend this option, though, as they produce invalid CSS code (which is but one of several reasons why the use of CSS hacks is generally frowned upon today).
The simple thing is to put the script below the document, just before your closing </body>
tag:
<body>
<div id="main">
<div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>
<script src="app.js"></script>
</body>
app.js file:
var main = new Vue({
el: '#main',
data: {
currentActivity: 'home'
}
});
The TLDR:
.config("spark.master", "local")
a list of the options for spark.master in spark 2.2.1
I ended up on this page after trying to run a simple Spark SQL java program in local mode. To do this, I found that I could set spark.master using:
SparkSession spark = SparkSession
.builder()
.appName("Java Spark SQL basic example")
.config("spark.master", "local")
.getOrCreate();
An update to my answer:
To be clear, this is not what you should do in a production environment. In a production environment, spark.master should be specified in one of a couple other places: either in $SPARK_HOME/conf/spark-defaults.conf (this is where cloudera manager will put it), or on the command line when you submit the app. (ex spark-submit --master yarn).
If you specify spark.master to be 'local' in this way, spark will try to run in a single jvm, as indicated by the comments below. If you then try to specify --deploy-mode cluster, you will get an error 'Cluster deploy mode is not compatible with master "local"'. This is because setting spark.master=local means that you are NOT running in cluster mode.
Instead, for a production app, within your main function (or in functions called by your main function), you should simply use:
SparkSession
.builder()
.appName("Java Spark SQL basic example")
.getOrCreate();
This will use the configurations specified on the command line/in config files.
Also, to be clear on this too: --master and "spark.master" are the exact same parameter, just specified in different ways. Setting spark.master in code, like in my answer above, will override attempts to set --master, and will override values in spark-defaults.conf, so don't do it in production. Its great for tests though.
also, see this answer. which links to a list of the options for spark.master and what each one actually does.
Every node.js process is single threaded by design. Therefore to get multiple threads, you have to have multiple processes (As some other posters have pointed out, there are also libraries you can link to that will give you the ability to work with threads in Node, but no such capability exists without those libraries. See answer by Shawn Vincent referencing https://github.com/audreyt/node-webworker-threads)
You can start child processes from your main process as shown here in the node.js documentation: http://nodejs.org/api/child_process.html. The examples are pretty good on this page and are pretty straight forward.
Your parent process can then watch for the close event on any process it started and then could force close the other processes you started to achieve the type of one fail all stop strategy you are talking about.
Also see: Node.js on multi-core machines
Well maybe a little late after 4 years haha... but I was looking for solution to do OBJECT to CSV, however most solutions here is actually for ARRAY to CSV...
After some tinkering, here is my solution to convert object into CSV, I think is pretty neat. Hope this would help someone else.
$resp = array();
foreach ($entries as $entry) {
$row = array();
foreach ($entry as $key => $value) {
array_push($row, $value);
}
array_push($resp, implode(',', $row));
}
echo implode(PHP_EOL, $resp);
Note that for the $key => $value
to work, your object
's attributes must be public, the private ones will not get fetched.
The end result is that you get something like this:
blah,blah,blah
blah,blah,blah
With jQuery (and without FormData API) you can use something like this:
function readFile(file){
var loader = new FileReader();
var def = $.Deferred(), promise = def.promise();
//--- provide classic deferred interface
loader.onload = function (e) { def.resolve(e.target.result); };
loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
loader.onerror = loader.onabort = function (e) { def.reject(e); };
promise.abort = function () { return loader.abort.apply(loader, arguments); };
loader.readAsBinaryString(file);
return promise;
}
function upload(url, data){
var def = $.Deferred(), promise = def.promise();
var mul = buildMultipart(data);
var req = $.ajax({
url: url,
data: mul.data,
processData: false,
type: "post",
async: true,
contentType: "multipart/form-data; boundary="+mul.bound,
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
def.notify(percent);
}
}, false);
}
return xhr;
}
});
req.done(function(){ def.resolve.apply(def, arguments); })
.fail(function(){ def.reject.apply(def, arguments); });
promise.abort = function(){ return req.abort.apply(req, arguments); }
return promise;
}
var buildMultipart = function(data){
var key, crunks = [], bound = false;
while (!bound) {
bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
}
for (var key = 0, l = data.length; key < l; key++){
if (typeof(data[key].value) !== "string") {
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n"+
data[key].value[0]);
}else{
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
data[key].value);
}
}
return {
bound: bound,
data: crunks.join("\r\n")+"\r\n--"+bound+"--"
};
};
//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
var formData = form.find(":input:not('#file')").serializeArray();
formData.file = [fileData, $file[0].files[0].name];
upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});
With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})
I had the exact same problem yesterday working through problem 2-3 in Accelerated C++. The key is to change all variables you will be comparing (using Boolean operators) to compatible types. In this case, that means string::size_type
(or unsigned int
, but since this example is using the former, I will just stick with that even though the two are technically compatible).
Notice that in their original code they did exactly this for the c counter (page 30 in Section 2.5 of the book), as you rightly pointed out.
What makes this example more complicated is that the different padding variables (padsides and padtopbottom), as well as all counters, must also be changed to string::size_type
.
Getting to your example, the code that you posted would end up looking like this:
cout << "Please enter the size of the frame between top and bottom";
string::size_type padtopbottom;
cin >> padtopbottom;
cout << "Please enter size of the frame from each side you would like: ";
string::size_type padsides;
cin >> padsides;
string::size_type c = 0; // definition of c in the program
if (r == padtopbottom + 1 && c == padsides + 1) { // where the error no longer occurs
Notice that in the previous conditional, you would get the error if you didn't initialize variable r as a string::size_type
in the for
loop. So you need to initialize the for loop using something like:
for (string::size_type r=0; r!=rows; ++r) //If r and rows are string::size_type, no error!
So, basically, once you introduce a string::size_type
variable into the mix, any time you want to perform a boolean operation on that item, all operands must have a compatible type for it to compile without warnings.
Its a bit late answer, but it covers merging images from urls using Picasso
MergeImageView
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.List;
public class MergeImageView extends ImageView {
private SparseArray<Bitmap> bitmaps = new SparseArray<>();
private Picasso picasso;
private final int DEFAULT_IMAGE_SIZE = 50;
private int MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE;
private int MAX_WIDTH = DEFAULT_IMAGE_SIZE * 2, MAX_HEIGHT = DEFAULT_IMAGE_SIZE * 2;
private String picassoRequestTag = null;
public MergeImageView(Context context) {
super(context);
}
public MergeImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean isInEditMode() {
return true;
}
public void clearResources() {
if (bitmaps != null) {
for (int i = 0; i < bitmaps.size(); i++)
bitmaps.get(i).recycle();
bitmaps.clear();
}
// cancel picasso requests
if (picasso != null && AppUtils.ifNotNullEmpty(picassoRequestTag))
picasso.cancelTag(picassoRequestTag);
picasso = null;
bitmaps = null;
}
public void createMergedBitmap(Context context, List<String> imageUrls, String picassoTag) {
picasso = Picasso.with(context);
int count = imageUrls.size();
picassoRequestTag = picassoTag;
boolean isEven = count % 2 == 0;
// if url size are not even make MIN_IMAGE_SIZE even
MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE + (isEven ? count / 2 : (count / 2) + 1);
// set MAX_WIDTH and MAX_HEIGHT to twice of MIN_IMAGE_SIZE
MAX_WIDTH = MAX_HEIGHT = MIN_IMAGE_SIZE * 2;
// in case of odd urls increase MAX_HEIGHT
if (!isEven) MAX_HEIGHT = MAX_WIDTH + MIN_IMAGE_SIZE;
// create default bitmap
Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wallpaper),
MIN_IMAGE_SIZE, MIN_IMAGE_SIZE, false);
// change default height (wrap_content) to MAX_HEIGHT
int height = Math.round(AppUtils.convertDpToPixel(MAX_HEIGHT, context));
setMinimumHeight(height * 2);
// start AsyncTask
for (int index = 0; index < count; index++) {
// put default bitmap as a place holder
bitmaps.put(index, bitmap);
new PicassoLoadImage(index, imageUrls.get(index)).execute();
// if you want parallel execution use
// new PicassoLoadImage(index, imageUrls.get(index)).(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private class PicassoLoadImage extends AsyncTask<String, Void, Bitmap> {
private int index = 0;
private String url;
PicassoLoadImage(int index, String url) {
this.index = index;
this.url = url;
}
@Override
protected Bitmap doInBackground(String... params) {
try {
// synchronous picasso call
return picasso.load(url).resize(MIN_IMAGE_SIZE, MIN_IMAGE_SIZE).tag(picassoRequestTag).get();
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(Bitmap output) {
super.onPostExecute(output);
if (output != null)
bitmaps.put(index, output);
// create canvas
Bitmap.Config conf = Bitmap.Config.RGB_565;
Bitmap canvasBitmap = Bitmap.createBitmap(MAX_WIDTH, MAX_HEIGHT, conf);
Canvas canvas = new Canvas(canvasBitmap);
canvas.drawColor(Color.WHITE);
// if height and width are equal we have even images
boolean isEven = MAX_HEIGHT == MAX_WIDTH;
int imageSize = bitmaps.size();
int count = imageSize;
// we have odd images
if (!isEven) count = imageSize - 1;
for (int i = 0; i < count; i++) {
Bitmap bitmap = bitmaps.get(i);
canvas.drawBitmap(bitmap, bitmap.getWidth() * (i % 2), bitmap.getHeight() * (i / 2), null);
}
// if images are not even set last image width to MAX_WIDTH
if (!isEven) {
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmaps.get(count), MAX_WIDTH, MIN_IMAGE_SIZE, false);
canvas.drawBitmap(scaledBitmap, scaledBitmap.getWidth() * (count % 2), scaledBitmap.getHeight() * (count / 2), null);
}
// set bitmap
setImageBitmap(canvasBitmap);
}
}
}
xml
<com.example.MergeImageView
android:id="@+id/iv_thumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Example
List<String> urls = new ArrayList<>();
String picassoTag = null;
// add your urls
((MergeImageView)findViewById(R.id.iv_thumb)).
createMergedBitmap(MainActivity.this, urls,picassoTag);
Suppose you have a data frame(say df) with columns "x" and "y", you can find mean of column (x or y) using:
1.Using mean() function
z<-mean(df$x)
2.Using the column name(say x) as a variable using attach()
function
attach(df)
mean(x)
When done you can call detach()
to remove "x"
detach()
3.Using with()
function, it lets you use columns of data frame as distinct variables.
z<-with(df,mean(x))
You can also try:
create table new_table as
select * from table1
union
select * from table2
It means that trackDAO
should not be serialized.
Try to use this code:
.col-lg-3 {
width: 100%;
}
.input-group {
width: 200px; // for exemple
margin: 0 auto;
}
if it didn't work use !important
I like simple javascript, and I usually have jQuery around. Here's what I came up with, based off mparkuk's:
function typeInTextarea(el, newText) {
var start = el.prop("selectionStart")
var end = el.prop("selectionEnd")
var text = el.val()
var before = text.substring(0, start)
var after = text.substring(end, text.length)
el.val(before + newText + after)
el[0].selectionStart = el[0].selectionEnd = start + newText.length
el.focus()
}
$("button").on("click", function() {
typeInTextarea($("textarea"), "some text")
return false
})
Here's a demo: http://codepen.io/erikpukinskis/pen/EjaaMY?editors=101
Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:
registered(X, Y) :-
X = ct101; X = ct102; X = ct103.
For a fuller explanation:
You can use nonzero function. it returns the nonzero indices of the given input.
Easy Way
>>> (e > 15).nonzero()
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
to see the indices more cleaner, use transpose
method:
>>> numpy.transpose((e>15).nonzero())
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Not Bad Way
>>> numpy.nonzero(e > 15)
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
or the clean way:
>>> numpy.transpose(numpy.nonzero(e > 15))
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
"How do I for example read a 3 bit integer value starting at the second bit?"
int number = // whatever;
uint8_t val; // uint8_t is the smallest data type capable of holding 3 bits
val = (number & (1 << 2 | 1 << 3 | 1 << 4)) >> 2;
(I assumed that "second bit" is bit #2, i. e. the third bit really.)
You can do something like this:
$('.notice')
.fadeIn()
.animate({opacity: '+=0'}, 2000) // Does nothing for 2000ms
.fadeOut('fast');
Sadly, you can't just do .animate({}, 2000) -- I think this is a bug, and will report it.