1, 2, 3 ,... are invalid identifiers in python because first of all they are integer objects and secondly in python a variable name can't start with a number.
>>> 1 = 12 #you can't assign to an integer
File "<ipython-input-177-30a62b7248f1>", line 1
SyntaxError: can't assign to literal
>>> 1a = 12 #1a is an invalid variable name
File "<ipython-input-176-f818ca46b7dc>", line 1
1a = 12
^
SyntaxError: invalid syntax
Valid identifier definition:
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
It appears to only be availabe using the mysqlnd driver.
Try replacing it with the integer it represents; 1002, if I am not mistaken.
Note: As of 17.0 from_csv
is discouraged: use pd.read_csv
instead
The documentation lists a .from_csv function that appears to do what you want:
DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')
If you have a header, you can pass header=0
.
DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t', header=0)
You can probably just use the true
command:
if [ "$a" -ge 10 ]; then
true
elif [ "$a" -le 5 ]; then
echo "1"
else
echo "2"
fi
An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:
if [ "$a" -le 5 ]; then
echo "1"
elif [ "$a" -lt 10 ]; then
echo "2"
fi
With does not work embedded, but it does work consecutive
;WITH A AS(
...
),
B AS(
...
)
SELECT *
FROM A
UNION ALL
SELECT *
FROM B
EDIT Fixed the syntax...
Also, have a look at the following example
I wonder why no one have mentioned this simple pattern? :
(function(next) {
//do something
next()
}(function() {
//do some more
}))
Using timeouts just for blindly waiting is bad practice; and involving promises just adds more complexity to the code. In OP's case:
(function(next) {
for(i=0;i<x;i++){
// do something
if (i==x-1) next()
}
}(function() {
// now wait for firstFunction to finish...
// do something else
}))
a small demo -> http://jsfiddle.net/5jdeb93r/
If you application is a Windows GUI application then using the code below to do the waiting is not ideal as messages for your application will not be getting processing. To the user it will look like your application has hung.
WaitForSingleObject(&processInfo.hProcess, INFINITE)
Something like the untested code below might be better as it will keep processing the windows message queue and your application will remain responsive:
//-- wait for the process to finish
while (true)
{
//-- see if the task has terminated
DWORD dwExitCode = WaitForSingleObject(ProcessInfo.hProcess, 0);
if ( (dwExitCode == WAIT_FAILED )
|| (dwExitCode == WAIT_OBJECT_0 )
|| (dwExitCode == WAIT_ABANDONED) )
{
DWORD dwExitCode;
//-- get the process exit code
GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);
//-- the task has ended so close the handle
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
//-- save the exit code
lExitCode = dwExitCode;
return;
}
else
{
//-- see if there are any message that need to be processed
while (PeekMessage(&message.msg, 0, 0, 0, PM_NOREMOVE))
{
if (message.msg.message == WM_QUIT)
{
return;
}
//-- process the message queue
if (GetMessage(&message.msg, 0, 0, 0))
{
//-- process the message
TranslateMessage(&pMessage->msg);
DispatchMessage(&pMessage->msg);
}
}
}
}
I found good solution myself. Since slick slider is still used nowadays i'll post my approach.
@RuivBoas answer is partly correct. - It can change the width of the slide but it can break the slider. Why?
Slick slider may exceed browser width. Actual container width is set to value that can accomodate all it's slides.
The best solution for setting slide width is to use width of the actual browser window. It works best with responsive design.
For example 2 slides with absorbed width
CSS
.slick-slide {
width: 50vw;
// for absorbing width from @Ken Wheeler answer
box-sizing: border-box;
}
JS
$(document).on('ready', function () {
$("#container").slick({
variableWidth: true,
slidesToShow: 2,
slidesToScroll: 2
});
});
HTML markup
<div id="container">
<div><img/></div>
<div><img/></div>
<div><img/></div>
</div>
How about
SELECT *
FROM Employees
WHERE PhoneNumber IN (
SELECT PhoneNumber
FROM Employees
GROUP BY PhoneNumber
HAVING COUNT(Employee_ID) > 1
)
fwrite($handle, "<br>"."\r\n");
Add this under
$password = $_POST['password'].PHP_EOL;
this. .
Try switching to Logback and use
ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(Level.toLevel("info"));
I believe this will be the only call to Logback and the rest of your code will remain unchanged. Logback uses SLF4J and the migration will be painless, just the xml config files will have to be changed.
Remember to set the log level back after you're done.
Write as
<input type="submit" ng-click="profileForm.$valid==true?updateMyProfile():''" name="submit" value="Save" class="submit" id="submit">
DATE_ADD(FROM_DATE_HERE, INTERVAL INTERVAL_TIME_HERE DAY)
will give the Date after adjusting the INTERVAL
eg.
DATE_ADD(NOW(), INTERVAL -1 DAY) for deducting 1 DAY from current Day
DATE_ADD(NOW(), INTERVAL 2 DAY) for adding 2 Days
You can use like
UPDATE classes WHERE date=(DATE_ADD(date, INTERVAL 1 DAY)) WHERE id=161
This will work, and if you need where statement you can add it as parameter.
class GenericDAOWithJPA<T, ID extends Serializable> {
.......
public List<T> findAll() {
return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
}
}
If anyone is looking for a quick fix for this, here's how you do it.
while (array[i] != '\0') i++;
The variable i will hold the used length of the array, not the entire initialized array. I know it's a late post, but it may help someone.
Thanks @BIJAY_JHA and @Manaus. I used the Kotlin version to call my signIn() method that lives in the Activity and that I'm calling from a Fragment. I'm using Navigation Architecture in Android so the Listener interface pattern isn't in the Fragment:
(activity as MainActivity).signIn()
There is no need to add if{}else{} control flow. Initialise the button texts for different states at the View or ViewController constructor:
[btnCheckButton setTitle:@"Normal" forState:UIControlStateNormal]; [btnCheckButton setTitle:@"Selected" forState:UIControlStateSelected];
Then switch the button state to Selected:
[btnCheckButton setSelected:YES];
Then switch the button state to Normal:
[btnCheckButton setSelected:NO];
It is not very nice to use native php resources like $_GET
as Laravel gives us easy ways to get the variables. As a matter of standard, whenever possible use the resources of the laravel itself instead of pure PHP.
There is at least two modes to get variables by GET in Laravel ( Laravel 5.x or greater):
Mode 1
Route:
Route::get('computers={id}', 'ComputersController@index');
Request (POSTMAN or client...):
http://localhost/api/computers=500
Controler - You can access the {id}
paramter in the Controlller by:
public function index(Request $request, $id){
return $id;
}
Mode 2
Route:
Route::get('computers', 'ComputersController@index');
Request (POSTMAN or client...):
http://localhost/api/computers?id=500
Controler - You can access the ?id
paramter in the Controlller by:
public function index(Request $request){
return $request->input('id');
}
I will make a little bit wider answer here.
There are generally speaking two types of conditional jumps in x86:
Arithmetic jumps - like JZ (jump if zero), JC (jump if carry), JNC (jump if not carry), etc.
Comparison jumps - JE (jump if equal), JB (jump if below), JAE (jump if above or equal), etc.
So, use the first type only after arithmetic or logical instructions:
sub eax, ebx
jnz .result_is_not_zero
and ecx, edx
jz .the_bit_is_not_set
Use the second group only after CMP instructions:
cmp eax, ebx
jne .eax_is_not_equal_to_ebx
cmp ecx, edx
ja .ecx_is_above_than_edx
This way, the program becomes more readable and you will never be confused.
Note, that sometimes these instructions are actually synonyms. JZ == JE; JC == JB; JNC == JAE and so on. The full table is following. As you can see, there are only 16 conditional jump instructions, but 30 mnemonics - they are provided to allow creation of more readable source code:
Mnemonic Condition tested Description
jo OF = 1 overflow
jno OF = 0 not overflow
jc, jb, jnae CF = 1 carry / below / not above nor equal
jnc, jae, jnb CF = 0 not carry / above or equal / not below
je, jz ZF = 1 equal / zero
jne, jnz ZF = 0 not equal / not zero
jbe, jna CF or ZF = 1 below or equal / not above
ja, jnbe CF and ZF = 0 above / not below or equal
js SF = 1 sign
jns SF = 0 not sign
jp, jpe PF = 1 parity / parity even
jnp, jpo PF = 0 not parity / parity odd
jl, jnge SF xor OF = 1 less / not greater nor equal
jge, jnl SF xor OF = 0 greater or equal / not less
jle, jng (SF xor OF) or ZF = 1 less or equal / not greater
jg, jnle (SF xor OF) or ZF = 0 greater / not less nor equal
I was having the same problem. I tried a
npm config set registry http://registry.npmjs.org/
to turn off https. I also tried
npm set progress=false
to turn off the progress bar (it has been reported to slow down downloads).
The problem was with my network driver. I just needed to reboot and the lag went away.
None of these solutions worked for me. Instead, what worked was to go to a command line tool (or terminal in Mac), CD into the SDK/platform-tools directory, and then run this:
adb kill-server
then run this:
adb start-server
After I did this everything worked again. Why? Who knows.
On my MAC the path to the platform-tools folder was $HOME/Installations/adt-bundle-mac-x86_64-20130522/sdk/platform-tools It will probably be somewhere else on your machine.
I also found this page that presents some helpful steps:
http://android.okhelp.cz/android-emulator-wont-run-application-started-from-eclipse/
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if(pairs.getKey().equals("mango"))
{
map.put(pairs.getKey(), pairs.getValue().add(18));
}
else if(!map.containsKey("mango"))
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango",ints);
}
it.remove(); // avoids a ConcurrentModificationException
}
EDIT: So inside the while try this:
map.put(pairs.getKey(), pairs.getValue().add(number))
You are getting the error because you are trying to put an integer to the values, whereas it is expected an ArrayList
.
EDIT 2: Then put the following inside your while loop:
if(pairs.getKey().equals("mango"))
{
map.put(pairs.getKey(), pairs.getValue().add(18));
}
else if(!map.containsKey("mango"))
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango",ints);
}
EDIT 3:
By reading your requirements, I come to think you may not need a loop. You may want to only check if the map contains the key mango
, and if it does add 18
, else create a new entry in the map with key mango
and value 18
.
So all you may need is the following, without the loop:
if(map.containsKey("mango"))
{
map.put("mango", map.get("mango).add(18));
}
else
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango", ints);
}
Use the -ss
option:
ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
For JPEG output use -q:v
to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.
The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.
Placing -ss
before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg
cli tool documentation:
-ss
position (input/output)When used as an input option (before
-i
), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, soffmpeg
will seek to the closest seek point before position. When transcoding and-accurate_seek
is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when-noaccurate_seek
is used, it will be preserved.When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.
position may be either in seconds or in
hh:mm:ss[.xxx]
form.
Following up as of 2019-04-04, this seems to be able to be accomplished with the React Hooks' useState
:
import React, { useState } from 'react'
import uniqueId from 'lodash/utility/uniqueId'
const Field = props => {
const [ id ] = useState(uniqueId('myprefix-'))
return (
<div>
<label htmlFor={id}>{props.label}</label>
<input id={id} type="text"/>
</div>
)
}
export default Field
As I understand it, you ignore the second array item in the array destructuring that would allow you to update id
, and now you've got a value that won't be updated again for the life of the component.
The value of id
will be myprefix-<n>
where <n>
is an incremental integer value returned from uniqueId
. If that's not unique enough for you, consider making your own like
function gen4() {
return Math.random().toString(16).slice(-4)
}
function simpleUniqueId(prefix) {
return (prefix || '').concat([
gen4(),
gen4(),
gen4(),
gen4(),
gen4(),
gen4(),
gen4(),
gen4()
].join(''))
}
or check out the library I published with this here: https://github.com/rpearce/simple-uniqueid. There are also hundreds or thousands of other unique ID things out there, but lodash's uniqueId
with a prefix should be enough to get the job done.
Thanks to @Huong Hk for pointing me to hooks lazy initial state, the sum of which is that you can pass a function to useState
that will only be run on the initial mount.
// before
const [ id ] = useState(uniqueId('myprefix-'))
// after
const [ id ] = useState(() => uniqueId('myprefix-'))
example given below
protocol NameOfProtocol: class {
// member of protocol
}
class ClassName: UIViewController {
weak var delegate: NameOfProtocol?
}
You can use binary file of curl .download file from here : http://www.paehl.com/open_source/?CURL_7.22.0 Download the file and after extract put in to any drive and set the absolute path into environment now you can also use curl as a command in windows. like c:\curl -u [email protected]:password http://localhost:3000/user/sign_in
I have the script all.p
set ...
...
list=system('ls -1B *.dat')
plot for [file in list] file w l u 1:2 t file
Here the two last rows are literal, not heuristic. Then i run
$ gnuplot -p all.p
Change *.dat
to the file type you have, or add file types.
Next step: Add to ~/.bashrc this line
alias p='gnuplot -p ~/./all.p'
and put your file all.p
int your home directory and voila. You can plot all files in any directory by typing p and enter.
EDIT I changed the command, because it didn't work. Previously it contained list(i)=word(system(ls -1B *.dat),i)
.
When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. You want to source the script by doing:
. ./setfoo.sh
This executes it in the context of the current shell, not as a sub shell.
From the bash man page:
. filename [arguments]
source filename [arguments]Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.
If filename does not contain a slash, file names in PATH are used to find the directory containing filename.
The file searched for in PATH need not be executable. When bash is not in POSIX mode, the current directory is searched if no file is found in PATH.
If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched.
If any arguments are supplied, they become the positional parameters when filename is executed.
Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load
method of your Test.aspx.cs
file.
but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display.
That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.
You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391
Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js
You can convert a string to a date easily by:
CAST(YourDate AS DATE)
For me, I changed C:\apps\Java\jdk1.8_162\bin\javac.exe to C:\apps\Java\jdk1.8_162\bin\javacpl.exe Since there was no executable with that name in the bin folder. That worked.
There's no such thing as a global variable in C#. Period.
You can have static members if you want:
public static class MyStaticValues
{
public static bool MyStaticBool {get;set;}
}
That you are running Windows. Read:
http://en.wikipedia.org/wiki/Sudo
It basically allows you to execute an application with elevated privileges. If you want to achieve a similar effect under Windows, open an administrative prompt and execute your command from there. Under Vista, this is easily done by opening the shortcut while holding Ctrl+Shift at the same time.
That being said, it might very well be possible that your account already has sufficient privileges, depending on how your OS is setup, and the Windows version used.
You need to put the worksheet identifier in your range statements as shown below ...
Option Explicit
Dim ws As Worksheet, a As Range
Sub forEachWs()
For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next
End Sub
Sub resizingColumns()
ws.Range("A:A").ColumnWidth = 20.14
ws.Range("B:B").ColumnWidth = 9.71
ws.Range("C:C").ColumnWidth = 35.86
ws.Range("D:D").ColumnWidth = 30.57
ws.Range("E:E").ColumnWidth = 23.57
ws.Range("F:F").ColumnWidth = 21.43
ws.Range("G:G").ColumnWidth = 18.43
ws.Range("H:H").ColumnWidth = 23.86
ws.Range("i:I").ColumnWidth = 27.43
ws.Range("J:J").ColumnWidth = 36.71
ws.Range("K:K").ColumnWidth = 30.29
ws.Range("L:L").ColumnWidth = 31.14
ws.Range("M:M").ColumnWidth = 31
ws.Range("N:N").ColumnWidth = 41.14
ws.Range("O:O").ColumnWidth = 33.86
End Sub
When passing a struct to another function, it would usually be better to do as Donnell suggested above and pass it by reference instead.
A very good reason for this is that it makes things easier if you want to make changes that will be reflected when you return to the function that created the instance of it.
Here is an example of the simplest way to do this:
#include <stdio.h>
typedef struct student {
int age;
} student;
void addStudent(student *s) {
/* Here we can use the arrow operator (->) to dereference
the pointer and access any of it's members: */
s->age = 10;
}
int main(void) {
student aStudent = {0}; /* create an instance of the student struct */
addStudent(&aStudent); /* pass a pointer to the instance */
printf("%d", aStudent.age);
return 0;
}
In this example, the argument for the addStudent()
function is a pointer to an instance of a student
struct - student *s
. In main()
, we create an instance of the student
struct and then pass a reference to it to our addStudent()
function using the reference operator (&
).
In the addStudent()
function we can make use of the arrow operator (->
) to dereference the pointer, and access any of it's members (functionally equivalent to: (*s).age
).
Any changes that we make in the addStudent()
function will be reflected when we return to main()
, because the pointer gave us a reference to where in the memory the instance of the student
struct is being stored. This is illustrated by the printf()
, which will output "10" in this example.
Had you not passed a reference, you would actually be working with a copy of the struct you passed in to the function, meaning that any changes would not be reflected when you return to main
- unless you implemented a way of passing the new version of the struct back to main or something along those lines!
Although pointers may seem off-putting at first, once you get your head around how they work and why they are so handy they become second nature, and you wonder how you ever coped without them!
Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
});
Different approach for creating columns string
create table #temp
(
date datetime,
category varchar(3),
amount money
)
insert into #temp values ('1/1/2012', 'ABC', 1000.00)
insert into #temp values ('2/1/2012', 'DEF', 500.00)
insert into #temp values ('2/1/2012', 'GHI', 800.00)
insert into #temp values ('2/10/2012', 'DEF', 700.00)
insert into #temp values ('3/1/2012', 'ABC', 1100.00)
DECLARE @cols AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';
SELECT @cols = @cols + QUOTENAME(category) + ',' FROM (select distinct category from #temp ) as tmp
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end
set @query =
'SELECT * from
(
select date, amount, category from #temp
) src
pivot
(
max(amount) for category in (' + @cols + ')
) piv'
execute(@query)
drop table #temp
Result
date ABC DEF GHI
2012-01-01 00:00:00.000 1000.00 NULL NULL
2012-02-01 00:00:00.000 NULL 500.00 800.00
2012-02-10 00:00:00.000 NULL 700.00 NULL
2012-03-01 00:00:00.000 1100.00 NULL NULL
There are many things that idea solves in a much simpler way, or there's no equivalent:
Autocomplete actions: Doing ctrl+shift+a you can call any idea action from the keyboard without remembering its key combination... Think about gnome-do or launchy in windows, and you've got the idea! Also, this feature supports CamelCasing abbreviations ;)
Shelf: Lets you keep easily some pieces of code apart, and then review them through the diff viewer.
Local history: It's far better managed, and simpler.
SVN annotations and history: simpler to inspect, and also you can easily see the history only for such a part of a whole source file.
Autocomplete everywhere, such as the evaluate expression and breakpoint condition windows.
Maven integration... much, much simpler, and well integrated.
Refactors much closer to the hand, such as loops insertion, wrapping/casting, renaming, and add variables.
Find much powerful and well organized. Even in big projects
Much stable to work with several branches of a big project at the same time (as a former bugfixer of 1.5Gb by branch sources, and the need to working in them simultaneously, idea shown its rock-solid capabilities)
Cleaner and simpler interface...
And, simpler to use only with the keyboard, letting apart the need of using the mouse for lots of simple taks, saving you time and giving you more focus on the code... where it matters!
And now, being opensource... the Idea user base will grow exponentially.
Actions at=new Actions(wd);
at.moveToElement(we);
at.contextClick(we).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
This approach using git-remote
worked well for me for HTTPS remotes:
$ git remote -v | grep "(fetch)" | sed 's/.*\/\([^ ]*\)\/.*/\1/'
| | | |
| | | +---------------+
| | | Extract capture |
| +--------------------+-----+
|Repository name capture|
+-----------------------+
Example
You can set it as a no title bar theme in the activity's xml in the AndroidManifest
<activity
android:name=".AnActivity"
android:label="@string/a_string"
android:theme="@android:style/Theme.NoTitleBar">
</activity>
As stated by the other answers, "%03d" % number
works pretty well, but it goes against the rubocop ruby style guide:
Favor the use of sprintf and its alias format over the fairly cryptic String#% method
We can obtain the same result in a more readable way using the following:
format('%03d', number)
I need to do the same thing. I ended up with something similar to Kman
static void ExcelToCSVCoversion(string sourceFile, string targetFile)
{
Application rawData = new Application();
try
{
Workbook workbook = rawData.Workbooks.Open(sourceFile);
Worksheet ws = (Worksheet) workbook.Sheets[1];
ws.SaveAs(targetFile, XlFileFormat.xlCSV);
Marshal.ReleaseComObject(ws);
}
finally
{
rawData.DisplayAlerts = false;
rawData.Quit();
Marshal.ReleaseComObject(rawData);
}
Console.WriteLine();
Console.WriteLine($"The excel file {sourceFile} has been converted into {targetFile} (CSV format).");
Console.WriteLine();
}
If there are multiple sheets this is lost in the conversion but you could loop over the number of sheets and save each one as csv.
You can!!! In short use this as the connection string:
ldap://<host>:3268/DC=<my>,DC=<domain>?cn
together with your search filter, e.g.
(&(sAMAccountName={0})(&((objectCategory=person)(objectclass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=<some-special-nested-group>,OU=<ou3>,OU=<ou2>,OU=<ou1>,DC=<dc3>,DC=<dc2>,DC=<dc1>))))
That will search in the so called Global Catalog, that had been available out-of-the-box in our environment.
Instead of the known/common other versions (or combinations thereof) that did NOT work in our environment with multiple OUs:
ldap://<host>/DC=<my>,DC=<domain>
ldap://<host>:389/DC=<my>,DC=<domain> (standard port)
ldap://<host>/OU=<someOU>,DC=<my>,DC=<domain>
ldap://<host>/CN=<someCN>,DC=<my>,DC=<domain>
ldap://<host>/(|(OU=<someOU1>)(OU=<someOU2>)),DC=<my>,DC=<domain> (search filters here shouldn't work at all by definition)
(I am a developer, not an AD/LDAP guru:) Damn I had been searching for this solution everywhere for almost 2 days and almost gave up, getting used to the thought I might have to implement this obviously very common scenario by hand (with Jasperserver/Spring security(/Tomcat)). (So this shall be a reminder if somebody else or me should have this problem again in the future :O) )
Here some other related threads I found during my research that had been mostly of little help:
And here I will provide our anonymized Tomcat LDAP config in case it may be helpful
(/var/lib/tomcat7/webapps/jasperserver/WEB-INF/applicationContext-externalAUTH-LDAP.xml
):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- ############ LDAP authentication ############ - Sample configuration
of external authentication via an external LDAP server. -->
<bean id="proxyAuthenticationProcessingFilter"
class="com.jaspersoft.jasperserver.api.security.externalAuth.BaseAuthenticationProcessingFilter">
<property name="authenticationManager">
<ref local="ldapAuthenticationManager" />
</property>
<property name="externalDataSynchronizer">
<ref local="externalDataSynchronizer" />
</property>
<property name="sessionRegistry">
<ref bean="sessionRegistry" />
</property>
<property name="internalAuthenticationFailureUrl" value="/login.html?error=1" />
<property name="defaultTargetUrl" value="/loginsuccess.html" />
<property name="invalidateSessionOnSuccessfulAuthentication"
value="true" />
<property name="migrateInvalidatedSessionAttributes" value="true" />
</bean>
<bean id="proxyAuthenticationSoapProcessingFilter"
class="com.jaspersoft.jasperserver.api.security.externalAuth.DefaultAuthenticationSoapProcessingFilter">
<property name="authenticationManager" ref="ldapAuthenticationManager" />
<property name="externalDataSynchronizer" ref="externalDataSynchronizer" />
<property name="invalidateSessionOnSuccessfulAuthentication"
value="true" />
<property name="migrateInvalidatedSessionAttributes" value="true" />
<property name="filterProcessesUrl" value="/services" />
</bean>
<bean id="proxyRequestParameterAuthenticationFilter"
class="com.jaspersoft.jasperserver.war.util.ExternalRequestParameterAuthenticationFilter">
<property name="authenticationManager">
<ref local="ldapAuthenticationManager" />
</property>
<property name="externalDataSynchronizer" ref="externalDataSynchronizer" />
<property name="authenticationFailureUrl">
<value>/login.html?error=1</value>
</property>
<property name="excludeUrls">
<list>
<value>/j_spring_switch_user</value>
</list>
</property>
</bean>
<bean id="proxyBasicProcessingFilter"
class="com.jaspersoft.jasperserver.api.security.externalAuth.ExternalAuthBasicProcessingFilter">
<property name="authenticationManager" ref="ldapAuthenticationManager" />
<property name="externalDataSynchronizer" ref="externalDataSynchronizer" />
<property name="authenticationEntryPoint">
<ref local="basicProcessingFilterEntryPoint" />
</property>
</bean>
<bean id="proxyAuthenticationRestProcessingFilter"
class="com.jaspersoft.jasperserver.api.security.externalAuth.DefaultAuthenticationRestProcessingFilter">
<property name="authenticationManager">
<ref local="ldapAuthenticationManager" />
</property>
<property name="externalDataSynchronizer">
<ref local="externalDataSynchronizer" />
</property>
<property name="filterProcessesUrl" value="/rest/login" />
<property name="invalidateSessionOnSuccessfulAuthentication"
value="true" />
<property name="migrateInvalidatedSessionAttributes" value="true" />
</bean>
<bean id="ldapAuthenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<list>
<ref local="ldapAuthenticationProvider" />
<ref bean="${bean.daoAuthenticationProvider}" />
<!--anonymousAuthenticationProvider only needed if filterInvocationInterceptor.alwaysReauthenticate
is set to true <ref bean="anonymousAuthenticationProvider"/> -->
</list>
</property>
</bean>
<bean id="ldapAuthenticationProvider"
class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
<constructor-arg>
<bean
class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
<constructor-arg>
<ref local="ldapContextSource" />
</constructor-arg>
<property name="userSearch" ref="userSearch" />
</bean>
</constructor-arg>
<constructor-arg>
<bean
class="org.springframework.security.ldap.populator.DefaultLdapAuthoritiesPopulator">
<constructor-arg index="0">
<ref local="ldapContextSource" />
</constructor-arg>
<constructor-arg index="1">
<value></value>
</constructor-arg>
<property name="groupRoleAttribute" value="cn" />
<property name="convertToUpperCase" value="true" />
<property name="rolePrefix" value="ROLE_" />
<property name="groupSearchFilter"
value="(&(member={0})(&(objectCategory=Group)(objectclass=group)(cn=my-nested-group-name)))" />
<property name="searchSubtree" value="true" />
<!-- Can setup additional external default roles here <property name="defaultRole"
value="LDAP"/> -->
</bean>
</constructor-arg>
</bean>
<bean id="userSearch"
class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
<constructor-arg index="0">
<value></value>
</constructor-arg>
<constructor-arg index="1">
<value>(&(sAMAccountName={0})(&((objectCategory=person)(objectclass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=my-nested-group-name,OU=ou3,OU=ou2,OU=ou1,DC=dc3,DC=dc2,DC=dc1))))
</value>
</constructor-arg>
<constructor-arg index="2">
<ref local="ldapContextSource" />
</constructor-arg>
<property name="searchSubtree">
<value>true</value>
</property>
</bean>
<bean id="ldapContextSource"
class="com.jaspersoft.jasperserver.api.security.externalAuth.ldap.JSLdapContextSource">
<constructor-arg value="ldap://myhost:3268/DC=dc3,DC=dc2,DC=dc1?cn" />
<!-- manager user name and password (may not be needed) -->
<property name="userDn" value="CN=someuser,OU=ou4,OU=1,DC=dc3,DC=dc2,DC=dc1" />
<property name="password" value="somepass" />
<!--End Changes -->
</bean>
<!-- ############ LDAP authentication ############ -->
<!-- ############ JRS Synchronizer ############ -->
<bean id="externalDataSynchronizer"
class="com.jaspersoft.jasperserver.api.security.externalAuth.ExternalDataSynchronizerImpl">
<property name="externalUserProcessors">
<list>
<ref local="externalUserSetupProcessor" />
<!-- Example processor for creating user folder -->
<!--<ref local="externalUserFolderProcessor"/> -->
</list>
</property>
</bean>
<bean id="abstractExternalProcessor"
class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.AbstractExternalUserProcessor"
abstract="true">
<property name="repositoryService" ref="${bean.repositoryService}" />
<property name="userAuthorityService" ref="${bean.userAuthorityService}" />
<property name="tenantService" ref="${bean.tenantService}" />
<property name="profileAttributeService" ref="profileAttributeService" />
<property name="objectPermissionService" ref="objectPermissionService" />
</bean>
<bean id="externalUserSetupProcessor"
class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserSetupProcessor"
parent="abstractExternalProcessor">
<property name="userAuthorityService">
<ref bean="${bean.internalUserAuthorityService}" />
</property>
<property name="defaultInternalRoles">
<list>
<value>ROLE_USER</value>
</list>
</property>
<property name="organizationRoleMap">
<map>
<!-- Example of mapping customer roles to JRS roles -->
<entry>
<key>
<value>ROLE_MY-NESTED-GROUP-NAME</value>
</key>
<!-- JRS role that the <key> external role is mapped to -->
<value>ROLE_USER</value>
</entry>
</map>
</property>
</bean>
<!--bean id="externalUserFolderProcessor" class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserFolderProcessor"
parent="abstractExternalProcessor"> <property name="repositoryService" ref="${bean.unsecureRepositoryService}"/>
</bean -->
<!-- ############ JRS Synchronizer ############ -->
1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory
Here is the program with all the changes needed. I compiled and ran... no errors or warnings.
#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h> //sine
#include <string.h>
#define TIME 255
#define HARM 32
int main (void) {
double sineRads;
double sine;
int tcount = 0;
int hcount = 0;
/* allocate some heap memory for the large array of waveform data */
double *ptr = malloc(sizeof(double) * TIME);
//memset( ptr, 0x00, sizeof(double) * TIME); may not always set double to 0
for( tcount = 0; tcount < TIME; tcount++ )
{
ptr[tcount] = 0;
}
tcount = 0;
if (NULL == ptr) {
printf("ERROR: couldn't allocate waveform memory!\n");
} else {
/*evaluate and add harmonic amplitudes for each time step */
for(tcount = 0; tcount < TIME; tcount++){
for(hcount = 0; hcount <= HARM; hcount++){
sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
sineRads *= (hcount + 1); //scale frequency by harmonic number
sine = sin(sineRads);
ptr[tcount] += sine; //add to other results for this time step
}
}
free(ptr);
ptr = NULL;
}
return 0;
}
I think you are talking about class level variables. As mentioned above using global variable/class level variables are not a good practice.
If you really want to use it. and if you are sure that there will not be impact...
Declare any variable out side the method. at the class level with out the variable type
eg:
{
method()
{
a=10
print(a)
}
// def a or int a wont work
a=0
}
To handle the situation in which there is no wiring, beans are available with @Autowired
required
attribute set to false
.
But when using @Inject
, the Provider interface works with the bean which means that the bean is not injected directly but with the Provider.
If you don't wish to use interop, you may want to try out OfficeWriter. Depending on how much processing you really need to do on the file, it might be overkill though. You can request a free trial. There's a fully documented api available at the documentation site.
DISCLAIMER: I'm one of the engineers who built the latest version.
Please double check that jenkins is not blocking this import. Go to script approvals and check to see if it is blocking it. If it is click allow.
public boolean compareMap(Map<String, String> map1, Map<String, String> map2) {
if (map1 == null || map2 == null)
return false;
for (String ch1 : map1.keySet()) {
if (!map1.get(ch1).equalsIgnoreCase(map2.get(ch1)))
return false;
}
for (String ch2 : map2.keySet()) {
if (!map2.get(ch2).equalsIgnoreCase(map1.get(ch2)))
return false;
}
return true;
}
RollingFileAppender
does this. You just need to set maxBackupIndex
to the highest value for the backup file.
It is very simple;
def median(alist):
#to find median you will have to sort the list first
sList = sorted(alist)
first = 0
last = len(sList)-1
midpoint = (first + last)//2
return midpoint
And you can use the return value like this median = median(anyList)
Try disabling Just My Code (JMC).
By default the debugger tries to restrict the view of the world to code that is only contained within your solution. This is really heplful at times but when you want to debug code which is not in your solution (as is your situation) you need to disable JMC in order to see it. Otherwise the code will be treated as external and largely hidden from your view.
EDIT
When you're broken in your code try the following.
Here is a pretty short version
function getCookie(n) {
let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
return a ? a[1] : '';
}
Note that I made use of ES6's template strings to compose the regex expression.
If you are using a php script to get the answer from the remote server, add this line at the begining:
header("Access-Control-Allow-Origin: *");
If you'r using LINUX, first let's check apache's user, since in some distros it can be different:
egrep -i '^user|^group' /etc/httpd/conf/httpd.conf
Let's say the result is "http". Do the folowwing, just remember change path_to_folder to folders path:
chown -R http:http path_to_folder
chmod -R g+rw path_to_folder
To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).
I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1¶m2=val2
) or JSON (parsed by your API upon receipt)
Threading's job is to enable applications to be responsive. Suppose you have a database connection and you need to respond to user input. Without threading, if the database connection is busy the application will not be able to respond to the user. By splitting off the database connection into a separate thread you can make the application more responsive. Also because both threads are in the same process, they can access the same data structures - good performance, plus a flexible software design.
Note that due to the GIL the app isn't actually doing two things at once, but what we've done is put the resource lock on the database into a separate thread so that CPU time can be switched between it and the user interaction. CPU time gets rationed out between the threads.
Multiprocessing is for times when you really do want more than one thing to be done at any given time. Suppose your application needs to connect to 6 databases and perform a complex matrix transformation on each dataset. Putting each job in a separate thread might help a little because when one connection is idle another one could get some CPU time, but the processing would not be done in parallel because the GIL means that you're only ever using the resources of one CPU. By putting each job in a Multiprocessing process, each can run on it's own CPU and run at full efficiency.
You need to do something with the return value...
import java.util.Arrays;
public class trial1{
public static void main(String[] args){
int[] B = numbers();
System.out.println(Arrays.toString(B));
}
public static int[] numbers(){
int[] A = {1,2,3};
return A;
}
}
1) Open your terminal and type
npm install -g http-server
2) Go to the root folder that you want to serve you files and type:
http-server ./
3)
Read the output of the terminal, something kinda http://localhost:8080
will appear.
Everything on there will be allowed to be got. Example:
background: url('http://localhost:8080/waw.png')
;
c.getCount()
returns 1
because the cursor contains a single row (the one with the real COUNT(*)
). The count you need is the int
value of first row in cursor.
public int getTaskCount(long tasklist_Id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery(
"SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) }
);
int count = 0;
if(null != cursor)
if(cursor.getCount() > 0){
cursor.moveToFirst();
count = cursor.getInt(0);
}
cursor.close();
}
db.close();
return count;
}
Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.
There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request
in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:
import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text)
some_elements = soup.find_all("div", class_="myCssClass")
Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.
When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:
from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)
I would advice to start your own solution. You'll understand Scrapy's benefits doing so.
ps: take a look at scrapely: https://github.com/scrapy/scrapely
pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia
Yes, $_SERVER["HTTP_X_FORWARDED_FOR"]
is how I see my ip when under a proxy on my nginx server.
But your best bet is to run phpinfo()
on a page requested from under a proxy so you can look at all the availabe variables and see what is the one that carries your real ip.
The ErrorDocument
directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot
. In your case, this means that the actual path to the ErrorDocument
is
ErrorDocument 404 /hellothere/error/404page.html
An API key is a unique value that is assigned to a user of this service when he's accepted as a user of the service.
The service maintains all the issued keys and checks them at each request.
By looking at the supplied key at the request, a service checks whether it is a valid key to decide on whether to grant access to a user or not.
On the version posted by sunshinekitty called "Version < 3.0" , you may need to specify apscheduler 2.1.2 . I accidentally had version 3 on my 2.7 install, so I went:
pip uninstall apscheduler
pip install apscheduler==2.1.2
It worked correctly after that. Hope that helps.
Use the FROM_UNIXTIME()
function in MySQL
Remember that if you are using a framework that stores it in milliseconds (for example Java's timestamp) you have to divide by 1000 to obtain the right Unix time in seconds.
The location to set the memory heap size (at least in spark-1.0.0) is in conf/spark-env.
The relevant variables are SPARK_EXECUTOR_MEMORY
& SPARK_DRIVER_MEMORY
.
More docs are in the deployment guide
Also, don't forget to copy the configuration file to all the slave nodes.
first need to get actual constrain name by this query
SHOW CREATE TABLE TABLE_NAME
This query will result constrain name of the foreign key, now below query will drop it.
ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1
last number in above constrain name depends how many foreign keys you have in table
If we have parameter like below in our POM XML
<version>${project.version}.${svn.version}</version>
<packaging>war</packaging>
I run maven command line as follows :
mvn clean install package -Dproject.version=10 -Dsvn.version=1
You need to write it like sprintf(aa, "%9.7lf", a)
Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.
This code will remove the indentation and list bullets.
ul {
padding: 0;
list-style-type: none;
}
Just use
from IPython.display import Image
Image('image.png')
If you are using eclipse, you can follow the steps here (maven in 5 min not working) for getting your proxy information. Once done follow the steps below:
C:\apache-maven-3.1.0\conf\
settings.xml
to C:\Users\[UserFolder]\.m2
Modify the proxy in settings.xml
based on the info that you get from the above link.
<proxy> <active>true</active> <protocol>http</protocol> <host>your proxy</host> <port>your port</port> </proxy>
Open eclipse
Go to: Windows > Preferences > Maven > User Settings
Browse the settings.xml
from .m2
folder
Click Update Settings
Click Reindex
Apply the changes and Click OK
You can now try to create Maven Project in Eclipse
You can use .bind()
or .live()
whichever is appropriate, but no need to name the function:
$('#target').bind('click hover', function () {
// common operation
});
or if you were doing this on lots of element (not much sense for an IE unless the element changes):
$('#target').live('click hover', function () {
// common operation
});
Note, this will only bind the first hover argument, the mouseover
event, it won't hook anything to the mouseleave
event.
There are two ways to do this. One is to use form validation to never let any number over 50 be entered by a user. Form validation docs.
If there is no user involved in the process, or you're not using a form to enter data, then you'll have to override the model's save
method to throw an exception or limit the data going into the field.
Edit: Although the return type has changed in new versions of HTML (see Tim Down's updated answer), the code below still works.
As others have said, it's a NodeList. Here's a complete, working example you can try:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function findTheOddOnes()
{
var theOddOnes = document.getElementsByClassName("odd");
for(var i=0; i<theOddOnes.length; i++)
{
alert(theOddOnes[i].innerHTML);
}
}
</script>
</head>
<body>
<h1>getElementsByClassName Test</h1>
<p class="odd">This is an odd para.</p>
<p>This is an even para.</p>
<p class="odd">This one is also odd.</p>
<p>This one is not odd.</p>
<form>
<input type="button" value="Find the odd ones..." onclick="findTheOddOnes()">
</form>
</body>
</html>
This works in IE 9, FF 5, Safari 5, and Chrome 12 on Win 7.
There is also -l:libstatic1.a
(minus l colon) variant of -l option in gcc which can be used to link static library (Thanks to https://stackoverflow.com/a/20728782). Is it documented? Not in the official documentation of gcc (which is not exact for shared libs too): https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html
-llibrary -l library
Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.) ... The only difference between using an -l option and specifying a file name is that -l surrounds library with ‘lib’ and ‘.a’ and searches several directories.
The binutils ld doc describes it. The -lname
option will do search for libname.so
then for libname.a
adding lib prefix and .so
(if enabled at the moment) or .a
suffix. But -l:name
option will only search exactly for the name specified:
https://sourceware.org/binutils/docs/ld/Options.html
-l namespec --library=namespec
Add the archive or object file specified by
namespec
to the list of files to link. This option may be used any number of times. Ifnamespec
is of the form:filename
, ld will search the library path for a file calledfilename
, otherwise it will search the library path for a file calledlibnamespec.a
.On systems which support shared libraries, ld may also search for files other than
libnamespec.a
. Specifically, on ELF and SunOS systems, ld will search a directory for a library calledlibnamespec.so
before searching for one calledlibnamespec.a
. (By convention, a.so
extension indicates a shared library.) Note that this behavior does not apply to:filename
, which always specifies a file calledfilename
.The linker will search an archive only once, at the location where it is specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive. However, an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again.
See the
-(
option for a way to force the linker to search archives multiple times.You may list the same archive multiple times on the command line.
This type of archive searching is standard for Unix linkers. However, if you are using ld on AIX, note that it is different from the behaviour of the AIX linker.
The variant -l:namespec
is documented since 2.18 version of binutils (2007): https://sourceware.org/binutils/docs-2.18/ld/Options.html
public class AsOfdates
{
public string DisplayDate { get; set; }
private DateTime TheDate;
public DateTime DateValue
{
get
{
return TheDate.Date;
}
set
{
TheDate = value;
}
}
}
This solution is compatible with Android (I've tested and used it myself). Thanks to @user467257 whose solution I adapted this from.
import android.util.Base64;
public class StringXORer {
public String encode(String s, String key) {
return new String(Base64.encode(xorWithKey(s.getBytes(), key.getBytes()), Base64.DEFAULT));
}
public String decode(String s, String key) {
return new String(xorWithKey(base64Decode(s), key.getBytes()));
}
private byte[] xorWithKey(byte[] a, byte[] key) {
byte[] out = new byte[a.length];
for (int i = 0; i < a.length; i++) {
out[i] = (byte) (a[i] ^ key[i%key.length]);
}
return out;
}
private byte[] base64Decode(String s) {
return Base64.decode(s,Base64.DEFAULT);
}
private String base64Encode(byte[] bytes) {
return new String(Base64.encode(bytes,Base64.DEFAULT));
}
}
try,
str_list = " ".join([str(ele) for ele in numlist])
this statement will give you each element of your list in string
format
print("The list now looks like [{0}]".format(str_list))
and,
change print(numlist.pop(2)+" has been removed")
to
print("{0} has been removed".format(numlist.pop(2)))
as well.
It's not a good idea to use hbm2ddl.auto
in production.
The only way to manage the database schema is to use incremental migration scripts because:
Even the Hibernate User Guide advise you to avoid using the hbm2ddl
tool for production environments.
Apart from the recursive traversal one can use a Visitor based approach as well.
Below code is uses Visitor based approach for the traversal.It is expected that the input to the program is the root directory to traverse.
public interface Visitor {
void visit(DirElement d);
void visit(FileElement f);
}
public abstract class Element {
protected File rootPath;
abstract void accept(Visitor v);
@Override
public String toString() {
return rootPath.getAbsolutePath();
}
}
public class FileElement extends Element {
FileElement(final String path) {
rootPath = new File(path);
}
@Override
void accept(final Visitor v) {
v.visit(this);
}
}
public class DirElement extends Element implements Iterable<Element> {
private final List<Element> elemList;
DirElement(final String path) {
elemList = new ArrayList<Element>();
rootPath = new File(path);
for (File f : rootPath.listFiles()) {
if (f.isDirectory()) {
elemList.add(new DirElement(f.getAbsolutePath()));
} else if (f.isFile()) {
elemList.add(new FileElement(f.getAbsolutePath()));
}
}
}
@Override
void accept(final Visitor v) {
v.visit(this);
}
public Iterator<Element> iterator() {
return elemList.iterator();
}
}
public class ElementWalker {
private final String rootDir;
ElementWalker(final String dir) {
rootDir = dir;
}
private void traverse() {
Element d = new DirElement(rootDir);
d.accept(new Walker());
}
public static void main(final String[] args) {
ElementWalker t = new ElementWalker("C:\\temp");
t.traverse();
}
private class Walker implements Visitor {
public void visit(final DirElement d) {
System.out.println(d);
for(Element e:d) {
e.accept(this);
}
}
public void visit(final FileElement f) {
System.out.println(f);
}
}
}
No. Either use readFile
or readFileSync
(The latter only at startup time).
Or use an existing library like
Alternatively write your config in a js file rather then a json file like
module.exports = {
// json
}
Use a document.ready()
event around your call.
$(document).ready(function () {
$('#memberModal').modal('show');
});
jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/
It is worth saying that the figure used for this setting is in BYTES - found that out the hard way!
I have used FileSaver.js
to save the blob as file.
This is the repo : https://github.com/eligrey/FileSaver.js/
Usage:
import { saveAs } from 'file-saver';
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
saveAs("https://httpbin.org/image", "image.jpg");
I know you already have several answers, but I was on a similar situation where my team didn't want to depend on a heavy libraries or anything related to bootstrap since we are using material so I made our own autocomplete control, using material-like styles, you can use my autocomplete or at least you can give a look to give you some guiadance, there was not much documentation on simple examples on how to upload your components to be shared on NPM.
Depends on what you want to do. If you want to use the two arguments as input files, you can just pass them in and then use <>
to read their contents.
If they have a different meaning, you can use GetOpt::Std
and GetOpt::Long
to process them easily. GetOpt::Std
supports only single-character switches and GetOpt::Long
is much more flexible. From GetOpt::Long
:
use Getopt::Long;
my $data = "file.dat";
my $length = 24;
my $verbose;
$result = GetOptions ("length=i" => \$length, # numeric
"file=s" => \$data, # string
"verbose" => \$verbose); # flag
Alternatively, @ARGV
is a special variable that contains all the command line arguments. $ARGV[0]
is the first (ie. "string1"
in your case) and $ARGV[1]
is the second argument. You don't need a special module to access @ARGV
.
To disable number of lines that was previously assigned in theme use xml attribute: android:lines="@null"
Another option is Visual Studio, which has prerelease support for debugging Cordova apps:
Unified debugging experience. Cross-platform development often requires a different tool for debugging each device, emulator, or simulator. Different tools mean different workflows and lost productivity every time you switch devices. With Visual Studio, you can use the same world-class debugging tools for all deployment targets, including Windows, the Android emulator, attached Android devices, iOS devices and emulators, and the Apache Ripple emulator.
Now that Microsoft has released Visual Studio Community edition for free, you can give this a try at no cost. You will need to download both Visual Studio, and Visual Studio Tools for Apache Cordova.
Yes of course, there is nothing special with floats. You can use the format strings as you use in printf() for floats and anyother datatypes.
EDIT I tried this sample code:
float x = 0.61;
char buf[10];
sprintf(buf, "Test=%.2f", x);
printf(buf);
Output was : Test=0.61
In addition to the CAST
and CONVERT
functions in the previous answers, if you are using SQL Server 2012 and above you use the FORMAT function to convert a DATETIME
based type to a string.
To convert back, use the opposite PARSE
or TRYPARSE
functions.
The formatting styles are based on .NET (similar to the string formatting options of the ToString() method) and has the advantage of being culture aware. eg.
DECLARE @DateTime DATETIME2 = SYSDATETIME();
DECLARE @StringResult1 NVARCHAR(100) = FORMAT(@DateTime, 'g') --without culture
DECLARE @StringResult2 NVARCHAR(100) = FORMAT(@DateTime, 'g', 'en-gb')
SELECT @DateTime
SELECT @StringResult1, @StringResult2
SELECT PARSE(@StringResult1 AS DATETIME2)
SELECT PARSE(@StringResult2 AS DATETIME2 USING 'en-gb')
Results:
2015-06-17 06:20:09.1320951
6/17/2015 6:20 AM
17/06/2015 06:20
2015-06-17 06:20:00.0000000
2015-06-17 06:20:00.0000000
Could you use a Dictionary<TKey1,Dictionary<TKey2,TValue>>
?
You could even subclass this:
public class DualKeyDictionary<TKey1,TKey2,TValue> : Dictionary<TKey1,Dictionary<TKey2,TValue>>
EDIT: This is now a duplicate answer. It also is limited in its practicality. While it does "work" and provide ability to code dict[key1][key2]
, there are lots of "workarounds" to get it to "just work".
HOWEVER: Just for kicks, one could implement Dictionary nonetheless, but at this point it gets a little verbose:
public class DualKeyDictionary<TKey1, TKey2, TValue> : Dictionary<TKey1, Dictionary<TKey2, TValue>> , IDictionary< object[], TValue >
{
#region IDictionary<object[],TValue> Members
void IDictionary<object[], TValue>.Add( object[] key, TValue value )
{
if ( key == null || key.Length != 2 )
throw new ArgumentException( "Invalid Key" );
TKey1 key1 = key[0] as TKey1;
TKey2 key2 = key[1] as TKey2;
if ( !ContainsKey( key1 ) )
Add( key1, new Dictionary<TKey2, TValue>() );
this[key1][key2] = value;
}
bool IDictionary<object[], TValue>.ContainsKey( object[] key )
{
if ( key == null || key.Length != 2 )
throw new ArgumentException( "Invalid Key" );
TKey1 key1 = key[0] as TKey1;
TKey2 key2 = key[1] as TKey2;
if ( !ContainsKey( key1 ) )
return false;
if ( !this[key1].ContainsKey( key2 ) )
return false;
return true;
}
Arrays (called list
in python) use the []
notation. {}
is for dict
(also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.
If you actually want an array (list), use:
array = []
array.append(valueToBeInserted)
You only need to do one thing. Run session_object.clear()
and then save the new object. This will clear the session (as aptly named) and remove the offending duplicate object from your session.
Why not simply
var item = $('.field-item');
for (var i = 0; i <= item.length; i++) {
if ($(item[i]).text() == 'someText') {
$(item[i]).addClass('thisClass');
//do some other stuff here
}
}
use Set Comprehensions {x for x in l2} or set(l2) to get set, then use List Comprehensions to get list
l2set = set(l2)
l3 = [x for x in l1 if x not in l2set]
benchmark test code:
import time
l1 = list(range(1000*10 * 3))
l2 = list(range(1000*10 * 2))
l2set = {x for x in l2}
tic = time.time()
l3 = [x for x in l1 if x not in l2set]
toc = time.time()
diffset = toc-tic
print(diffset)
tic = time.time()
l3 = [x for x in l1 if x not in l2]
toc = time.time()
difflist = toc-tic
print(difflist)
print("speedup %fx"%(difflist/diffset))
benchmark test result:
0.0015058517456054688
3.968189239501953
speedup 2635.179227x
While inserting multiple rows with a single INSERT
statement is generally faster, it leads to a more complicated and often unsafe code. Below I present the best practices when it comes to inserting multiple records in one go using PHP.
To insert multiple new rows into the database at the same time, one needs to follow the following 3 steps:
INSERT
statementUsing database transactions ensures that the data is saved in one piece and significantly improves performance.
PDO is the most common choice of database extension in PHP and inserting multiple records with PDO is quite simple.
$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
// Start transaction
$pdo->beginTransaction();
// Prepare statement
$stmt = $pdo->prepare('INSERT
INTO `pxlot` (realname,email,address,phone,status,regtime,ip)
VALUES (?,?,?,?,?,?,?)');
// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
// All seven parameters are passed into the execute() in a form of an array
$stmt->execute([$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
}
// Commit the data into the database
$pdo->commit();
The mysqli extension is a little bit more cumbersome to use but operates on very similar principles. The function names are different and take slightly different parameters.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'user', 'password', 'database');
$mysqli->set_charset('utf8mb4');
// Start transaction
$mysqli->begin_transaction();
// Prepare statement
$stmt = $mysqli->prepare('INSERT
INTO `pxlot` (realname,email,address,phone,status,regtime,ip)
VALUES (?,?,?,?,?,?,?)');
// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
// mysqli doesn't accept bind in execute yet, so we have to bind the data first
// The first argument is a list of letters denoting types of parameters. It's best to use 's' for all unless you need a specific type
// bind_param doesn't accept an array so we need to unpack it first using '...'
$stmt->bind_param('sssssss', ...[$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
$stmt->execute();
}
// Commit the data into the database
$mysqli->commit();
Both extensions offer the ability to use transactions. Executing prepared statement with transactions greatly improves performance, but it's still not as good as a single SQL query. However, the difference is so negligible that for the sake of conciseness and clean code it is perfectly acceptable to execute prepared statements multiple times. If you need a faster option to insert many records into the database at once, then chances are that PHP is not the right tool.
Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:
00 00 00 07
: four byte length prefix (7 bytes)73 73 68 2d 72 73 61
: "ssh-rsa"00 00 00 01
: four byte length prefix (1 byte)25
: RSA Exponent (e
): 2500 00 01 00
: four byte length prefix (256 bytes)RSA Modulus (n
):
7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46
dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9
cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32
70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60
1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1
90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d
3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0
e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb
d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b
ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d
e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8
76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1
fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f
5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b
60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
The closest validation of my theory i can find it from RFC 4253:
The "ssh-rsa" key format has the following specific encoding:
string "ssh-rsa" mpint e mpint n
Here the 'e' and 'n' parameters form the signature key blob.
But it doesn't explain the length prefixes.
Taking the random RSA PUBLIC KEY
i found (in the question), and decoding the base64 into hex:
30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a
63 02 03 01 00 01
From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:
A.1.1 RSA public key syntax
An RSA public key should be represented with the ASN.1 type
RSAPublicKey
:RSAPublicKey ::= SEQUENCE { modulus INTEGER, -- n publicExponent INTEGER -- e }
The fields of type RSAPublicKey have the following meanings:
- modulus is the RSA modulus n.
- publicExponent is the RSA public exponent e.
Using Microsoft's excellent (and the only real) ASN.1 documentation:
30 82 01 0a ;SEQUENCE (0x010A bytes: 266 bytes)
| 02 82 01 01 ;INTEGER (0x0101 bytes: 257 bytes)
| | 00 ;leading zero because high-bit, but number is positive
| | fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68
| | e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e
| | 11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d
| | dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80
| | fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94
| | 23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0
| | 9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3
| | 4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd
| | 41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e
| | 97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f
| | fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a
| | 63
| 02 03 ;INTEGER (3 bytes)
| 01 00 01
giving the public key modulus and exponent:
0xfb1199ff0733f6e805a4fd3b36ca68...837a63
If it's not work in your centos 7 machine "export CATALINA_OPTS="-Xms512M -Xmx1024M"" then you can change heap memory from vi /etc/systemd/system/tomcat.service file then this value shown in your tomcat by help of ps -ef|grep tomcat.
This worked for me in Bitbucket Cloud.
Entering this:
* item a
* item b
** item b1
** item b2
* item3
I've got this:
It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).
One way around this is to bind your event handler in javascript (where it should be):
document.getElementById('optionID').onchange = function () {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:
window.changeMessage() {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
?
I think I was trying something very similar to the original poster. the get() worked for me, although the name inside the chart was not inherited. Here is the code that worked for me.
#install it if you dont have it
library(quantmod)
# a list of stock tickers
myStocks <- c("INTC", "AAPL", "GOOG", "LTD")
# get some stock prices from default service
getSymbols(myStocks)
# to pause in between plots
par(ask=TRUE)
# plot all symbols
for (i in 1:length(myStocks)) {
chartSeries(get(myStocks[i]), subset="last 26 weeks")
}
@RequestParam
makes Spring to map request parameters from the GET/POST request to your method argument.
GET Request
http://testwebaddress.com/getInformation.do?city=Sydney&country=Australia
public String getCountryFactors(@RequestParam(value = "city") String city,
@RequestParam(value = "country") String country){ }
POST Request
@RequestBody
makes Spring to map entire request to a model class and from there you can retrieve or set values from its getter and setter methods. Check below.
http://testwebaddress.com/getInformation.do
You have JSON
data as such coming from the front end and hits your controller class
{
"city": "Sydney",
"country": "Australia"
}
Java
Code - backend (@RequestBody
)
public String getCountryFactors(@RequestBody Country countryFacts)
{
countryFacts.getCity();
countryFacts.getCountry();
}
public class Country {
private String city;
private String country;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Remove Windows Service via Registry
Its very easy to remove a service from registry if you know the right path. Here is how I did that:
Run Regedit or Regedt32
Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"
Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).
Delete Windows Service via Command Window
Alternatively, you can also use command prompt and delete a service using following command:
sc delete
You can also create service by using following command
sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"
Note: You may have to reboot the system to get the list updated in service manager.
Map:
Map transformation.
The map works on a single Row at a time.
Map returns after each input Row.
The map doesn’t hold the output result in Memory.
Map no way to figure out then to end the service.
// map example
val dfList = (1 to 100) toList
val df = dfList.toDF()
val dfInt = df.map(x => x.getInt(0)+2)
display(dfInt)
MapPartition:
MapPartition transformation.
MapPartition works on a partition at a time.
MapPartition returns after processing all the rows in the partition.
MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.
MapPartition service can be shut down before returning.
// MapPartition example
Val dfList = (1 to 100) toList
Val df = dfList.toDF()
Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))
Df1.collec()
//display(df1.collect())
For more details, please refer to the Spark map vs mapPartitions transformation article.
Hope this is helpful!
A simple way of using one instance of logging library in multiple modules for me was following solution:
import logging
logger = logging
logger.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
from base_logger import logger
if __name__ == '__main__':
logger.info("This is an info message")
Create a new custom object and add it to the object array that Import-Csv
creates.
$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow
You can use Object.values
in TypeScript by doing this (<any>Object).values(data)
if for some reason you can't update to ES7 in tsconfig.
A query of type MyEntity
is going to return MyEntity
. You want a query for a Long
.
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.
You cannot always make a branch or pull an existing branch and push back to it, because you are not registered as a collaborator for that specific project.
Forking is nothing more than a clone on the GitHub server side:
You keep a fork in sync with the original project by:
The rebase allows you to make sure your changes are straightforward (no merge conflict to handle), making your pulling request that more easy when you want the maintainer of the original project to include your patches in his project.
The goal is really to allow collaboration even though direct participation is not always possible.
The fact that you clone on the GitHub side means you have now two "central" repository ("central" as "visible from several collaborators).
If you can add them directly as collaborator for one project, you don't need to manage another one with a fork.
The merge experience would be about the same, but with an extra level of indirection (push first on the fork, then ask for a pull, with the risk of evolutions on the original repo making your fast-forward merges not fast-forward anymore).
That means the correct workflow is to git pull --rebase upstream
(rebase your work on top of new commits from upstream), and then git push --force origin
, in order to rewrite the history in such a way your own commits are always on top of the commits from the original (upstream) repo.
See also:
There's actually quite a bit of useful information added to debug allocations. This table is more complete:
http://www.nobugs.org/developer/win32/debug_crt_heap.html#table
Address Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments 0x00320FD8 -40 0x01090009 0x01090009 0x01090009 0x0109005A Win32 heap info 0x00320FDC -36 0x01090009 0x00180700 0x01090009 0x00180400 Win32 heap info 0x00320FE0 -32 0xBAADF00D 0x00320798 0xDDDDDDDD 0x00320448 Ptr to next CRT heap block (allocated earlier in time) 0x00320FE4 -28 0xBAADF00D 0x00000000 0xDDDDDDDD 0x00320448 Ptr to prev CRT heap block (allocated later in time) 0x00320FE8 -24 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Filename of malloc() call 0x00320FEC -20 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Line number of malloc() call 0x00320FF0 -16 0xBAADF00D 0x00000008 0xDDDDDDDD 0xFEEEFEEE Number of bytes to malloc() 0x00320FF4 -12 0xBAADF00D 0x00000001 0xDDDDDDDD 0xFEEEFEEE Type (0=Freed, 1=Normal, 2=CRT use, etc) 0x00320FF8 -8 0xBAADF00D 0x00000031 0xDDDDDDDD 0xFEEEFEEE Request #, increases from 0 0x00320FFC -4 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x00321000 +0 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321004 +4 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321008 +8 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x0032100C +12 0xBAADF00D 0xBAADF00D 0xDDDDDDDD 0xFEEEFEEE Win32 heap allocations are rounded up to 16 bytes 0x00321010 +16 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321014 +20 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321018 +24 0x00000010 0x00000010 0x00000010 0xFEEEFEEE Win32 heap bookkeeping 0x0032101C +28 0x00000000 0x00000000 0x00000000 0xFEEEFEEE Win32 heap bookkeeping 0x00321020 +32 0x00090051 0x00090051 0x00090051 0xFEEEFEEE Win32 heap bookkeeping 0x00321024 +36 0xFEEE0400 0xFEEE0400 0xFEEE0400 0xFEEEFEEE Win32 heap bookkeeping 0x00321028 +40 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping 0x0032102C +44 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping
It is an old post, but I came across this recently
Selecting a specific interval
As @aleroot already mentioned, by using
table.setRowSelectionInterval(index0, index1);
You can specify an interval, which should be selected.
Adding an interval to the existing selection
You can also keep the current selection, and simply add additional rows by using this here
table.getSelectionModel().addSelectionInterval(index0, index1);
This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.
As of v1.1.0-alpha1 (pre release package) the framework uses the VirtualPathProvider
to access files rather than touching the physical file system.
The updated transformer can be seen below:
public class StyleRelativePathTransform
: IBundleTransform
{
public void Process(BundleContext context, BundleResponse response)
{
Regex pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
response.Content = string.Empty;
// open each of the files
foreach (var file in response.Files)
{
using (var reader = new StreamReader(file.Open()))
{
var contents = reader.ReadToEnd();
// apply the RegEx to the file (to change relative paths)
var matches = pattern.Matches(contents);
if (matches.Count > 0)
{
var directoryPath = VirtualPathUtility.GetDirectory(file.VirtualPath);
foreach (Match match in matches)
{
// this is a path that is relative to the CSS file
var imageRelativePath = match.Groups[2].Value;
// get the image virtual path
var imageVirtualPath = VirtualPathUtility.Combine(directoryPath, imageRelativePath);
// convert the image virtual path to absolute
var quote = match.Groups[1].Value;
var replace = String.Format("url({0}{1}{0})", quote, VirtualPathUtility.ToAbsolute(imageVirtualPath));
contents = contents.Replace(match.Groups[0].Value, replace);
}
}
// copy the result into the response.
response.Content = String.Format("{0}\r\n{1}", response.Content, contents);
}
}
}
}
My try is combined solution.
string = string.replace(',', '.').replace(/[^\d\.]/g, "").replace(/\./, "x").replace(/\./g, "").replace(/x/, ".");
string = Math.round( parseFloat(string) * 100) / 100;
First line solution from here: regex replacing multiple periods in floating number . It replaces comma "," with dot "." ; Replaces first comma with x; Removes all dots and replaces x back to dot.
Second line cleans numbers after dot.
This can be achieved by three different approaches (see my blog article here for more details):
Elements
panel like below$x()
and $$()
in Console
panel, as shown in Lawrence's answerHere is how you search XPath in Elements
panel:
Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see documentation for more info.
In the command line at the bottom use the following:
$()
: Returns the first element that matches. Equivalent to document.querySelector()
or calls the $
function in the page, if it exists.
$$()
: Returns an array of DOM nodes that match. This is like for document.querySelectorAll()
, but returns an array instead of a NodeList
.
$x()
: Evaluates an XPath expression and returns an array of matching nodes.
html, body {_x000D_
font-family: Arial, Helvetica, sans-serif;_x000D_
}_x000D_
_x000D_
/* define a fixed width for the entire menu */_x000D_
.navigation {_x000D_
width: 150px;_x000D_
}_x000D_
_x000D_
/* reset our lists to remove bullet points and padding */_x000D_
.mainmenu, .submenu {_x000D_
list-style: none;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
/* make ALL links (main and submenu) have padding and background color */_x000D_
.mainmenu a {_x000D_
display: block;_x000D_
background-color: #CCC;_x000D_
text-decoration: none;_x000D_
padding: 10px;_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
/* add hover behaviour */_x000D_
.mainmenu a:hover {_x000D_
background-color: #C5C5C5;_x000D_
}_x000D_
_x000D_
_x000D_
/* when hovering over a .mainmenu item,_x000D_
display the submenu inside it._x000D_
we're changing the submenu's max-height from 0 to 200px;_x000D_
*/_x000D_
_x000D_
.mainmenu li:hover .submenu {_x000D_
display: block;_x000D_
max-height: 200px;_x000D_
}_x000D_
_x000D_
/*_x000D_
we now overwrite the background-color for .submenu links only._x000D_
CSS reads down the page, so code at the bottom will overwrite the code at the top._x000D_
*/_x000D_
_x000D_
.submenu a {_x000D_
background-color: #999;_x000D_
}_x000D_
_x000D_
/* hover behaviour for links inside .submenu */_x000D_
.submenu a:hover {_x000D_
background-color: #666;_x000D_
}_x000D_
_x000D_
/* this is the initial state of all submenus._x000D_
we set it to max-height: 0, and hide the overflowed content._x000D_
*/_x000D_
.submenu {_x000D_
overflow: hidden;_x000D_
max-height: 0;_x000D_
-webkit-transition: all 0.5s ease-out;_x000D_
}
_x000D_
<html>_x000D_
<body>_x000D_
<head>_x000D_
<link rel="stylesheet" type="css/text" href="nav.css">_x000D_
</head>_x000D_
</body>_x000D_
<nav class="navigation">_x000D_
<ul class="mainmenu">_x000D_
<li><a href="">Home</a></li>_x000D_
<li><a href="">About</a></li>_x000D_
<li><a href="">Products</a>_x000D_
<ul class="submenu">_x000D_
<li><a href="">Tops</a></li>_x000D_
<li><a href="">Bottoms</a></li>_x000D_
<li><a href="">Footwear</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="">Contact us</a></li>_x000D_
</ul>_x000D_
</nav>
_x000D_
With namespace declaration and schema location you can also check the syntax of the namespace use for example :-
<beans xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation= http://www.springframework.org/`enter code here`schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-driven/> <!-- This is wrong -->
<context:annotation-config/> <!-- This should work -->
Also make sure you do not wrap parentheses around your query string like so:
SELECT Name from [USER] WHERE [UserId] in (@ids)
I had this cause a SQL Syntax error using Dapper 1.50.2, fixed by removing parentheses
SELECT Name from [USER] WHERE [UserId] in @ids
You can access the index attribute of a df using .index
:
In [277]:
df = pd.DataFrame({'a':np.arange(10), 'b':np.random.randn(10)})
df
Out[277]:
a b
0 0 0.293422
1 1 -1.631018
2 2 0.065344
3 3 -0.417926
4 4 1.925325
5 5 0.167545
6 6 -0.988941
7 7 -0.277446
8 8 1.426912
9 9 -0.114189
In [278]:
df.index
Out[278]:
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')
try this.. instead of using re i think using split with strip is much better
def my_handle(self):
sentence = ' hello apple '
' '.join(x.strip() for x in sentence.split())
#hello apple
''.join(x.strip() for x in sentence.split())
#helloapple
var xyz : NSDictionary?
// case 1:
xyz = ["1":"one"]
// case 2: (empty dictionary)
xyz = NSDictionary()
// case 3: do nothing
if xyz { NSLog("xyz is not nil.") }
else { NSLog("xyz is nil.") }
This test worked as expected in all cases.
BTW, you do not need the brackets ()
.
I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:
gcc -o exec main.o add.o
But my program is a C++ program. Using the g++
compiler solved my issue:
g++ -o exec main.o add.o
I was always under the impression that gcc
could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.
You can use npm list -global
to list all the component versions currently installed on your system.
For viewing specific lists at different levels use --depth
.
e.g:
npm list -global --depth 0
You could pass a Class<T>
in.
private void foo(Class<?> cls) {
if (cls == String.class) { ... }
else if (cls == int.class) { ... }
}
private void bar() {
foo(String.class);
}
Update: the OOP way depends on the functional requirement. Best bet would be an interface defining foo()
and two concrete implementations implementing foo()
and then just call foo()
on the implementation you've at hand. Another way may be a Map<Class<?>, Action>
which you could call by actions.get(cls)
. This is easily to be combined with an interface and concrete implementations: actions.get(cls).foo()
.
Based on twitter scroll trouble (http://ejohn.org/blog/learning-from-twitter/).
Here is my solution, throttling the js scroll event (usefull for mobile devices)
JS:
$(function() {
var $document, didScroll, offset;
offset = $('.menu').position().top;
$document = $(document);
didScroll = false;
$(window).on('scroll touchmove', function() {
return didScroll = true;
});
return setInterval(function() {
if (didScroll) {
$('.menu').toggleClass('fixed', $document.scrollTop() > offset);
return didScroll = false;
}
}, 250);
});
CSS:
.menu {
background: pink;
top: 5px;
}
.fixed {
width: 100%;
position: fixed;
top: 0;
}
HTML:
<div class="menu">MENU FIXED ON TOP</div>
This worked for me as well:
Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"
This was bugging me too, since this was a standard feature in Sublime Text 2, but somehow automatic indentation no longer worked in Sublime Text 3 for HTML files.
My solution was to find the Miscellaneous.tmPreferences file from Sublime Text 2 (found under %AppData%/Roaming/Sublime Text 2/Packages/HTML) and copy those settings to the same file for ST3.
Now package handling has been made more difficult for ST3, but luckily you can just add the files to your %AppData%/Roaming/Sublime Text 3/Packages folder and they overwrite default settings in the install directory. Just save this file as "%AppData%/Roaming/Sublime Text 3/Packages/HTML/Miscellaneous.tmPreferences" and auto indent works again like it did in ST2.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>name</key>
<string>Miscellaneous</string>
<key>scope</key>
<string>text.html</string>
<key>settings</key>
<dict>
<key>decreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>batchDecreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>increaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>batchIncreaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>bracketIndentNextLinePattern</key>
<string><!DOCTYPE(?!.*>)</string>
</dict>
</dict>
</plist>
Although Martijin's answer is prob best. Here is a more intuitive way to process large csv files for beginners. This allows you to process groups of rows, or chunks, at a time.
import pandas as pd
chunksize = 10 ** 8
for chunk in pd.read_csv(filename, chunksize=chunksize):
process(chunk)
Just wanted to add, that after you remove the package in question you might also need to check to see if it's listed in the list of packages in the following area and manually remove its listing:
Preferences>Package Settings>Package Control>Settings - User
{
"auto_upgrade_last_run": null,
"installed_packages":
[
"AdvancedNewFile",
"Emmet",
"Package Control",
"SideBarEnhancements",
"Sublimerge"
]
}
In my instance, my trial period for "Sublimerge" had run out and I would get a popup every time I would start Sublime Text 2 saying:
"The package specified, Sublimerge, is not available"
I would have to close the event window out before being able to do anything in ST2.
But in my case, even after successfully removing the package through package control, I still received a event window popup message telling me "Sublimerge" wasn't available. This didn't make any sense as I had successfully removed the package.
It wasn't until I found this "auto_upgrade_last_run" file and manually removed the "Sublimerge" entry and saved my edit, did the message go away.
All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE
.
Reference: https://www.postgresql.org/docs/current/functions-matching.html
For older versions of windows (2k, 2k3, xp)
"%Userprofile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions"
Convert binary file to base64 & vice versa. Prove in python 3.5.2
import base64
read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()
b64 = base64.b64encode(data)
print (b64)
# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)
# Test in python 3.5.2
I just managed how to center icons and and making them a container instead of putting them into one.
.fas {
position: relative;
color: #EEE;
font-size: 16px;
}
.fas:before {
position: absolute;
left: calc(50% - .5em);
top: calc(50% - .5em);
}
.fas.fa-icon {
width: 60px;
height: 60px;
color: white;
background-color: black;
}
sudo chown -R $USER:$USER /var/www
new String(byteArray, Charset.defaultCharset())
This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.
From the HTML 4 spec:
If a form contains more than one submit button, only the activated submit button is successful.
This means that given more than 1 submit button and none activated (clicked), none should be successful.
And I'd argue this makes sense: Imagine a huge form with multiple submit-buttons. At the top, there is a "delete this record"-button, then lots of inputs follow and at the bottom there is an "update this record"-button. A user hitting enter while in a field at the bottom of the form would never suspect that he implicitly hits the "delete this record" from the top.
Therefore I think it is not a good idea to use the first or any other button it the user does not define (click) one. Nevertheless, browsers are doing it of course.
I was looking for something along what you wanted, but wanted to put it back into a variable.
So this is what I did
variable = ['hello this is x' x ', this is now y' y ', finally this is d:' d]
basically
variable = [str1 str2 str3 str4 str5 str6]
Perhaps this information will help you.
var sitePersonel = {};_x000D_
var employees = []_x000D_
sitePersonel.employees = employees;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var firstName = "John";_x000D_
var lastName = "Smith";_x000D_
var employee = {_x000D_
"firstName": firstName,_x000D_
"lastName": lastName_x000D_
}_x000D_
sitePersonel.employees.push(employee);_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var manager = "Jane Doe";_x000D_
sitePersonel.employees[0].manager = manager;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
console.log(JSON.stringify(sitePersonel));
_x000D_
git reset --hard
This is to revert all your local changes to the origin head
Here is how I was able to trick Excel to count expired certifications in a list. I didn't have a set date, or date range, just current date. "TODAY()" doesn't work in these for Excel 2013. It sees it as text or condition, not the date value. So these previous didn't work for me. So the word problem/scenario: How many people are expired in this list?
Use: =IFERROR(D5-TODAY(),0) Where D5 is the date to be interrogated.
Then use: =IF(J5>=1,1,0) Where J5 is the cell where the first equation is producing either a positive or negative number. This set, I have hidden on the side of the visible sheet, then I just sum the total for the number of unexpired members.
Ok guys I found a possible solution to this problem. I realized that joins do not exists in Mongo, that's why first you need to query the user's ids with the role you like, and after that do another query to the profiles document, something like this:
const exclude: string = '-_id -created_at -gallery -wallet -MaxRequestersPerBooking -active -__v';
// Get the _ids of users with the role equal to role.
await User.find({role: role}, {_id: 1, role: 1, name: 1}, function(err, docs) {
// Map the docs into an array of just the _ids
var ids = docs.map(function(doc) { return doc._id; });
// Get the profiles whose users are in that set.
Profile.find({user: {$in: ids}}, function(err, profiles) {
// docs contains your answer
res.json({
code: 200,
profiles: profiles,
page: page
})
})
.select(exclude)
.populate({
path: 'user',
select: '-password -verified -_id -__v'
// group: { role: "$role"}
})
});
A little late to the party, but hopefully this will help someone.
In C arrays always allocate memory on the stack, thus a function can't return a (non-static) array due to the fact that memory allocated on the stack gets freed automatically when the execution reaches the end of the current block. That's really annoying when you want to deal with two-dimensional arrays (i.e. matrices) and implement a few functions that can alter and return matrices. To achieve this, you could use a pointer-to-pointer to implement a matrix with dynamically allocated memory:
/* Initializes a matrix */
double** init_matrix(int num_rows, int num_cols){
// Allocate memory for num_rows float-pointers
double** A = calloc(num_rows, sizeof(double*));
// return NULL if the memory couldn't allocated
if(A == NULL) return NULL;
// For each double-pointer (row) allocate memory for num_cols floats
for(int i = 0; i < num_rows; i++){
A[i] = calloc(num_cols, sizeof(double));
// return NULL if the memory couldn't allocated
// and free the already allocated memory
if(A[i] == NULL){
for(int j = 0; j < i; j++){
free(A[j]);
}
free(A);
return NULL;
}
}
return A;
}
Here's an illustration:
double** double* double
------------- ---------------------------------------------------------
A ------> | A[0] | ----> | A[0][0] | A[0][1] | A[0][2] | ........ | A[0][cols-1] |
| --------- | ---------------------------------------------------------
| A[1] | ----> | A[1][0] | A[1][1] | A[1][2] | ........ | A[1][cols-1] |
| --------- | ---------------------------------------------------------
| . | .
| . | .
| . | .
| --------- | ---------------------------------------------------------
| A[i] | ----> | A[i][0] | A[i][1] | A[i][2] | ........ | A[i][cols-1] |
| --------- | ---------------------------------------------------------
| . | .
| . | .
| . | .
| --------- | ---------------------------------------------------------
| A[rows-1] | ----> | A[rows-1][0] | A[rows-1][1] | ... | A[rows-1][cols-1] |
------------- ---------------------------------------------------------
The double-pointer-to-double-pointer A
points to the first element A[0]
of a
memory block whose elements are double-pointers itself. You can imagine these
double-pointers as the rows of the matrix. That's the reason why every
double-pointer allocates memory for num_cols elements of type double.
Furthermore A[i]
points to the i-th row, i.e. A[i]
points to A[i][0]
and
that's just the first double-element of the memory block for the i-th row.
Finally, you can access the element in the i-th row
and j-th column easily with A[i][j]
.
Here's a complete example that demonstrates the usage:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Initializes a matrix */
double** init_matrix(int num_rows, int num_cols){
// Allocate memory for num_rows double-pointers
double** matrix = calloc(num_rows, sizeof(double*));
// return NULL if the memory couldn't allocated
if(matrix == NULL) return NULL;
// For each double-pointer (row) allocate memory for num_cols
// doubles
for(int i = 0; i < num_rows; i++){
matrix[i] = calloc(num_cols, sizeof(double));
// return NULL if the memory couldn't allocated
// and free the already allocated memory
if(matrix[i] == NULL){
for(int j = 0; j < i; j++){
free(matrix[j]);
}
free(matrix);
return NULL;
}
}
return matrix;
}
/* Fills the matrix with random double-numbers between -1 and 1 */
void randn_fill_matrix(double** matrix, int rows, int cols){
for (int i = 0; i < rows; ++i){
for (int j = 0; j < cols; ++j){
matrix[i][j] = (double) rand()/RAND_MAX*2.0-1.0;
}
}
}
/* Frees the memory allocated by the matrix */
void free_matrix(double** matrix, int rows, int cols){
for(int i = 0; i < rows; i++){
free(matrix[i]);
}
free(matrix);
}
/* Outputs the matrix to the console */
void print_matrix(double** matrix, int rows, int cols){
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
printf(" %- f ", matrix[i][j]);
}
printf("\n");
}
}
int main(){
srand(time(NULL));
int m = 3, n = 3;
double** A = init_matrix(m, n);
randn_fill_matrix(A, m, n);
print_matrix(A, m, n);
free_matrix(A, m, n);
return 0;
}
In Support Library 27.1.0 and later, Google has introduced new methods requireContext()
and requireActivity()
methods.
Eg:ContextCompat.getColor(requireContext(), R.color.soft_gray)
More info here
Since you mention synaptic I think you're on Ubuntu. You probably need to run update-python-modules to update your Tkinter module for Python 3.
EDIT: Running update-python-modules
First, make sure you have python-support
installed:
sudo apt-get install python-support
Then, run update-python-modules
with the -a
option to rebuild all the modules:
sudo update-python-modules -a
I cannot guarantee all your modules will build though, since there are some API changes between Python 2 and Python 3.
A possible alternative for that:
Use an encoder (e.g. VLC or FFmpeg) into packetize your input stream to OGG format. For example, in this case I used VLC to packetize screen capture device with this code:
C:\Program Files\VideoLAN\VLC\vlc.exe -I dummy screen:// :screen-fps=16.000000 :screen-caching=100 :sout=#transcode{vcodec=theo,vb=800,scale=1,width=600,height=480,acodec=mp3}:http{mux=ogg,dst=127.0.0.1:8080/desktop.ogg} :no-sout-rtp-sap :no-sout-standard-sap :ttl=1 :sout-keep
Embed this code into a <video>
tag in your HTML page like that:
<video id="video" src="http://localhost:8080/desktop.ogg" autoplay="autoplay" />
This should do the trick. However it's kind of poor performance and AFAIK MP4 container type should have a better support among browsers than OGG.
Looks like you got what you need from @matt, but if you want a quick way to get a value for a key, or just the first value if that key doesn’t exist:
extension Dictionary {
func keyedOrFirstValue(key: Key) -> Value? {
// if key not found, replace the nil with
// the first element of the values collection
return self[key] ?? first(self.values)
// note, this is still an optional (because the
// dictionary could be empty)
}
}
let d = ["one":"red", "two":"blue"]
d.keyedOrFirstValue("one") // {Some "red"}
d.keyedOrFirstValue("two") // {Some "blue"}
d.keyedOrFirstValue("three") // {Some "red”}
Note, no guarantees what you'll actually get as the first value, it just happens in this case to return “red”.
When your browser redirects the user to Google's oAuth page, are you passing as a parameter the redirect URI you want Google's server to return to with the token response? Setting a redirect URI in the console is not a way of telling Google where to go when a login attempt comes in, but rather it's a way of telling Google what the allowed redirect URIs are (so if someone else writes a web app with your client ID but a different redirect URI it will be disallowed); your web app should, when someone clicks the "login" button, send the browser to:
https://accounts.google.com/o/oauth2/auth?client_id=XXXXX&redirect_uri=http://localhost:8080/WEBAPP/youtube-callback.html&response_type=code&scope=https://www.googleapis.com/auth/youtube.upload
(the callback URI passed as a parameter must be url-encoded, btw).
When Google's server gets authorization from the user, then, it'll redirect the browser to whatever you sent in as the redirect_uri
. It'll include in that request the token as a parameter, so your callback page can then validate the token, get an access token, and move on to the other parts of your app.
If you visit:
http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow
You can see better samples of the java client there, demonstrating that you have to override the getRedirectUri
method to specify your callback path so the default isn't used.
The redirect URIs are in the client_secrets.json
file for multiple reasons ... one big one is so that the oAuth flow can verify that the redirect your app specifies matches what your app allows.
If you visit https://developers.google.com/api-client-library/java/apis/youtube/v3 You can generate a sample application for yourself that's based directly off your app in the console, in which (again) the getRedirectUri method is overwritten to use your specific callbacks.
You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.
So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded
event or functions like $.ready
in jQuery.
Here is a tweak of McDowell's algorithm that doesn't pad the result:
function toHex(str) {
var result = '';
for (var i=0; i<str.length; i++) {
result += str.charCodeAt(i).toString(16);
}
return result;
}
It is used in the new short hand for/loop
final List<String> list = new ArrayList<String>();
for (final String s : list)
{
System.out.println(s);
}
and the ternary operator
list.isEmpty() ? true : false;
Late to the conversation...
But, why not use css? That way you can keep the button as a submit type.
html:
<input type="submit" value="go" />
css:
button, input[type="submit"] {
background:url(/images/submit.png) no-repeat;"
}
Works like a charm.
EDIT: If you want to remove the default button styles, you can use the following css:
button, input[type="submit"]{
color: inherit;
border: none;
padding: 0;
font: inherit;
cursor: pointer;
outline: inherit;
}
from this SO question
Internal will allow you to reference, say, a Data Access static class (for thread safety) between multiple business logic classes, while not subscribing them to inherit that class/trip over each other in connection pools, and to ultimately avoid allowing a DAL class to promote access at the public level. This has countless backings in design and best practices.
Entity Framework makes good use of this type of access
We can use refs in another way as-
We are going to create a Parent element, it will render a <Child/>
component. As you can see, the component that will be rendered, you need to add the ref attribute and provide a name for it.
Then, the triggerChildAlert
function, located in the parent class will access the refs property of the this context (when the triggerChildAlert
function is triggered will access the child reference and it will has all the functions of the child element).
class Parent extends React.Component {
triggerChildAlert(){
this.refs.child.callChildMethod();
// to get child parent returned value-
// this.value = this.refs.child.callChildMethod();
// alert('Returned value- '+this.value);
}
render() {
return (
<div>
{/* Note that you need to give a value to the ref parameter, in this case child*/}
<Child ref="child" />
<button onClick={this.triggerChildAlert}>Click</button>
</div>
);
}
}
Now, the child component, as theoretically designed previously, will look like:
class Child extends React.Component {
callChildMethod() {
alert('Hello World');
// to return some value
// return this.state.someValue;
}
render() {
return (
<h1>Hello</h1>
);
}
}
Here is the source code-
Hope will help you !
The given answer will throw an error if used in Microsoft Excel 14.0 Object Library. Object does not contain a definition for get_range. Instead use
int countRows = xlWorkSheetData.UsedRange.Rows.Count;
int countColumns = xlWorkSheetData.UsedRange.Columns.Count;
object[,] data = xlWorkSheetData.Range[xlWorkSheetData.Cells[1, 1], xlWorkSheetData.Cells[countRows, countColumns]].Cells.Value2;
I do this often and use a simple 5 line prototype that accepts varargs. It is fast and works everywhere.
myString.containsIgnoreCase('red','orange','yellow')
/**_x000D_
* @param {...string} var_strings Strings to search for_x000D_
* @return {boolean} true if ANY of the arguments is contained in the string_x000D_
*/_x000D_
String.prototype.containsIgnoreCase = function(var_strings) {_x000D_
const thisLowerCase = this.toLowerCase()_x000D_
for (let i = 0; i < arguments.length; i++) {_x000D_
let needle = arguments[i]_x000D_
if (thisLowerCase.indexOf(needle.toLowerCase()) >= 0) {_x000D_
return true_x000D_
}_x000D_
}_x000D_
return false_x000D_
}_x000D_
_x000D_
/**_x000D_
* @param {...string} var_strings Strings to search for_x000D_
* @return {boolean} true if ALL of the arguments are contained in the string_x000D_
*/_x000D_
String.prototype.containsAllIgnoreCase = function(var_strings) {_x000D_
const thisLowerCase = this.toLowerCase()_x000D_
for (let i = 0; i < arguments.length; i++) {_x000D_
let needle = arguments[i]_x000D_
if (thisLowerCase.indexOf(needle.toLowerCase()) === -1) {_x000D_
return false_x000D_
}_x000D_
}_x000D_
return true_x000D_
}_x000D_
_x000D_
// Unit test_x000D_
_x000D_
let content = `_x000D_
FIRST SECOND_x000D_
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."_x000D_
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."_x000D_
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."_x000D_
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."_x000D_
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."_x000D_
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."_x000D_
FOO BAR_x000D_
`_x000D_
_x000D_
let data = [_x000D_
'foo',_x000D_
'Foo',_x000D_
'foobar',_x000D_
'barfoo',_x000D_
'first',_x000D_
'second'_x000D_
]_x000D_
_x000D_
let result_x000D_
data.forEach(item => {_x000D_
console.log('Searching for', item)_x000D_
result = content.containsIgnoreCase(item)_x000D_
console.log(result ? 'Found' : 'Not Found')_x000D_
})_x000D_
_x000D_
console.log('Searching for', 'x, y, foo')_x000D_
result = content.containsIgnoreCase('x', 'y', 'foo');_x000D_
console.log(result ? 'Found' : 'Not Found')_x000D_
_x000D_
console.log('Searching for all', 'foo, bar, foobar')_x000D_
result = content.containsAllIgnoreCase('foo', 'bar', 'foobar');_x000D_
console.log(result ? 'Found' : 'Not Found')_x000D_
_x000D_
console.log('Searching for all', 'foo, bar')_x000D_
result = content.containsAllIgnoreCase('foo', 'bar');_x000D_
console.log(result ? 'Found' : 'Not Found')
_x000D_
This is the code I usually do:
try
{
...........
throw null;//this line just works like a 'break'
...........
}
catch (NullReferenceException)
{
}
catch (System.Exception ex)
{
.........
}
Yes - different
chmod a+x
will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others
and group
.
chmod 755
will always make the file with perms 755
no matter what initial permissions were.
This may or may not matter for your script.
in python intended block mean there is every thing must be written in manner in my case I written it this way
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_input.set(operator)
Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code
def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)
If you want to convert any DataTable to a equivalent IEnumerable vector function.
Please take a look at the following generic function, this may help your needs (you may need to include write cases for different datatypes based on your needs).
/// <summary>
/// Get entities from DataTable
/// </summary>
/// <typeparam name="T">Type of entity</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public IEnumerable<T> GetEntities<T>(DataTable dt)
{
if (dt == null)
{
return null;
}
List<T> returnValue = new List<T>();
List<string> typeProperties = new List<string>();
T typeInstance = Activator.CreateInstance<T>();
foreach (DataColumn column in dt.Columns)
{
var prop = typeInstance.GetType().GetProperty(column.ColumnName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
if (prop != null)
{
typeProperties.Add(column.ColumnName);
}
}
foreach (DataRow row in dt.Rows)
{
T entity = Activator.CreateInstance<T>();
foreach (var propertyName in typeProperties)
{
if (row[propertyName] != DBNull.Value)
{
string str = row[propertyName].GetType().FullName;
if (entity.GetType().GetProperty(propertyName).PropertyType == typeof(System.String))
{
object Val = row[propertyName].ToString();
entity.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).SetValue(entity, Val, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, null, null);
}
else if (entity.GetType().GetProperty(propertyName).PropertyType == typeof(System.Guid))
{
object Val = Guid.Parse(row[propertyName].ToString());
entity.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).SetValue(entity, Val, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, null, null);
}
else
{
entity.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).SetValue(entity, row[propertyName], BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, null, null);
}
}
else
{
entity.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).SetValue(entity, null, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, null, null);
}
}
returnValue.Add(entity);
}
return returnValue.AsEnumerable();
}
A cookie key(used to identify a session) and a cookie are the same thing being used in different ways. So the limit would be the same. According to Microsoft its 4096 bytes.
cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.
I have the same issue as you did. I think the problem is that you used relative import in in-package import
. There is no __init__.py
in your directory. So just import as Moses answered above.
The core issue I think is when you import with a dot:
from .p_02_paying_debt_off_in_a_year import compute_balance_after
It is equivalent to:
from __main__.p_02_paying_debt_off_in_a_year import compute_balance_after
where __main__
refers to your current module p_03_using_bisection_search.py
.
Briefly, the interpreter does not know your directory architecture.
When the interpreter get in p_03.py
, the script equals:
from p_03_using_bisection_search.p_02_paying_debt_off_in_a_year import compute_balance_after
and p_03_using_bisection_search
does not contain any modules or instances called p_02_paying_debt_off_in_a_year
.
So I came up with a cleaner solution without changing python environment valuables (after looking up how requests do in relative import):
The main architecture of the directory is:
main.py
setup.py
problem_set_02/
__init__.py
p01.py
p02.py
p03.py
Then write in __init__.py
:
from .p_02_paying_debt_off_in_a_year import compute_balance_after
Here __main__
is __init__
, it exactly refers to the module problem_set_02
.
Then go to main.py
:
import problem_set_02
You can also write a setup.py
to add specific module to the environment.
Just to phrase things differently from the great answers above, as that has helped me get an intuitive understanding of negative margins:
A negative margin on an element allows it to eat up the space of its parent container.
Adding a (positive) margin on the bottom doesn't allow the element to do that - it only pushes back whatever element is below.
IE9 currently lacks CSS3 gradient support. However, here is a nice workaround solution using PHP to return an SVG (vertical linear) gradient instead, which allows us to keep our design in our stylesheets.
<?php
$from_stop = isset($_GET['from']) ? $_GET['from'] : '000000';
$to_stop = isset($_GET['to']) ? $_GET['to'] : '000000';
header('Content-type: image/svg+xml; charset=utf-8');
echo '<?xml version="1.0"?>
';
?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%">
<defs>
<linearGradient id="linear-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#<?php echo $from_stop; ?>" stop-opacity="1"/>
<stop offset="100%" stop-color="#<?php echo $to_stop; ?>" stop-opacity="1"/>
</linearGradient>
</defs>
<rect width="100%" height="100%" fill="url(#linear-gradient)"/>
</svg>
Simply upload it to your server and call the URL like so:
gradient.php?from=f00&to=00f
This can be used in conjunction with your CSS3 gradients like this:
.my-color {
background-color: #f00;
background-image: url(gradient.php?from=f00&to=00f);
background-image: -webkit-gradient(linear, left top, left bottom, from(#f00), to(#00f));
background-image: -webkit-linear-gradient(top, #f00, #00f);
background-image: -moz-linear-gradient(top, #f00, #00f);
background-image: linear-gradient(top, #f00, #00f);
}
If you need to target below IE9, you can still use the old proprietary 'filter' method:
.ie7 .my-color, .ie8 .my-color {
filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr="#ff0000", endColorStr="#0000ff");
}
Of course you can amend the PHP code to add more stops on the gradient, or make it more sophisticated (radial gradients, transparency etc.) but this is great for those simple (vertical) linear gradients.
You can export a pfx from IIS on another server, if you have a server with the cert successfully installed.
Update:
Working on another round of certificate updates (a renewal) I ran into this problem again, on every server I tried. @Geir's answer didn't work, but it did give me an idea. I identified the server where I had generated the Certificate Request and successfully installed the new cert there. From that server I was able to export a pfx and then import the pfx version on the rest of the servers. No need to redo the Cert Request.
There are three main reasons for using the assert() function over the normal if else and printf
assert() function is mainly used in the debugging phase, it is tedious to write if else with a printf statement everytime you want to test a condition which might not even make its way in the final code.
In large software deployments , assert comes very handy where you can make the compiler ignore the assert statements using the NDEBUG macro defined before linking the header file for assert() function.
assert() comes handy when you are designing a function or some code and want to get an idea as to what limits the code will and not work and finally include an if else for evaluating it basically playing with assumptions.
The only easy way to do this is to use snprintf
to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:
char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);
This is an inverted version of @Jeff's answer* where a hidden character (U+115F, U+1160 or U+3164) is used to create variables that look like 1
, 2
and 3
.
var a = 1;_x000D_
var ?1 = a;_x000D_
var ?2 = a;_x000D_
var ?3 = a;_x000D_
console.log( a ==?1 && a ==?2 && a ==?3 );
_x000D_
* That answer can be simplified by using zero width non-joiner (U+200C) and zero width joiner (U+200D). Both of these characters are allowed inside identifiers but not at the beginning:
var a = 1;_x000D_
var a? = 2;_x000D_
var a? = 3;_x000D_
console.log(a == 1 && a? == 2 && a? == 3);_x000D_
_x000D_
/****_x000D_
var a = 1;_x000D_
var a\u200c = 2;_x000D_
var a\u200d = 3;_x000D_
console.log(a == 1 && a\u200c == 2 && a\u200d == 3);_x000D_
****/
_x000D_
Other tricks are possible using the same idea e.g. by using Unicode variation selectors to create variables that look exactly alike (a? = 1; a? = 2; a? == 1 && a? == 2; // true
).
VAR1=value1 VAR2=value2 myScript args ...
Basically we can create spring container object in two ways
both are the interfaces,
using implementation classes we can create object for spring container
coming to the differences
BeanFactory :
Does not support the Annotation based dependency Injection.
Doesn't Support I18N.
By default its support Lazy loading.
it doesn't allow configure to multiple configuration files.
ex: BeanFactory context=new XmlBeanFactory(new Resource("applicationContext.xml"));
ApplicationContext
Support Annotation based dependency Injection.-@Autowired, @PreDestroy
Support I18N
Its By default support Aggresive loading.
It allow to configure multiple configuration files.
ex:
ApplicationContext context=new ClasspathXmlApplicationContext("applicationContext.xml");
When rewriting the html is allowed, you can nest <ul>
s within the <ul>
and just let the inner <li>
s display as inline-block. This would also semantically make sense IMHO, as the grouping also is reflected within the html.
<ul>
<li>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</li>
<li>
<ul>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
</li>
</ul>
li li { display:inline-block; }
$(function() { $('img').attr('src', 'http://phrogz.net/tmp/alphaball.png'); });
_x000D_
h3 {_x000D_
border-bottom: 1px solid #ccc;_x000D_
font-family: sans-serif;_x000D_
font-weight: bold;_x000D_
}_x000D_
ul {_x000D_
margin: 0.5em auto;_x000D_
list-style-type: none;_x000D_
}_x000D_
li li {_x000D_
text-align: center;_x000D_
display: inline-block;_x000D_
padding: 0.1em 1em;_x000D_
}_x000D_
img {_x000D_
width: 64px;_x000D_
display: block;_x000D_
margin: 0 auto;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<h3>Features</h3>_x000D_
<ul>_x000D_
<li>_x000D_
<ul>_x000D_
<li><img />Smells Good</li>_x000D_
<li><img />Tastes Great</li>_x000D_
<li><img />Delicious</li>_x000D_
</ul>_x000D_
</li>_x000D_
<li>_x000D_
<ul>_x000D_
<li><img />Wholesome</li>_x000D_
<li><img />Eats Children</li>_x000D_
<li><img />Yo' Mama</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>
_x000D_
Super simple answer that will apply to most cases is to just make set the margin to 0 auto
and set the display to block
. You can see how I centered my button in my demo on CodePen
In Swift 3, you can simply change the title of a button by:
button.setTitle("Title", for: .normal)
and you disable the button by:
button.isEnabled = false
.normal
is the same as UIControlState.normal
because the type is inferred.
My solution to show .svg in UIImageView from URL. You need to install SVGKit pod
Then just use it like this:
import SVGKit
let svg = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!
let data = try? Data(contentsOf: svg)
let receivedimage: SVGKImage = SVGKImage(data: data)
imageview.image = receivedimage.uiImage
or you can use extension for async download
extension UIImageView {
func downloadedsvg(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let receivedicon: SVGKImage = SVGKImage(data: data),
let image = receivedicon.uiImage
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
}
How to use:
let svg = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!
imageview.downloadedsvg(from: svg)
Unless you absolutely have to convert the date to an integer, consider using a Double
instead to represent the time interval. After all, this is the type that timeIntervalSince1970
returns. All of the answers that convert to integers loose sub-millisecond precision, but this solution is much more accurate (although you will still lose some precision due to floating-point imprecision).
public extension Date {
/// The interval, in milliseconds, between the date value and
/// 00:00:00 UTC on 1 January 1970.
/// Equivalent to `self.timeIntervalSince1970 * 1000`.
var millisecondsSince1970: Double {
return self.timeIntervalSince1970 * 1000
}
/**
Creates a date value initialized relative to 00:00:00 UTC
on 1 January 1970 by a given number of **milliseconds**.
equivalent to
```
self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
```
- Parameter millisecondsSince1970: A time interval in milliseconds.
*/
init(millisecondsSince1970: Double) {
self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
}
}
enum A { foo, bar } a;
a = foo;
printf( "%d", a ); // see comments below
let storyboard = UIStoryboard(name: "StoryboardFileName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "StoryboardID")
self.present(controller, animated: true, completion: nil)
Note:
"StoryboardFileName"
is the filename of the Storyboard and not the ID of the storyboard!"StoryboardID"
is the ID you have manually set in the identity inspector for that storyboard (see screenshot below). Sometimes people believe that the first one is the Storyboard ID and the second one the View Controller class name, so note the difference.
You can plot multiple subplots of multiple pandas data frames using matplotlib with a simple trick of making a list of all data frame. Then using the for loop for plotting subplots.
Working code:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# dataframe sample data
df1 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df2 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df3 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df4 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df5 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df6 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
#define number of rows and columns for subplots
nrow=3
ncol=2
# make a list of all dataframes
df_list = [df1 ,df2, df3, df4, df5, df6]
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
for c in range(ncol):
df_list[count].plot(ax=axes[r,c])
count=+1
Using this code you can plot subplots in any configuration. You need to just define number of rows nrow
and number of columns ncol
. Also, you need to make list of data frames df_list
which you wanted to plot.
Here's some code from Excel 2010 that may work. It has a couple specifics (like filtering bad-encode characters from titles) but it was designed to create multiple multi-series graphs from 4-dimensional data having both absolute and percentage-based data. Modify it how you like:
Sub createAllGraphs()
Const chartWidth As Integer = 260
Const chartHeight As Integer = 200
If Sheets.Count = 1 Then
Sheets.Add , Sheets(1)
Sheets(2).Name = "AllCharts"
ElseIf Sheets("AllCharts").ChartObjects.Count > 0 Then
Sheets("AllCharts").ChartObjects.Delete
End If
Dim c As Variant
Dim c2 As Variant
Dim cs As Object
Set cs = Sheets("AllCharts")
Dim s As Object
Set s = Sheets(1)
Dim i As Integer
Dim chartX As Integer
Dim chartY As Integer
Dim r As Integer
r = 2
Dim curA As String
curA = s.Range("A" & r)
Dim curB As String
Dim curC As String
Dim startR As Integer
startR = 2
Dim lastTime As Boolean
lastTime = False
Do While s.Range("A" & r) <> ""
If curC <> s.Range("C" & r) Then
If r <> 2 Then
seriesAdd:
c.SeriesCollection.Add s.Range("D" & startR & ":E" & (r - 1)), , False, True
c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
c.SeriesCollection(c.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).Values = "='" & s.Name & "'!$E$" & startR & ":$E$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True
c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select
c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1), minusvalues:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
c2.SeriesCollection.Add s.Range("D" & startR & ":D" & (r - 1) & ",G" & startR & ":G" & (r - 1)), , False, True
c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
c2.SeriesCollection(c2.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).Values = "='" & s.Name & "'!$G$" & startR & ":$G$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1), minusvalues:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
If lastTime = True Then GoTo postLoop
End If
If curB <> s.Range("B" & r).Value Then
If curA <> s.Range("A" & r).Value Then
chartX = chartX + chartWidth * 2
chartY = 0
curA = s.Range("A" & r)
End If
Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)
Set c = c.Chart
c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r), s.Range("D1"), s.Range("E1")
Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)
Set c2 = c2.Chart
c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r) & " (%)", s.Range("D1"), s.Range("G1")
chartY = chartY + chartHeight
curB = s.Range("B" & r)
curC = s.Range("C" & r)
End If
curC = s.Range("C" & r)
startR = r
End If
If s.Range("A" & r) <> "" Then oneMoreTime = False ' end the loop for real this time
r = r + 1
Loop
lastTime = True
GoTo seriesAdd
postLoop:
cs.Activate
End Sub
You can't do a sleep like that in JavaScript, or, rather, you shouldn't. Running a sleep or a while loop will cause the user's browser to hang until the loop is done.
Use a timer, as specified in the link you referenced.
You want this:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
The YAML equivalent of a JSON object is a mapping, which looks like these:
# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2
Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:
# OK
foo: 1
bar: 2
# Parse error
foo: 1
bar: 2
The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):
# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz
In a block sequence the -
s must be in the same column.
Let's turn your JSON into YAML. Here's your JSON:
{"AAPL": [
{
"shares": -75.088,
"date": "11/27/2015"
},
{
"shares": 75.088,
"date": "11/26/2015"
},
]}
As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.
Starting from the inside out, we have objects that look like this:
{
"shares": -75.088,
"date": "11/27/2015"
}
The equivalent YAML mapping is:
shares: -75.088
date: 11/27/2015
We have two of these in an array (sequence):
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Note how the -
s line up and the first characters of the mapping keys line up.
Finally, this sequence is itself a value in a mapping with the key AAPL
:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Parsing this and converting it back to JSON yields the expected result:
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
You can see it (and edit it interactively) here.
In addition to the 3 floated column structure (which I would suggest as well), you have to insert a clearfix to prevent layoutproblems with elements after the columncontainer (keep the columncontainer in the flow, so to speak...).
<div id="contentBox" class="clearfix">
....
</div>
CSS:
.clearfix { zoom: 1; }
.clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; }
.clearfix:after { clear: both; }
You're seeing firsthand one of the cons of Lua having only one data structure---you have to roll your own. If you stick with Lua you will gradually accumulate a library of functions that manipulate tables in the way you like to do things. My library includes a list-to-set conversion and a higher-order list-searching function:
function table.set(t) -- set of list
local u = { }
for _, v in ipairs(t) do u[v] = true end
return u
end
function table.find(f, l) -- find element v of l satisfying f(v)
for _, v in ipairs(l) do
if f(v) then
return v
end
end
return nil
end
For anyone learning this stuff, comments are more important, so drawing on Xak Tacit's idea
(from User500099's link) for Single Property comments, add this to the top of the XAML code block:
<!--Comments Allowed With Markup Compatibility (mc) In XAML!
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
Usage in property:
ØignoreØ:AttributeToIgnore="Text Of AttributeToIgnore"-->
Then in the code block
<Application FooApp:Class="Foo.App"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
...
AttributeNotToIgnore="TextNotToIgnore"
...
...
ØignoreØ:IgnoreThisAttribute="IgnoreThatText"
...
>
</Application>
a = ['1', '2', '3', '4']
print len(a) - 1
3
If you are using MySQL interactively, you can set your pager to use sed
like this:
$ mysql -u <user> p<password>
mysql> pager sed 's/,/\n/g'
PAGER set to 'sed 's/,/\n/g''
mysql> SELECT blah FROM blah WHERE blah = blah
.
.
.
"blah":"blah"
"blah":"blah"
"blah":"blah"
If you don't use sed
as the pager, the output is like this:
"blah":"blah","blah":"blah","blah":"blah"
How to create FLUTTER project in android studio in fedora:-
I have installed following:- 1 Android studio 2 Then do following:-
Start Android Studio. Open plugin preferences (Preferences > Plugins on macOS, File > Settings > Plugins on Windows & Linux). Select Marketplace, select the Flutter plugin and click Install. Click Yes when prompted to install the Dart plugin. Click Restart when prompted.
4:- Now create project by clicking new flutter project and do following:- * Choose Flutter Application from the list of configurations * Fill the name and other things * For flutter sdk click and install flutter sdk and specify the location of downloading and after downloading completion, choose that sdk path, this will load your FLutter sdk.
Rest do steps as per your need to create project
when the object is empty return this error:
Uncaught TypeError: Cannot read property '0' of null
I try this code :
try{
if ($("#btext" + i).length) {};
}catch(err){
if ($("#btext" + i).length) {
//working this code if the item, not NULL
}
}
We can take a simple example.
Consider a table named TableA
with the following values:
id firstname lastname Mark
-------------------------------------------------------------------
1 arun prasanth 40
2 ann antony 45
3 sruthy abc 41
6 new abc 47
1 arun prasanth 45
1 arun prasanth 49
2 ann antony 49
GROUP BY
The SQL GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns.
In more simple words GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.
Syntax:
SELECT expression1, expression2, ... expression_n,
aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;
We can apply GROUP BY
in our table:
select SUM(Mark)marksum,firstname from TableA
group by id,firstName
Results:
marksum firstname
----------------
94 ann
134 arun
47 new
41 sruthy
In our real table we have 7 rows and when we apply GROUP BY id
, the server group the results based on id
:
In simple words:
here
GROUP BY
normally reduces the number of rows returned by rolling them up and calculatingSum()
for each row.
PARTITION BY
Before going to PARTITION BY, let us look at the OVER
clause:
According to the MSDN definition:
OVER clause defines a window or user-specified set of rows within a query result set. A window function then computes a value for each row in the window. You can use the OVER clause with functions to compute aggregated values such as moving averages, cumulative aggregates, running totals, or a top N per group results.
PARTITION BY will not reduce the number of rows returned.
We can apply PARTITION BY in our example table:
SELECT SUM(Mark) OVER (PARTITION BY id) AS marksum, firstname FROM TableA
Result:
marksum firstname
-------------------
134 arun
134 arun
134 arun
94 ann
94 ann
41 sruthy
47 new
Look at the results - it will partition the rows and returns all rows, unlike GROUP BY.
Use of Ascyimageview you can easy load imageurl in imageview.
let image1Url:URL = URL(string: "(imageurl)" as String)! imageview.imageURL = image1Url